在Tkinter窗口中刷新图像 [英] Refresh image in Tkinter window

查看:1703
本文介绍了在Tkinter窗口中刷新图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个应用程序来连续显示从IP摄像机获取的图像。我已经弄明白了如何获取图像,以及如何使用Tkinter显示图像。但我不能让它不断刷新图像。使用Python 2.7 +。

I am building an application to continuously display an image fetched from an IP camera. I have figured out how to fetch the image, and how to also display the image using Tkinter. But I cannot get it to continuously refresh the image. Using Python 2.7+.

这是我到目前为止的代码。

Here is the code I have so far.

import urllib2, base64
from PIL import Image,ImageTk
import StringIO
import Tkinter

URL = 'http://myurl.cgi'
USERNAME = 'myusername'
PASSWORD = 'mypassword'

def fetch_image(url,username,password):
    # this code works fine
    request = urllib2.Request(url)
    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)   
    result = urllib2.urlopen(request)
    imgresp = result.read()
    img = Image.open(StringIO.StringIO(imgresp))
    return img

root = Tkinter.Tk()
img = fetch_image(URL,USERNAME,PASSWORD)
tkimg = ImageTk.PhotoImage(img)
Tkinter.Label(root,image=tkimg).pack()
root.mainloop()

我应该如何编辑代码这样重复调用 fetch_image 并在Tkinter窗口更新其输出?

How should I edit the code so that the fetch_image is called repeatedly and its output updated in the Tkinter window?

注意我没有使用任何触发图像刷新的按钮事件,而不应该每1秒自动刷新一次。

Note that I am not using any button-events to trigger the image refresh, rather it should be refreshed automatically, say, every 1 second.

推荐答案

这是使用Tkinter的 Tk.after 函数的解决方案,该函数计划将来对函数的调用。如果您使用下面的剪辑替换 fetch_image 定义后的所有内容,您将获得您描述的行为:

Here is a solution that uses Tkinter's Tk.after function, which schedules future calls to functions. If you replace everything after your fetch_image definition with the snipped below, you'll get the behavior you described:

root = Tkinter.Tk()
label = Tkinter.Label(root)
label.pack()
img = None
tkimg = [None]  # This, or something like it, is necessary because if you do not keep a reference to PhotoImage instances, they get garbage collected.

delay = 500   # in milliseconds
def loopCapture():
    print "capturing"
#    img = fetch_image(URL,USERNAME,PASSWORD)
    img = Image.new('1', (100, 100), 0)
    tkimg[0] = ImageTk.PhotoImage(img)
    label.config(image=tkimg[0])
    root.update_idletasks()
    root.after(delay, loopCapture)

loopCapture()
root.mainloop()

这篇关于在Tkinter窗口中刷新图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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