gpt4 book ai didi

python - 使用python更新标签中的图像

转载 作者:行者123 更新时间:2023-12-01 04:24:12 25 4
gpt4 key购买 nike

我有一个 python 模块,可以转换 python 的 datetime.datetime.now() 函数,根据看到的数字返回图像。如果它看到 01 秒,它会返回两张图像,一张为 0,一张为 1。这些只是 jpg 图像。我的 python 模块只返回一个字典,如下所示:

{'am_pm': '{file_path}am.jpg', 'hour': '{file_path}five.jpg', 'second2': {file_path}one.jpg, 'second1': {file_path}zero.jpg, 'colon': '{file_path}Colon.jpg', 'minute2': '{file_path}zero.jpg', 'minute1': '{file_path}zero.jpg'}

然后我有以下代码试图将其显示在标签中。不过,对于使用 tKinter 来说还是很陌生。

from PIL import ImageTk, Image
import datetime
from translator import Translator # my converter to get the above dict
import Tkinter as tk


def counter_label(label):
def count():
clock.get_time(datetime.datetime.now())
image = clock.return_images() # this is the dict mentioned above
label.configure(image=ImageTk.PhotoImage(Image.open(image['second2']))) # just using one entry in the dict for now.
label.after(1000, count)
count()


root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="green")
label.pack()
clock = Translator()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()

代码运行,我可以看到标签刷新,但是我看不到标签中的 jpg 图像。我究竟做错了什么?

最佳答案

问题是您没有让应用程序保存对图像对象的引用。既然你这样做了-

label.configure(image=ImageTk.PhotoImage(Image.open(image['second2'])))

label 不持有对您创建的图像对象的强引用,并将其作为 image 关键字参数的值发送给 label.configure() .因此,一旦执行上述行,图像对象就有资格进行垃圾收集(并且确实被垃圾收集),因此您看不到图像。

您需要使您的应用程序/程序持有对您的对象的强引用。一种非常简单的方法是使用全局变量来存储对图像的引用。示例-

def counter_label(label):
def count():
global image_obj
clock.get_time(datetime.datetime.now())
image = clock.return_images() # this is the dict mentioned above
image_obj = ImageTk.PhotoImage(Image.open(image['second2']))
label.configure(image=image_obj) # just using one entry in the dict for now.
label.after(1000, count)
count()

关于python - 使用python更新标签中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33329032/

25 4 0