How to change icon in tkinter [duplicate] - python

This question already has answers here:
Changing the application and taskbar icon - Python/Tkinter
(7 answers)
Closed 1 year ago.
#MY Code
from tkinter import *
root = Tk()
root.geometry("1200x700")
root.title("MY_OS LOGIN/REGISTER")
icon=PhotoImage("C:\\Users\\Malay\\Desktop\\Main\\malay\\Python Scripts\\My OS GUI\\favicon.ico")
root.iconphoto(True,icon)
#Error I'm facing
Traceback (most recent call last):
File "C:\Users\Malay\Desktop\Main\malay\Python Scripts\My OS GUI\main.py", line 35, in
root.iconphoto(True,icon)
File "C:\Users\Malay\AppData\Local\Programs\Python\Python39\lib\tkinter_init_.py", line 2125, in wm_iconphoto
self.tk.call('wm', 'iconphoto', self._w, "-default", *args)
tkinter.TclError: failed to create color bitmap for "C:\Users\Malay\Desktop\Main\malay\Python Scripts\My OS GUI\favicon.ico"enter code here

To change the window icon in a tkinter application:
Add this piece of code
root.iconbitmap("yourimage.ico")

There appears to be two reasons this is not working. First PhotoImage does not work with the .ico file type. Second, the file name is a keyword argument, so your code should look like this.
#MY Code
from tkinter import *
root = Tk()
root.geometry("1200x700")
root.title("MY_OS LOGIN/REGISTER")
# Comment out incorrect file type
# icon=PhotoImage(file="C:\\Users\\Malay\\Desktop\\Main\\malay\\Python Scripts\\My OS GUI\\favicon.ico")
# Using keyword file and using a png
icon=PhotoImage(file="C:\\Users\\Malay\\Desktop\\Main\\malay\\Python Scripts\\My OS GUI\\favicon.png")
root.iconphoto(True,icon)

Related

When opining a PDF with Python tkPDFViewer throws an error, is there an mistake I'm not seeing?

When testing the opening of a PDF for a larger project the code throws an error. The error emanates from the tkPDFViewer.
Any ideas?
Here is the error:
Exception in thread Thread-1 (add_img): Traceback (most recent call last):
File "C:\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run()
File "C:\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, *self._kwargs)
File "C:\Python\Python310\lib\site-packages\tkPDFViewer\tkPDFViewer.py", line 46, in add_img
pix = page.getPixmap()
AttributeError: 'Page' object has no attribute 'getPixmap'. Did you mean: 'get_pixmap'?
import tkinter as tk
from tkPDFViewer import tkPDFViewer as pdf
print('Starting TestPDF2')
mainWindow = tk.Tk()
# Set the width and height of our root window.
mainWindow.geometry("550x750")
# creating object of ShowPdf from tkPDFViewer.
v1 = pdf.ShowPdf()
# Adding pdf location and width and height.
v2 = v1.pdf_view(mainWindow, pdf_location = 'testpdf.pdf', width = 50, height = 100)
# Placing Pdf in my gui.
v2.pack()
mainWindow.mainloop()
print('End TestPDF2')
This is an internal problem with tkPDFViewer. The error is quite self-explanatory - getPixmap was deprecated and removed in favor of get_pixmap in one of the dependencies of tkPDFViewer (see here). So the library needs to get fixed (the methods need to be renamed to match the new version) and it doesn't look very well maintained. You can try opening an issue or a PR on its GitHub. But I'd probably lean towards saying this library is dead and broken, and finding yourself an alternative that works.

Was told to use select method of tkinter Checkbutton. It doesn't work. How do I have it chacked if the stored setting is true?

I'm trying to make a GUI for my app, but I have hit a roadblock when trying to make a settings Toplevel. This Toplevel comes with tabs and setting buttons that start at the same state their respective settings are stored as from last settings/defaults.
Here is the exception I am currently getting:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 1885, in __call__
return self.func(*args)
File "KMIU 4\kmiu_dv7.pyw", line 38, in settings
sett.display(main)
File "KMIU 4\bk\settings.py", line 54, in __init__
self.windowsettings(tab2)
File "KMIU 4\bk\settings.py", line 23, in windowsettings
if settings['Fullscreen'].get(): fs_butt.select()
AttributeError: 'Checkbutton' object has no attribute 'select'
Here is the bit of code that is causing the issue:
def windowsettings(self, tab):
global settings
text = Label(tab, text ="sample text")
text.grid(columnspan = 2)
fs_butt = Checkbutton(
tab,
text="Fullscreen",
command=lambda: settings['Fullscreen'].set(not settings['Fullscreen'].get()))
print(settings)
fs_butt.grid(row=1)
if settings['Fullscreen'].get(): fs_butt.select()
For me in my code with tk.Checkbutton, select() works, and ive seen some other people having the same issue, not sure whats causing it(maybe your using ttk.Checkbutton), but here is a way around:
First assign a BooleanVar() to your checkbutton:
var = BooleanVar()
....
fs_butt = Checkbutton(tab,variable=var,......) #same for ttk.Checkbutton(..) too
Now to set the value of the variable to True, to select, and False to deselect:
if settings['Fullscreen'].get():
var.set(True)
Or maybe your using ttk.Checkbutton which does not have select() and deselect()

Unable to pass location of input and output to an extenal command using User-Interface in python

I am completely new to python.
I am trying to pass the location of Input and output using User interface as shown in this particular discussion [1]:How to give the location of "Input" and "Output" for a python code using User Interface and run the code from UI itself?
But here, I am calling an external command and trying to run it from my python code by passing location of input and output as in the above mentioned case.
from tkinter import *
from tkinter import filedialog
import numpy as np
import gdal
gdal.UseExceptions()
import os
def your_code(input_file, intermediate_file, output_file):
cmd = "gpt F:\saikiran\myGraph.xml -Psource=input_file - Ptarget=intermediate_file"
os.system(cmd)
ds = gdal.Open(intermediate_file)
band = ds.GetRasterBand(1)
……………………………………………...
#gen_map_button.place(x=230, y=300)
gen_map_button.pack()
root.mainloop()
But I encountered with this error :
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\User\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\User\GUI-pywt.py", line 145, in gen_map
your_code(input_filename, intermediate_filename, output_filename)
File "C:\Users\User\GUI-pywt.py", line 15, in your_code
ds = gdal.Open(intermediate_file)
File "C:\Users\User\Anaconda3\lib\site-packages\osgeo\gdal.py", line 3251, in Open
return _gdal.Open(*args)
RuntimeError: F:/saikiran/ddd: No such file or directory
What mistake did i do ?
Your cmd is not correct.
Concatenate string with values
cmd = "gpt F:\saikiran\myGraph.xml -Psource=" + input_file + " - Ptarget=" + intermediate_file
or use string formatting
cmd = "gpt F:\saikiran\myGraph.xml -Psource={} - Ptarget={}".format(input_file, intermediate_file)
With Python 3.6 or 3.7 you can use f-string
cmd = f"gpt F:\saikiran\myGraph.xml -Psource={input_file} - Ptarget={intermediate_file}"
Current cmd
"gpt F:\saikiran\myGraph.xml -Psource=input_file - Ptarget=intermediate_file"
will create file with name literally
intermediate_file
not
F:/saikiran/ddd
and it can make problem in gdal.Open()

Converting python2 PIL to python3 code

A program I'm trying to convert from python2 to python3 uses PIL the python image library.
I try to download a thumbnail from the web to display within a tkinter style gui. Here is, what I think, the offending line of code:
# grab the thumbnail jpg.
req = requests.get(video.thumb)
photo = ImageTk.PhotoImage(Image.open(StringIO(req.content)))
# now this is in PhotoImage format can be displayed by Tk.
plabel = tk.Label(tf, image=photo)
plabel.image = photo
plabel.grid(row=0, column=2)
The program stops and gives a TypeError, here is the backtrce:
Traceback (most recent call last): File "/home/kreator/.local/bin/url-launcher.py", line 281, in <module>
main()
File "/home/kreator/.local/bin/url-launcher.py", line 251, in main
runYoutubeDownloader()
File "/home/kreator/.local/bin/url-launcher.py", line 210, in runYoutubeDownloader
photo = ImageTk.PhotoImage(Image.open(StringIO(req.content)))
TypeError: initial_value must be str or None, not bytes
How do I satisfy python3's requirements here?
In this case you can see that the library you have imported doesn't support Python3. This isn't something you can fix from within your own code.
The lack of Python3 support is because PIL has been discontinued for quite some time now. There is a fork that's actively maintained that I would recommend you use instead: https://pillow.readthedocs.io/
You can download it from pypi.

How do I store images in a python script using Tkinter?

I want to render an image in tkinter but I always end up with an error saying that the image (PieTalk.gif) could not be found even though the image is in the same directory as the python script (startupgui.py):
/Home/COMP3203/COMP30203-project/src/ptgui/
Here is the method where I want to render an image in a GUI. The following code is a class called startupgui.py. It consists of a constructor and a method to load the image
Constructor:
def __init__(self):
# String to decide whether to go to client or server
self.trigger = None
#-----------------------#
# Creating window frame #
#-----------------------#
self.root = Tk()
self.root.wm_title("PieTalk")
self.root.geometry('600x450')
# creating PieTalk image
self.createimage()
# creating buttons
self.createbuttons()
Method to load image:
def createimage(self):
# Creating image frame
self.imageframe = Frame(self.root, bg='light grey')
self.imageframe.place(relx=0.1, relwidth=0.8, rely=0.05, relheight=0.65)
# Creating PieTalk image
self.pietalkimage=PhotoImage(file="PieTalk.gif")
# Creating label
self.imagelabel = Label(self.imageframe, image=pietalkimage)
self.imagelabel.image = self.pietalkimage
self.imagelabel.pack()
I have used the file name only:
self.pietalkimage=PhotoImage(file="PieTalk.gif")
And I have also used the absolute path to the file:
self.pietalkimage=PhotoImage(file="/Home/COMP3203/COMP30203-project/src/ptgui/PieTalk.gif")
Unfortunately, I keep on getting the same error when I execute the script:
Traceback (most recent call last):
File "pietalk.py", line 361, in <module>
startview=sgui.startupgui()
File "/home/archit/COMP3203/COMP3203-project/src/ptgui/startupgui.py", line 66, in __init__
self.createimage()
File "/home/archit/COMP3203/COMP3203-project/src/ptgui/startupgui.py", line 33, in createimage
self.pietalkimage=PhotoImage(file="/Home/COMP3203/COMP30203-project/src/ptgui/PieTalk.gif")
File "/usr/lib/python3.4/tkinter/__init__.py", line 3387, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/usr/lib/python3.4/tkinter/__init__.py", line 3343, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "/Home/COMP3203/COMP30203-project/src/ptgui/PieTalk.gif": no such file or directory
Is there something else that I am doing wrong when I am loading the image? What else can I do to load an image?
first convert it to base64 python variable
>>> import base64
>>> with open("my_image.py","w") as f:
... f.write('my_image="""%s"""'%base64.b64encode(open("my_gif.gif","rb").read()))
...
>>> exit()
you should now have the my_image.py file there ... copy that to the same directory as your tkinter script... an now you can do
from my_image import my_image
image=PhotoImage(data = my_image)
since you are having some problems lets try and simplify it a little bit
img2base64.py
import base64,sys,os,re
assert len(sys.argv) > 2,"Error: Useage %s /path/to/image.gif outfile.py"
assert os.path.exists(sys.argv[1]),"Error Unable to find image passed in as first argument"
outfile = open(sys.argv[2],"w")
raw_binary_data = open(sys.argv[1],"rb").read()
b64_encoded_data = base64.b64encode(raw_binary_data)
varname = re.sub("[^W]","_",os.path.splitext(os.path.basename(sys.argv[1]))[0])
pyname = os.path.splitext(os.path.basename(sys.argv[2]))[0]
outfile.write("%s='''%s'''"%(varname,b64_encoded_data))
outfile.close()
print "all done please put %s in your script directory and use it as follows:"%sys.argv[2]
print "from %s import %s"%(pyname,varname)
print "image=PhotoImage(data = %s)"%(varname)
just save that and then call it
$ python img2base64.py /path/to/image.gif pyimage.py
I think at least I didnt try it ...
Inspired by previous answer:
import base64
from pathlib import Path
import sys
src = Path(sys.argv[1])
dst = src.with_suffix(".py")
with dst.open("w") as f:
data = base64.b64encode(src.read_bytes()).decode('utf-8')
f.write(f'image="{data}"')
exit()
and I tested it ;-)

Categories

Resources