Skip to main content
 首页 » 编程设计

python之如何定期更改 tkinter 图像

2024年10月17日7三少

我有一个保存在文件 test.bmp 中的图像,这个文件每秒被覆盖 2 次
(我想每秒显示 2 张图像)。

这是我目前所拥有的:

import tkinter as tk 
from PIL import Image, ImageTk 
 
root = tk.Tk() 
img_path = 'test.bmp' 
img = ImageTk.PhotoImage(Image.open(img_path), Image.ANTIALIAS)) 
 
canvas = tk.Canvas(root, height=400, width=400) 
canvas.create_image(200, 200, image=img) 
canvas.pack() 
 
root.mainloop() 

但我不知道如何每 ½ 秒刷新一次图像?
我正在使用 Python3 和 Tkinter。

请您参考如下方法:

哎呀,你问题中的代码看起来很familiar ...

由于需要通过一些神秘的未指定进程更新图像文件,因此想出一个由经过测试的代码组成的答案很复杂。这是在下面的代码中通过创建一个单独的线程来完成的,该线程独立于主进程定期覆盖图像文件。我试图用注释将这段代码与其余代码区分开来,因为我觉得它有点分散注意力,让事情看起来比实际情况更复杂。

主要内容是您需要使用通用的 tkinter 小部件 after()安排图像在未来某个时间刷新的方法。还需要注意首先创建一个占位 Canvas 图像对象,以便稍后可以就地更新它。这是必需的,因为可能存在其他 Canvas 对象,否则如果未创建占位符,更新的图像可能会根据相对位置覆盖它们(因此返回的图像对象 ID 可以保存并稍后用于更改它)。

from PIL import Image, ImageTk 
import tkinter as tk 
 
#------------------------------------------------------------------------------ 
# Code to simulate background process periodically updating the image file. 
# Note:  
#   It's important that this code *not* interact directly with tkinter  
#   stuff in the main process since it doesn't support multi-threading. 
import itertools 
import os 
import shutil 
import threading 
import time 
 
def update_image_file(dst): 
    """ Overwrite (or create) destination file by copying successive image  
        files to the destination path. Runs indefinitely.  
    """ 
    TEST_IMAGES = 'test_image1.png', 'test_image2.png', 'test_image3.png' 
 
    for src in itertools.cycle(TEST_IMAGES): 
        shutil.copy(src, dst) 
        time.sleep(.5)  # pause between updates 
#------------------------------------------------------------------------------ 
 
def refresh_image(canvas, img, image_path, image_id): 
    try: 
        pil_img = Image.open(image_path).resize((400,400), Image.ANTIALIAS) 
        img = ImageTk.PhotoImage(pil_img) 
        canvas.itemconfigure(image_id, image=img) 
    except IOError:  # missing or corrupt image file 
        img = None 
    # repeat every half sec 
    canvas.after(500, refresh_image, canvas, img, image_path, image_id)   
 
root = tk.Tk() 
image_path = 'test.png' 
 
#------------------------------------------------------------------------------ 
# More code to simulate background process periodically updating the image file. 
th = threading.Thread(target=update_image_file, args=(image_path,)) 
th.daemon = True  # terminates whenever main thread does 
th.start() 
while not os.path.exists(image_path):  # let it run until image file exists 
    time.sleep(.1) 
#------------------------------------------------------------------------------ 
 
canvas = tk.Canvas(root, height=400, width=400) 
img = None  # initially only need a canvas image place-holder 
image_id = canvas.create_image(200, 200, image=img) 
canvas.pack() 
 
refresh_image(canvas, img, image_path, image_id) 
root.mainloop()