【发布时间】:2017-12-26 22:22:08
【问题描述】:
我正在编写一个代码,只要用户在 Treeview 小部件中选择一个项目,它就会在画布小部件中显示一个 .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)
这是我得到的错误:
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
我知道 TypeError 之一。这是故意让图像显示。我认为问题出在 tkinter call 函数中。有什么想法吗?
【问题讨论】:
-
总是将完整的错误消息(Traceback)放在有问题的地方(作为文本,而不是屏幕截图)。还有其他有用的信息。
-
至少我们需要能够使用上传的代码重现您的错误。我的猜测是,我们最终会达到你将need to use a global reference to your image 的地步。
-
感谢您提供问题发布礼仪指南。我更新了我的问题,使其更简洁并包含错误消息。
-
您不能添加字符串
"hello"和数字 7 - 您必须将数字转换为字符串str(7)以连接两者"hello" + str(7) -
@furas 我知道字符串不是这样工作的。那是我故意插入的一条线,以使图像正确显示。不过,我认为 Nae 正在做某事。
标签: python tkinter tkinter-canvas photoimage