我正在编写一个代码,当用户在Treeview小部件中选择一个项目时,它将在canvas小部件中显示一个.png。运行代码时,只有在selectedItems函数中抛出错误时,图像才会显示在画布中。到目前为止,它可以是任何错误,但是除非抛出错误,否则不会显示图像。我尝试过插入一个时间延迟,并使用了一个调试工具,但我仍然不明白为什么会发生这种情况。如果没有错误,Treeview仍会为所选项目生成索引,但画布不会随图片更新。有人能教育我吗?在
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)
这是我得到的错误:
^{pr2}$我知道打字错误1。这是有意让图像显示出来的。我认为问题出在tkinter调用函数中。有什么想法吗?在
tkinter中的bug有问题,它从内存中删除了分配给函数中局部变量的图像,然后它就不显示它了。你必须把它赋给全局变量或类。在
请参阅代码中的
global
,这样,image1
将是全局变量,而不是局部变量。在另请参阅第The Tkinter PhotoImage Class页末尾的“注:”
相关问题 更多 >
编程相关推荐