更新Tkinter窗口的内容

时间:2014-09-04 04:37:25

标签: python python-2.7 user-interface time tkinter

我正在创建一个在Tkinter窗口中显示时间和天气的Python程序。我需要有时间,天气和其他任何不断更新的东西。这是我的旧代码:

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)之类的内容吗?

有解决方法或解决方案,还是我遗漏了什么?如果您发现我的代码有任何问题,请告诉我。

谢谢! 亚历

1 个答案:

答案 0 :(得分:0)

您可以“嵌套”after来电:

def update():
    now = time.localtime(time.time())
    label = time.strftime("%I:%M:%S", now)
    w.configure(text=label)
    root.after(1000, update)

现在你只需要在主循环之前调用after一次,并且它从现在开始每秒更新一次。