【问题标题】:tkinter canvas only updates with an errortkinter 画布仅更新错误
【发布时间】: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


【解决方案1】:

您在 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

【讨论】:

  • 是的。这样就彻底解决了。我已经查看了您之前链接到的 Tkinter PhotoImage 类,并将图像保存到将在函数中返回的变量中。那没有用,但使其全球化完全解决了它。谢谢。
  • bind()/command=/after() 分配的函数稍后由mainloop() 执行,但mainloop() 不会将返回值分配给全局变量。它不关心返回值。它不让他们知道。
猜你喜欢
  • 1970-01-01
  • 2022-01-01
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多