【问题标题】:Updating label image in tKinter works, but I'm not sure why?在 tKinter 中更新标签图像有效,但我不确定为什么?
【发布时间】:2019-03-12 06:19:19
【问题描述】:

好的,所以我在 tKinter 中有一个项目,其中包括一个带有图像的标签和一个输入框。我需要发生的是图像会根据输入框中的文本而变化。以下是相关代码:

from tkinter import *


def go():
    art = PhotoImage(file=str(entry.get() + ".png"))
    portrait = Label(root, image=art)
    portrait_1.grid(row=0, column=0)
    print(z1)


root = Tk()
root.title("Window Title")

art = PhotoImage(file="image1_.png")
portrait = Label(root, image=art)
portrait1.grid(row=0, column=0)

entry = Entry(root)
entry.grid(row=1, column=0)

goButt = Button(root, text="Go", command=go)
goButt.grid(row=1, column=1)

root.mainloop()

我尝试了许多不同的方法来让这个(更新标签图像)工作,但这是唯一成功的方法。

您可能会注意到go() 函数中的print(z1) 命令。 z1 不是一个已定义的变量,也没有在代码中的任何其他地方使用,但如果没有它,点击 Go 按钮会删除旧图像,但将标签留空(即不会加载新图像)。删除那段代码,或以任何方式定义z1(例如z1 = 1)都会做同样的事情。

到目前为止,拥有print(z1) 不会以任何方式对项目产生负面影响,但拥有它有点烦人。我想知道是否有人可以解释为什么该项目似乎只能使用那段代码(以及为什么它只在未定义的情况下才有效),以及是否有办法安全地摆脱它。

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    您发布的代码中有一些混淆,标签小部件名称为portraitportrait1portrait_1。修复后它似乎像这样工作:

    函数go() 创建一个新标签(纵向)。这与您之前创建的标签不同,而是一个仅存在于函数go() 中的新标签。然后将图像放入标签中并将其放置在根窗口中。图像的名称只存在于函数go() 中,这意味着函数结束时将进行垃圾回收。

    print(z1) 行在函数结束前停止程序,从而保持对图像的引用。如果没有print(z1) 行,函数将退出,对图像的引用将被垃圾收集,标签将无法再找到图像。

    通常的做法是使用.config() 更新标签,然后在标签小部件中保存对图像的引用:

    from tkinter import *
    
    def go():
        new = PhotoImage(file=str(entry.get() + ".png")) # Create new image
        portrait.config(image=new)  # Update label with new image
        portrait.image = new        # Save reference to the image
    
    root = Tk()
    root.title("Window Title")
    
    art = PhotoImage(file="image1_.png")
    portrait = Label(root, image=art)
    portrait.grid(row=0, column=0)
    
    entry = Entry(root)
    entry.grid(row=1, column=0)
    
    goButt = Button(root, text="Go", command=go)
    goButt.grid(row=1, column=1)
    
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-23
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多