2016-07-24 41 views
1

我有一个图像保存在文件test.bmp和这个文件被覆盖每秒2次
(我想每秒显示2张图片)。我如何定期更改tkinter图像?

这是我到目前为止有:

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

只需在计时器上创建一个回调 –

+0

@PadraicCunningham您可以举一个例子或多解释一下。我对此很陌生。 – lads

+1

'root.after(500,your_function)',您的功能添加图像 –

回答

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()