我有一个保存在文件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。
答案 0 :(得分:2)
哎呀,你问题中的代码非常familiar ...
由于需要通过一些神秘的未指定过程更新图像文件,所以提出由测试代码组成的答案变得复杂。这是通过创建一个独立的线程在下面的代码中完成的,该线程定期覆盖独立于主进程的图像文件。我试图用其他评论来描述这些代码,因为我觉得这有点让人分心,让事情看起来比实际上更复杂。
主要的一点是,您需要使用通用tkinter小部件after()
方法来安排在将来某个时间刷新图像。还需要注意首先创建一个占位符画布图像对象,以便以后可以在适当的位置进行更新。这是必需的,因为可能存在其他画布对象,否则如果尚未创建占位符,则更新的图像可以根据相对位置覆盖它们(因此可以保存返回的图像对象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()