如何定期更改 tkinter 图像?

lad*_*ads 3 python image tkinter python-3.x

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

\n\n

这是我到目前为止所拥有的:

\n\n
import tkinter as tk\nfrom PIL import Image, ImageTk\n\nroot = tk.Tk()\nimg_path = 'test.bmp'\nimg = ImageTk.PhotoImage(Image.open(img_path), Image.ANTIALIAS))\n\ncanvas = tk.Canvas(root, height=400, width=400)\ncanvas.create_image(200, 200, image=img)\ncanvas.pack()\n\nroot.mainloop()\n
Run Code Online (Sandbox Code Playgroud)\n\n

但我不知道如何每隔 \xc2\xbd 秒刷新图像?
\n我正在使用 Python3 和 Tkinter。

\n

mar*_*eau 8

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

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

主要要点是您需要使用通用 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()
Run Code Online (Sandbox Code Playgroud)