[英]Update the contents of Tkinter window
我正在創建一個在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)
類的東西進行更新嗎?
是否有解決方法或解決方案,或者我缺少什么? 如果您發現我的代碼有任何問題,請告訴我。
謝謝! 亞歷克斯
您可以“嵌套”您的通話after
:
def update():
now = time.localtime(time.time())
label = time.strftime("%I:%M:%S", now)
w.configure(text=label)
root.after(1000, update)
現在,你只需要調用after
主循環前一次,它從現在每秒更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.