2014-09-04 54 views
0

我正在创建一个Python程序,在Tkinter窗口中显示时间和天气。我需要有时间,天气和其他不断更新的东西。这里是我的旧代码:更新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)之类的东西吗?

是否有解决方法或解决方案,或者我错过了什么?如果您看到我的代码有任何问题,请告诉我。

谢谢! 亚历

回答

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一次,并从现在起每秒更新。

+0

所以我得到这个: [链接](http://txt.do/o5we) 它不断打开新的空白窗口的每一秒。我在这里错过了什么? – user3724472 2014-09-04 16:27:38

+0

1.每次调用update时,都会创建一个新的'Tk'实例。像以前一样将它移到函数之外。 2.启动主循环后,不必调用'update'。当然,我没有发表整个剧本。我只是给了你方法和一些说明如何实现你的功能。 – TidB 2014-09-04 16:30:59