I'm writing a code that will display a .png in a canvas widget whenever the user selects an item in a Treeview widget. When I run my code, the image only displays in the canvas when there is an error thrown in the selectedItems function. So far, it can be any error, but will not display the image unless an error is thrown. I have tried inserting a time delay and used a debugging tool but I still do not understand why this happens. When there is no error, the Treeview still generates an index for the selected item, but the canvas doesn't update with the picture. Can someone educate me?
import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk
def selectedItems(event):
item = tree.selection()
item_iid = tree.selection()[0]
parent_iid= tree.parent(item_iid)
directory= r"..."
if tree.item(parent_iid, "text") != "":
imageFile= directory + tree.item(item_iid, "text")
image_o= Image.open(imageFile)
image_o.thumbnail([683, 384], Image.ANTIALIAS)
image1= ImageTk.PhotoImage(image_o)
canvas1.create_image((0, 0), anchor= "nw", image= image1)
a= 'hello' + 7
tree.bind("<<TreeviewSelect>>", selectedItems)
This is the error I get:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File ".\front_end_DataManager.py", line 21, in selectedItems
a= 'hello' + 7
TypeError: must be str, not int
I'm aware of the TypeError one. That's intentional to get the image to display. I think the problem is in the tkinter call function. Any ideas?
You have problem with bug in tkinter which removes from memory image assigned to local variable in function - and then it doesn't display it. You have to assign it to global variable or class.
See global
in code - this way image1
will be global variable, not local.
def selectedItems(event):
global image1
item = tree.selection()
item_iid = tree.selection()[0]
parent_iid = tree.parent(item_iid)
directory = r"..."
if tree.item(parent_iid, "text") != "":
imageFile = directory + tree.item(item_iid, "text")
image_o = Image.open(imageFile)
image_o.thumbnail([683, 384], Image.ANTIALIAS)
image1 = ImageTk.PhotoImage(image_o)
canvas1.create_image((0, 0), anchor= "nw", image= image1)
See also "Note:" at the end of page The Tkinter PhotoImage Class