如何自动更新tkinter用户界面

2024-09-27 09:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 用户apiuitkinter解决方案用户界面按钮正试图
1条回答
网友
1楼 · 发布于 2024-09-27 09:28:01

您可以制作一个在后台运行的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()

相关问题 更多 >

    热门问题