【问题标题】:How to automatically update a tkinter ui如何自动更新 tkinter gui
【发布时间】:2021-07-04 17:10:34
【问题描述】:

我正在尝试使用 tkinter 在 python 中制作 UI。我希望它在右上角显示非常不稳定的值(我通过 api 获取值)。这个值几乎每秒都会改变,所以我想确保它是最新的。我可以制作一个刷新用户界面的按钮,但这对用户来说并不是很酷。我的问题是如何使用 tkinter 每 x 秒自动刷新 ui 中的值,或者不可能有更好的解决方案。

【问题讨论】:

  • 你需要给我们一个最小的工作示例。您可以使用<tkinter.Tk>.after(time_in_ms, <your function>)。这将在您指定的延迟后调用您的函数。

标签: python user-interface tkinter page-refresh


【解决方案1】:

您可以创建一个在后台运行的Thread,并使用StringVar() 在 tkinter 中每 x 秒更新一次值。

更新时间的示例代码:

import tkinter as tk
from threading import Thread
import datetime
import time

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        # Make a StringVar that will contain the value
        self.value = tk.StringVar()

        # Make a label that will show the value of self.value
        self.label = tk.Label(self, textvariable=self.value).pack()


        # Make a thread that will run outside the tkinter program
        self.thread = Thread(target=self.show_time)

        # set daemon to True (This means that the thread will stop when you stop the tkinter program)
        self.thread.daemon = True

        # start the thread
        self.thread.start()

        tk.Button(self, text="Click me", command=lambda: print("Hello World")).pack()

    def show_time(self):
        # The thread will execute this function in the background, so you need to while loop to update the value of self.value
        while True:

            # Get the time (in your case, you need to get the api data)
            data = datetime.datetime.now().strftime('Time: %H:%M:%S, Milliseconds: %f')

            # Update the StringVar variable
            self.value.set(data)

            # Pause the while loop with 1 second, so you can set an interval to update your value
            time.sleep(1)

# rest of your code.

root = SampleApp()
root.mainloop()

【讨论】:

    猜你喜欢
    • 2014-09-11
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 2020-10-01
    • 2023-03-18
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    相关资源
    最近更新 更多