【问题标题】:Python tkinter - How to reload label's image every second? [duplicate]Python tkinter - 如何每秒重新加载标签的图像? [复制]
【发布时间】:2021-08-28 03:01:03
【问题描述】:

我有一个图像(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 Label redrawing every 10 seconds

Tkinter Reloading Window displaying an Image

Tkinter.Misc-class.html#update

Tkinter.Misc-class.html#update_idletasks

我还尝试使用 Label["image"]=... ... 和线程库进行循环。

【问题讨论】:

  • 问题似乎是您无法显示图像,因为它还不存在。你希望我们能提出什么建议?我只能想象 2 种可能性……要么显示一个替代图像,上面写着 “正在加载”,要么等到你的图像确实存在。或者做微软的事情并说“图像加载在 4 秒、3 秒、2 秒、8 分钟、8 分钟、1 秒、15 分钟......” ;-)
  • @Mark Setchell 正如我之前提到的,它确实在 while 之后存在

标签: python tkinter


【解决方案1】:

您必须首先保留对 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 忽略所有错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-24
    • 2011-08-17
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 2012-12-26
    • 2014-09-11
    • 1970-01-01
    相关资源
    最近更新 更多