【问题标题】:Update the contents of Tkinter window更新 Tkinter 窗口的内容
【发布时间】: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


    【解决方案1】:

    您可以“嵌套”您的 after 电话:

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

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

    【讨论】:

    • 所以我得到了这个:[链接] (txt.do/o5we) 它每秒都会打开新的空白窗口。我在这里错过了什么?
    • 1.每次调用 update 时,您都会创建一个新的 Tk 实例。像以前一样将它移到函数之外。 2. 启动主循环后,您不必调用update。 3. 当然,我没有发布整个剧本。我只是给了你如何实现你的功能的方法和一些说明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多