如何定期更改tkinter图像? [英] How can I periodically change a tkinter image?

查看:139
本文介绍了如何定期更改tkinter图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的图像保存在文件 test.bmp 中,此文件每秒被覆盖2次

(我想要显示每秒2张图片。



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

 从TIL导入tkinter为tk 
导入图像,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。

解决方案

哎呀,你问题中的代码看起来非常熟悉 ...... / p>

由于需要对图像文件进行更新,因此使用经过测试的代码组成的答案很复杂d通过一些神秘的未指定过程。这在下面的代码中通过创建一个独立的线程来完成,该线程定期覆盖独立于主进程的图像文件。我尝试用评论来描述这些代码,因为我觉得这有点让人分心,让事情看起来比实际情况更复杂。



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



  -------------------------------------------------- ---------------------------- 
#代码模拟后台进程定期更新图像文件。
#注意:
#重要的是这段代码*不能直接与主流程中的tkinter
#stuff交互,因为它不支持多线程。
import itertools
import os
import shutil
import threading
import time

def update_image_file(dst):
通过将连续图像
文件复制到目标路径来覆盖(或创建)目标文件。无限期运行。

TEST_IMAGES ='test_image1.png','test_image2.png', itertools.cycle(TEST_IMAGES)中src的'test_image3.png'


shutil.copy(src,dst)
time.sleep(.5)更新之间的暂停
#--------------------------------------------- ---------------------------------

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)
除了IOError:#jill错误或损坏的图像文件
img =无
#每半秒重复
ca nvas.after(500,refresh_image,canvas,img,image_path,image_id)

root = tk.Tk()
image_path ='test.png'

#------------------------------------------------- -----------------------------
#更多代码模拟后台进程定期更新图像文件。
th = threading.Thread(target = update_image_file,args =(image_path,))
th.daemon = True#终止每当主线程执行
th.start()
而不是os.path.exists(image_path):#让它运行直到图像文件存在
time.sleep(.1)
#---------------- -------------------------------------------------- ------------

canvas = tk.Canvas(root,height = 400,width = 400)
img =无#最初只需要画布图像占位符
image_id = canvas.create_image(200,200,image = img)
canvas.pack()

refresh_image(canvas,img,image_path,image_id)
root.mainloop()


I have an image that is saved in a file test.bmp and this file is overwritten 2 times per second
(I want to show 2 images per second).

Here is what I have so far:

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

But I don't know how can I refresh the image every ½ second?
I'm using Python3 and Tkinter.

解决方案

Gee, the code in your question looks very familiar...

Coming up with an answer comprised of tested code was complicated by the need to have the image file be updated by some mysterious unspecified process. This is done in the code below by creating a separate thread that periodically overwrites the image file independent of the main process. I tried to delineate this code from the rest with comments because I felt it was somewhat distracting and makes things seem more complex than they are really.

The main takeaway is that you'll need to use the universal tkinter widget after() method to schedule the image to be refreshed at some future time. Care also needs to be taken to first create a place-holder canvas image object so it can be updated in-place later. This is needed because there may be other canvas objects present, and otherwise the updated image could cover them up depending on relative placement if a place-holder had not been created (so the image object id that's returned can be saved and used later to change it).

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

这篇关于如何定期更改tkinter图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆