"_tkinter.TclError: image "pyimage2" doesn't exist" - python

I'm trying to fix this and I don't know how... When I click on the first button the second doesn't appear. It raises this exception:
_tkinter.TclError: image "pyimage2" doesn't exist
I tried everything but I don't know what to do anymore.
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "test\main.py", line 26, in <lambda>
boutonAlphabetMaj.bind("<Leave>", lambda e: boutonAlphabetMaj.config(fg='#3f3f3f', bg='#383838'))
File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 1646, in configure
return self._configure('configure', cnf, kw)
File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 1636, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: image "pyimage2" doesn't exist
Code:
import tkinter as tk
from tkinter import font
from PIL import ImageTk, Image
import time
import os
# Root
root = tk.Tk()
root.minsize(1920, 1080)
root.maxsize(1920, 1080)
# Frame + Canvas
frame = tk.LabelFrame(root, borderwidth=0)
canvas = tk.Canvas(frame, height=1080, width=1920, borderwidth=0, bg="#383838")
frame.grid()
canvas.grid()
# Fonctions
def alphabet() :
canvas.delete("boutonAlphabet")
# Bouton Alphabet Majuscule
pathAlphabetMaj = os.path.join("test/alphabetMaj.png")
pictureAlphabetMaj = Image.open(pathAlphabetMaj)
picAlphabetMaj = ImageTk.PhotoImage(pictureAlphabetMaj)
boutonAlphabetMaj = tk.Button(canvas, image=picAlphabetMaj, borderwidth=0, bg="#383838", activebackground="#4a4a4a", cursor="hand2")
picAlphabetMaj.pictureAlphabetMaj = pictureAlphabetMaj
boutonAlphabetMaj.bind("<Enter>", lambda e: boutonAlphabetMaj.config(fg='#383838', bg='#3f3f3f'))
boutonAlphabetMaj.bind("<Leave>", lambda e: boutonAlphabetMaj.config(fg='#3f3f3f', bg='#383838'))
canvas.create_window(200, 500, window=boutonAlphabetMaj, tags=("boutonAlphabetMaj"))
# Titre
canvas.create_text(960, 50, text="APPRENDRE LE FRANÇAIS", font=("",50), fill="white")
# Bouton Alphabet
pathAlphabet = os.path.join("test/alphabet.png")
pictureAlphabet = Image.open(pathAlphabet)
picAlphabet = ImageTk.PhotoImage(pictureAlphabet)
boutonAlphabet = tk.Button(canvas, image=picAlphabet, borderwidth=0, bg="#383838", activebackground="#4a4a4a", command=lambda: alphabet(), cursor="hand2")
picAlphabet.pictureAlphabet = pictureAlphabet
boutonAlphabet.bind("<Enter>", lambda e: boutonAlphabet.config(fg='#383838', bg='#3f3f3f'))
boutonAlphabet.bind("<Leave>", lambda e: boutonAlphabet.config(fg='#3f3f3f', bg='#383838'))
canvas.create_window(200, 250, window=boutonAlphabet, tags=("boutonAlphabet"))
# loop
root.mainloop()

You have common problem with bug in ImagePhoto which removes image when it is assigned to local variable in function. You have to assign it to global variable or to class.
It seems you try to resolve this problem but you use wrong variables.
You assign Image.open() to PhotoImage .
picAlphabetMaj.pictureAlphabetMaj = pictureAlphabetMaj
but you should assign PhotoImage to button boutonAlphabetMaj
boutonAlphabetMaj.pictureAlphabetMaj = picAlphabetMaj

Related

Button Picture Attribute issues with Tkinter

I'm having weird issues with some iterated buttons that are made inside of a function. I have my button list as a global variable and photos are saved within my main python folder.
When I use the Button image= attribute, the buttons aren't clickable and are kind of greyed out with no picture. When I use the Button text= attribute, the buttons are clickable and the text pops up, but the width and height attributes don't run. I haven't been able to find similar issues/answers here.
from tkinter import *
from tkinter import filedialog as fd
from tkinter.messagebox import showinfo
from PIL import Image, ImageTk
def OnSomeClick():
---Some Code---
if Orientation == 1:
for i in range(len(Ordered_xCoord)):
InitButtonPhoto = '{}.png'.format(i)
ButtonPhoto = PhotoImage(file=InitButtonPhoto)
ImageButtonList.append(Button(action_window, command=Command, bd=3, width=110,
height=85, image=ButtonPhoto))
ImageButtonList[i].grid(row=Ordered_yCoord[i], column=Ordered_xCoord[i])
#this top if statement is what runs with my test; the bottom is my original
else:
for i in range(len(Ordered_xCoord)):
ImageButtonList.append(Button(action_window,
image=PhotoImage(file='{}.png'.format(i)),
command=Command, bd=3, width=85, height=110))
ImageButtonList[i].grid(row=Ordered_yCoord[i], column=Ordered_xCoord[i])
When loading the photo through PhotoImage(Image.open(file)), there is a traceback error. I'm not too sure why my photos are out of scope/garbaged or why the command working is dependent on the photo saving.
Traceback Error with Image.open:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Users/.conda/envs/CoordinateMath/lib/python3.8/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "/Users/PycharmProjects/CoordinateMath/TkinterWindow.py", line 163, in Submit
ButtonPhoto = PhotoImage(file=InitButtonPhoto)
File "/Users/.conda/envs/CoordinateMath/lib/python3.8/tkinter/__init__.py", line 4064, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/Users/.conda/envs/CoordinateMath/lib/python3.8/tkinter/__init__.py", line 4009, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "<PIL.PngImagePlugin.PngImageFile image mode=RGB size=990x765 at 0x11034C310>": no such file or directory
Thank you, Matiiss and BryanOakley! The fix was a combo of the latest comment and putting my changing the formatting of my image list.
def onClick():
global Image_List, Ordered_xCoord, Ordered_yCoord, ImagedButtonList
--some code---
for i in range(len(Ordered_xCoord)):
y = myimage.save('{}.png'.format(i))
z = ImageTk.PhotoImage(Image.open('{}.png'.format(i)))
Image_List.append(z)
---more code----
if PaperOrientation == 1:
for i in range(len(Ordered_xCoord)):
InitButtonPhoto = Image_List[i]
ButtonPhoto = InitButtonPhoto
ImageButtonList.append(Button(action_window, command=Command, bd=3, width=110,
height=85, image=ButtonPhoto))
ImageButtonList[i].grid(row=Ordered_yCoord[i], column=Ordered_xCoord[i])
else:
for i in range(len(Ordered_xCoord)):
InitButtonPhoto = Image_List[i]
ButtonPhoto = InitButtonPhoto
ImageButtonList.append(Button(action_window, command=Command, bd=3, width=85,
height=110, image=ButtonPhoto))
ImageButtonList[i].grid(row=Ordered_yCoord[i], column=Ordered_xCoord[i])
Kind of sloppy on my part, but it works.

Exception KeyError if call focus_get() when down arrow clicked on widget Combo

Try to view where the focus by following code, but get Exception KeyError if call focus_get() when down arrow clicked on widget Combo.
import tkinter as tk
from tkinter import ttk
def show_focus():
label.configure(text=f'Focus at {root.focus_get()}')
root.after(100, show_focus)
font = ('Courier New', 16)
root = tk.Tk()
label = tk.Label(root, text='Focus at', width=40, font=font, anchor='w')
label.pack(anchor='w', fill='x')
value1 = tk.StringVar()
value1.set("Entry")
entry = tk.Entry(root, textvariable=value1, width=40, font=font, bg='green', fg='black')
entry.pack(anchor='w', fill='x')
value2 = tk.StringVar()
value2.set("Male")
combo = ttk.Combobox(root, values=['Male', 'Female'], textvariable=value2, width=40, height=5, font=font)
combo.pack(anchor='w')
show_focus()
root.mainloop()
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Software\Python\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Software\Python\lib\tkinter\__init__.py", line 814, in callit
func(*args)
File "D:\tkinter focus_get.py", line 5, in show_focus
label.configure(text=f'Focus at {root.focus_get()}')
File "C:\Software\Python\lib\tkinter\__init__.py", line 758, in focus_get
return self._nametowidget(name)
File "C:\Software\Python\lib\tkinter\__init__.py", line 1507, in nametowidget
w = w.children[n]
KeyError: 'popdown'
In method focus_get() of tkinter
...
name = self.tk.call('focus') #name: <string object: '.!combobox.popdown.f.l'>
...
self._nametowidget(name)
...
def nametowidget(self, name):
"""Return the Tkinter instance of a widget identified by
its Tcl name NAME."""
name = str(name).split('.')
w = self
if not name[0]:
w = w._root()
name = name[1:]
for n in name:
if not n:
break
w = w.children[n] # '!combobox' in root.children, but 'popdown' not in combo.children, so it get KeyError here.
return w
_nametowidget = nametowidget
My question is how can I get where the focus, but to avoid situation like this one. Maybe try except statement can skip exception, but it will get wrong focus at that moment.
[Update]
def show_focus():
try:
label.configure(text=f'Focus at {root.focus_get()}')
except:
# root.after(100, show_focus), if this statement put here, this function will stop if no exception
pass
root.after(100, show_focus) # statement here to keep update where the focus
You can get over the error by ignoring each press on the 'popdown' button.
def show_focus():
if str(root.tk.call(combo,'state')) != 'pressed':
label.configure(text=f'Focus at {root.focus_get()}')
else:
label.configure(text=f'Focus at {str(combo)}')
root.after(100, show_focus)
This is a way around the issue as 'popdown' button is not identified by nametowidget()(which is used to return the widget name when using focus_get()). I was able to find a similar bug at https://bugs.python.org/issue18686

Insert an JPG image in Python using Tkinter

i'm trying to insert an image using Tkinter but it doesn't work, there is an error message saying : (In fact it is saying that python can't recognise the data in image file)
Traceback (most recent call last):
File "E:/Tle/ISN/Programs (Pyhton)/IMC (Widget) ULTIMATE.py", line 10, in <module>
my_image = PhotoImage(file="C:/Users/mateo.PCMATEO/Pictures/MonCoachPersonnel.jpg")
File "C:\Users\mateo.PCMATEO\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 3545, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\mateo.PCMATEO\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 3501, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "C:/Users/mateo.PCMATEO/Pictures/MonCoachPersonnel.jpg"
And here's the code i've entered :
from tkinter import*
import tkinter as tk
window = tk.Tk()
window.title("My Personnal Fitness Coach")
window.geometry("400x500")
window.configure(background='grey')
canvas = Canvas(window, width = 100, height = 100)
canvas.pack
my_image = PhotoImage(file="C:/Users/mateo.PCMATEO/Pictures/MonCoachPersonnel.jpg")
canvas.create_image(0, 0, anchor = NW, image=my_image)
window.mainloop()
The problem is that i don't have any modules except the ones predownloaded with python and i don't want to install some yet. So could you help me?
if you use jpg you must do so
from PIL import ImageTk
then
my_image = ImageTk.PhotoImage(file="MonCoachPersonnel.jpg")
canvas.create_image(50, 50, image=my_image, anchor=NW)
I've simplify the file dir, note that I've increase the dimension of the pic, from 0,0 to 50,50.
Please, try this (only change image file path)
from tkinter import*
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
window.title("My Personnal Fitness Coach")
window.geometry("400x500")
window.configure(background='grey')
canvas = Canvas(window, width = 100, height = 100)
canvas.pack()
photo_image = ImageTk.PhotoImage(Image.open('xxxx\\racecar.jpg'))
my_image = canvas.create_image(0, 0, image=photo_image, anchor=NW)
# my_image = PhotoImage(file="xxxx\\racecar.jpg")
# canvas.create_image(0, 0, anchor = NW, image=my_image)
window.mainloop()

Putting gif image in tkinter window

I'm trying to insert a gif image in a new tkinter window when a button is clicked but I keep getting this error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\idlelib\run.py", line 119, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\queue.py", line 172, in get
raise Empty
queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:/Users/Afro/Desktop/mff.py", line 8, in sex
canvas = tkinter.Label(wind,image = photo)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2605, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2138, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage1" doesn't exist
Here's the code. The image and the location actually exists.
import tkinter
def six():
wind = tkinter.Tk()
photo = tkinter.PhotoImage(file = 'American-Crime-Story-1.gif')
self = photo
canvas = tkinter.Label(wind,image = photo)
canvas.grid(row = 0, column = 0)
def base():
ssw = tkinter.Tk()
la = tkinter.Button(ssw,text = 'yes',command=six)
la.grid()
base()
What am I doing wrong?
You are trying to create two instances of Tk window. You can't do that. If you want second window or pop-up window you should use Toplevel() widget.
Also, self doesn't mean anything in this context. Using the widget's image property would be better to keep a reference.
import tkinter
ssw = tkinter.Tk()
def six():
toplvl = tkinter.Toplevel() #created Toplevel widger
photo = tkinter.PhotoImage(file = 'American-Crime-Story-1.gif')
lbl = tkinter.Label(toplvl ,image = photo)
lbl.image = photo #keeping a reference in this line
lbl.grid(row=0, column=0)
def base():
la = tkinter.Button(ssw,text = 'yes',command=six)
la.grid(row=0, column=0) #specifying row and column values is much better
base()
ssw.mainloop()

_tkinter.TclError: can't pack when trying to add ttkcalendar into tkinter GUI

I'm trying to add a ttk calendar into my Tkinter GUI. The problem is that it raises _tkinter.TclError: can't pack .34164128 inside .34161248.34161448.34161608
import Tkinter
import tkSimpleDialog
import ttkcalendar
class CalendarDialog(tkSimpleDialog.Dialog):
"""Dialog box that displays a calendar and returns the selected date"""
def body(self, master):
self.calendar = ttkcalendar.Calendar(master)
self.calendar.pack()
def apply(self):
self.result = self.calendar.selection
# Demo code:
def main():
root = Tkinter.Tk()
root.wm_title("CalendarDialog Demo")
def onclick():
print 'click'
cd = CalendarDialog(root)
button = Tkinter.Button(root, text="Click me to see a calendar!", command=onclick)
button.pack()
root.update()
root.mainloop()
if __name__ == "__main__":
main()
TRACEBACK:
File "C:/Users/Milano/PycharmProjects/MC/plots/ds.py", line 32, in <module>
main()
File "C:/Users/Milano/PycharmProjects/MC/plots/ds.py", line 23, in main
cd = CalendarDialog(root)
File "C:\Python27\lib\lib-tk\tkSimpleDialog.py", line 64, in __init__
self.initial_focus = self.body(body)
File "C:/Users/Milano/PycharmProjects/MC/plots/ds.py", line 9, in body
self.calendar = ttkcalendar.Calendar(master)
File "C:\Users\Milano\PycharmProjects\MC\plots\ttkcalendar.py", line 52, in __init__
self.__place_widgets() # pack/grid used widgets
File "C:\Users\Milano\PycharmProjects\MC\plots\ttkcalendar.py", line 110, in __place_widgets
self._calendar.pack(in_=self, expand=1, fill='both', side='bottom')
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1940, in pack_configure
+ self._options(cnf, kw))
_tkinter.TclError: can't pack .34164128 inside .34161248.34161448.34161608
Do you know where is the problem?
The fault is that you don't have an __init__ method in the class CalendarDialog. So just rename the body method to __init__. Now you have initialized the instance every time one is made and a pack() method is defined.
I also encountered this problem putting a ttkCalendar into a Dialog box.
I suspect the author of this post "borrowed" the same code for building a calendar as I did:
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=2ahUKEwiWgYWKsJ3nAhVKl3IEHYrhCU8QFjABegQICBAB&url=https%3A%2F%2Fsvn.python.org%2Fprojects%2Fpython%2Ftrunk%2FDemo%2Ftkinter%2Fttk%2Fttkcalendar.py&usg=AOvVaw0ifTox4EI7CtBFWlRYD_m9
There are two problems I found using this code to create a Calendar object and placing it into a Dialog box.
The first one causes the traceback as shown in the post. The fix is to modify the ttkcalendar.py file to pack the calendar when it is created, not after it is created using the pack() function.
Here is the diff:
102c102
< self._calendar = ttk.Treeview(show='', selectmode='none', height=7)
---
> self._calendar = ttk.Treeview(self, show='', selectmode='none', height=7)
109c109
< self._calendar.pack(in_=self, expand=1, fill='both', side='bottom')
---
> self._calendar.pack(expand=1, fill='both', side='bottom')
Once you make this change, the calendar will appear in the dialog box. However, your problems are not yet done. Another exception occurs when trying to set the minimum size of the calendar:
Exception in Tkinter callback
Traceback (most recent call last):
File "/home/richawil/Applications/anaconda3/envs/TLM/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/home/richawil/Documents/Programming/Apps/TLM/TLM/ttkcalendar.py", line 134, in __minsize
width, height = self._calendar.master.geometry().split('x')
AttributeError: 'Calendar' object has no attribute 'geometry'
I have not been able to fix this issue other than to comment out the call to self.__minsize.
63c62,63
< self._calendar.bind('<Map>', self.__minsize)
---
> # Commented out because _calendar object does not support geometry() function
> #self._calendar.bind('<Map>', self.__minsize)

Categories

Resources