首页 > 解决方案 > Python tkinter - 如何每秒重新加载标签的图像?

问题描述

我有一个图像(QR 图像),我必须显示它,并且每次都保持刷新。我尝试了很多解决方案,但都没有奏效,这是我的代码:

def QRDisplayer():
    global displayQR #I tried a tutorial wrote like this line, with it or without nothing changes 
    path = getcwd() + r"\temp\qr.png"
    try:
        displayQR.configure(image=PhotoImage(file=path))
    except: pass #I used try/except to avoid errors incase the image doesn't exists
    root.after(1000, QRDisplayer)


#main window:
root = Tk()
loadConfig()
root.title("")
root.resizable(False, False)
root.geometry("700x500")
displayQR = Label(root,image = None) #None bc it doesn't exists yet
displayQR.pack()
QRDisplayer()

if __name__ == "__main__":
    root.mainloop()

图像第一次不显示,bc它不存在,然后我必须开始刷新元素,直到照片在阅读后出现。照片也是可变的,所以我一直在阅读文件并显示内容。

我花了 6 个小时在上面工作,没有任何效果,包括:

Python Tkinter 标签每 10 秒重绘一次

显示图像的 Tkinter 重新加载窗口

Tkinter.Misc-class.html#update

Tkinter.Misc-class.html#update_idletasks

我也尝试了Label["image"]=......的循环和线程库。

标签: pythontkinter

解决方案


您必须首先保留对PhotoImage实例的引用,而您不是:

def QRDisplayer():
    global img

    img  = None
    path = getcwd() + r"\temp\qr.png"
    try:
        img = PhotoImage(file=path)
    except TclError: # Error that gets invoked with invalid files
        img = None
    
    if img is not None:
        displayQR.configure(image=img)

    root.after(1000, QRDisplayer)

这感觉像是一种更好的继续方式,所以只要万一内部发生其他错误,try您就可以捕获它,而不是用普通的except.


推荐阅读