【问题标题】:Display image with Tkinter and loop over time使用 Tkinter 显示图像并随时间循环
【发布时间】:2011-10-03 16:49:41
【问题描述】:

我目前正在使用 PIL 和 Tkinter 来显示图像。我正在从网络传输图像,并希望在进入时自动更新我的窗口(很像图片幻灯片)。我的显示图像代码有效;但是,我必须单击显示窗口上的 [x] 按钮才能更新照片。我希望窗口在新照片出现时自动更新,或者至少每 5 秒运行一次循环(这样窗口要么自行关闭并出现新照片,要么照片只是在窗口中更改)。我的代码是:

##I have a database of photos i want to display one by one...

im=image.open(currentphoto)
root=Tk()
canvas=...
photo=imageTk.PhotoImage(im)
item=canvas.create_image(10,10,anchor=NW,image=photo)

root.mainloop()

##want to display next photo either as it comes in or every 5 seconds (whichever is easier -- first method preferred)

此代码有效;

【问题讨论】:

  • 你需要一个计时器和一个回调。
  • 您不需要创建计时器——事件循环能够在特定时间点运行代码。

标签: python tkinter python-imaging-library


【解决方案1】:

调用方法after 来安排命令在未来运行。该命令还可以调用after 来安排自己在将来再次运行是完全合法的。

有关显示标签每秒更新其文本的示例,请参阅this answer 此处关于 SO 的另一个问题。

【讨论】:

  • 我已经尝试过了,但似乎无法让它发挥作用。我的整个脚本是用一个简单的 py 脚本编写的。我不使用 def 或 class 或任何其他类型。你能帮忙了解一下吗?
  • 没有看到您尝试过的内容或看到您遇到的错误,我无法猜测您做错了什么。话虽如此,您只需必须使用 def 来定义要定期运行的函数。
  • 好的,希望这是有道理的。我的代码运行如下:while True:
  • 好的,希望这是有道理的。我的代码运行如下:#ive 设置一些数据流以从网络接收 #ive 设置一些数据流以从网络接收,而 True: data=sock.recv(4096) image_index=xydist(min(data)) # This行是浓缩的,但这是我为我的图片选择索引的地方 current photo="C:\Python27\pics\%s" % (listing(image_index)) im=Image.open(currentphoto) root=Tk() canvas= Canvas(...) photo=ImageTk.PhotoImage(im) item=canvas.create_image(10,10,anchor=NW,image=photo) root.mainloop()
  • 然后我看了你的建议,我试过: import Tkinter as tk class sample(tk.Tk): def __init__(self,*args,**kwargs): tk.Tk.__init( self,*args,**kwargs) root=Tk() data=sock.recv(4096) image_index=xydist(min(data)) # 这行是压缩的,但这是我为我的图片选择索引的地方 current photo= "C:\Python27\pics\%s" % (listing(image_index)) im=Image.open(currentphoto) canvas=Canvas(...) photo=ImageTk.PhotoImage(im) item=canvas.create_image(10, 10,anchor=NW,image=photo) root.mainloop() self.update_clock()
猜你喜欢
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 2011-08-24
  • 2015-04-24
  • 2020-04-29
  • 2014-06-27
  • 1970-01-01
  • 2013-12-24
相关资源
最近更新 更多