python - 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 个小时在上面工作,没有任何效果,包括:
Tkinter.Misc-class.html#update
Tkinter.Misc-class.html#update_idletasks
我也尝试了Label["image"]=...
...的循环和线程库。
解决方案
您必须首先保留对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
.
推荐阅读
- ruby-on-rails - # 未定义的方法“last”
- php - HTML 内容如何作为附件响应返回以下载 pdf 和 docx
- python - TensorFlow/Keras 模型 __call__ 在 GPU 上运行时变得越来越慢
- mysql - 如何在单个原子操作中将临时表转换为永久表?
- javascript - 我使用 split 和 join 的替换代码仅适用于单个单词输入,而不适用于整个单词
- python - 使用参数化和 xfail 时出现 pytest 错误
- r - 如果我使用 {.tabset},如何在我的 Flexdashboard 中添加另一行?R
- python - 在 Python 中子类化两个类?
- machine-learning - 获取错误作为数据的 DataFrame.dtypes 必须是 int、float、bool 或 categorical
- javascript - Mailchimp Api 无法获取我发送的 email_address 字段