I am getting errors when I want to display photos using canvas and Tkinter.
The code runs properly but when I added a few lines to display the image I got error like this
*Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\lib\tkinter_init_.py", line 1921, in call return self.func(args) File "C:\Users\Kacper\PycharmProjects\kosmos[w budowie]guicosmoscatalog.py", line 60, in show photo_display.pack() AttributeError: 'int' object has no attribute 'pack'
def show(event):
type = clicked.get()
if type == options_list_planets[0]:
#IMAGE DISPLAYING
canvas2 = Canvas(root, width = 400, height = 400, bg='#171717', bd = 0, highlightthickness=0, relief='ridge')
canvas2.pack()
my_img = ImageTk.PhotoImage(Image.open("Merkury.png"))
canvas2.place(relx = 0.05, rely = 0.1, relheight = 0.6, relwidth = 0.5)
photo_display = canvas2.create_image(225, 210, image=my_img)
photo_display.pack()
#LINES OF CODE RESPONSIBLE FOR DISPLAYING TEXT (IT WORKS)
for widget in pierwszy_frame.winfo_children():
widget.destroy()
for widget in drugi_frame.winfo_children():
widget.destroy()
text_label = tk.Label(pierwszy_frame, text = FULL_MERCURY_DESC)
text_label.pack()
#text2_label = tk.Label(drugi_frame, text = MERCURY_FACT)
#text2_label.pack(side = 'left')
CodePudding user response:
When you create an object on a canvas, it's not a widget and can't be treated as a widget. When you call canvas2.create_image(225, 210, image=my_img)
, tkinter is going to put the image on the canvas at the given location and then return an integer representing the id of the image.
You are then trying to call pack
on this integer, which gives the error 'int' object has no attribute 'pack'
The simply solution is to remove that line of code.
You are also making a very common mistake: you are storing the image reference in a local variable. Python will destroy this variable when the function returns. In order for the image to not be destroyed it needs to be saved as a global variable or as an attribute of some object.
For example, you could attach the image to the canvas2
object like so:
canvas2.my_img = my_img
This is arguably a design flaw in tkinter, but the solution is simple so it's easy to work around.