【问题标题】:Can't create a new image in mainloop无法在主循环中创建新图像
【发布时间】:2018-11-02 23:04:52
【问题描述】:

我有一长串图片想要加载到Tkinter 画布中。

如果我在 Tkinter 实例上调用 mainloop 之前创建 PIL.PhotoImage 实例,我发现这可行。我将以下内容放入绑定到按键或类似事件的回调函数中:

def onkeypress( event )
  canvas.itemconfig( canvas_image, image_content )

image_content = PIL.PhotoImage( file="myfile.jpg" )
mytk.bind( "<Key>", onkeypress )
mytk.mainloop()

...但这要求我在启动主循环之前将整个图像库加载到内存中。如果我尝试仅在需要时创建每个 PIL.PhotoImage

def onkeypress( event )
  image_content = PIL.PhotoImage( file="myfile.jpg" )
  canvas.itemconfig( canvas_image, image_content )

mytk.bind( "<Key>", onkeypress )
mytk.mainloop()

然后代码执行没有给我一个错误,但我没有看到画布内容发生变化。

请问我需要做什么才能更改画布内容?

【问题讨论】:

    标签: python tkinter python-imaging-library


    【解决方案1】:

    第一个问题我可以在mainloop() 之后看到它的一个函数你不能在主循环之后运行任何东西,直到 tkinter 实例被关闭。所以你需要将你的函数移动到主循环和绑定之上。另一个重要问题是函数中的局部变量。您的函数会创建一个本地图像,该图像将在函数完成后消失,因此您需要在函数中将 image_content 定义为全局图像。

    在使用画布时也适用相同的规则,因此如果您以下面的示例为例,您也可以将其应用于您的需求。

    这是一个简单的示例,说明如何将参考保存为图像,并在需要时通过按钮应用它们。

    import tkinter as tk
    from PIL import ImageTk
    
    
    root = tk.Tk()
    
    def change_color(img_path):
        global current_image
        current_image = ImageTk.PhotoImage(file=img_path)
        lbl.config(image=current_image)
    
    
    current_image = ImageTk.PhotoImage(file="red.gif")
    lbl = tk.Label(root, image=current_image)
    lbl.grid(row=0, column=0, columnspan=3)
    
    tk.Button(root, text="RED", command=lambda: change_color("red.gif")).grid(row=1, column=0)
    tk.Button(root, text="BLUE", command=lambda: change_color("blue.gif")).grid(row=1, column=1)
    tk.Button(root, text="GREEN", command=lambda: change_color("green.gif")).grid(row=1, column=2)
    
    root.mainloop()
    

    结果:

    【讨论】:

      【解决方案2】:

      这是因为tk 不会持有该图像对象的引用,因此 GC 会在函数作用域之后收集它,因为 image_content 是最后一个引用并且它会消失。

      您可以通过任何长期参考轻松解决此问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 2014-04-11
        相关资源
        最近更新 更多