【发布时间】:2014-10-28 17:24:36
【问题描述】:
我正在创建一个 Python 程序,它在 Tkinter 窗口中显示时间和天气。我需要时间、天气和其他任何东西不断更新。这是我的旧代码:
import time
from Tkinter import *
root = Tk()
while True:
now = time.localtime(time.time()) # Fetch the time
label = time.strftime("%I:%M", now) # Format it nicely
# We'll add weather later once we find a source (urllib maybe?)
w = Label(root, text=label) # Make our Tkinter label
w.pack()
root.mainloop()
我以前从未对 Tkinter 做过任何事情,令人沮丧的是循环不起作用。显然,Tkinter 不允许您在运行时执行任何类似循环或任何非 Tkinter 的操作。我想我也许可以用线程做点什么。
#!/usr/bin/env python
# Import anything we feel like importing
import threading
import time
# Thread for updating the date and weather
class TimeThread ( threading.Thread ):
def run ( self ):
while True:
now = time.localtime(time.time()) # Get the time
label = time.strftime("%I:%M", now) # Put it in a nice format
global label # Make our label available to the TkinterThread class
time.sleep(6)
label = "Weather is unavailable." # We'll add in weather via urllib later.
time.sleep(6)
# Thread for Tkinter UI
class TkinterThread ( threading.Thread ):
def run ( self ):
from Tkinter import * # Import Tkinter
root = Tk() # Make our root widget
w = Label(root, text=label) # Put our time and weather into a Tkinter label
w.pack() # Pack our Tkinter window
root.mainloop() # Make it go!
# Now that we've defined our threads, we can actually do something interesting.
TimeThread().start() # Start our time thread
while True:
TkinterThread().start() # Start our Tkinter window
TimeThread().start() # Update the time
time.sleep(3) # Wait 3 seconds and update our Tkinter interface
所以这也行不通。出现多个空窗口,它们会出现大量故障。我的调试器中也出现大量错误。
更新时是否需要停止并重新打开窗口?我可以告诉 Tkinter 用 tkinter.update(root) 之类的东西更新吗?
有解决方法或解决方案,还是我遗漏了什么?如果您发现我的代码有任何问题,请告诉我。
谢谢! 亚历克斯
【问题讨论】:
标签: python python-2.7 user-interface time tkinter