tkinter canvas仅更新时出错

问题描述 投票:0回答:1

我正在编写一个代码,只要用户选择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调用函数中。有任何想法吗?

python tkinter tkinter-canvas photoimage
1个回答
0
投票

你有问题在tkinter中删除从内存中分配给函数中的局部变量的图像 - 然后它不会显示它。您必须将其分配给全局变量或类。

在代码中查看global - 这样image1将是全局变量,而不是本地变量。

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)

另见The Tkinter PhotoImage Class页面末尾的“注意:”

© www.soinside.com 2019 - 2024. All rights reserved.