Python Tkinter,每秒钟更新一次

2024-05-16 00:38:53 发布

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

所以我创建了一个pythontkinter应用程序,它有一个我需要每秒显示在屏幕上的测量值。当程序运行时,值会显示,但不会更新(我在外部操作值,因此我知道显示应该会更改)。如何使显示器每秒动态更新?我明白我不需要为Tkinter应用程序创建Update()方法或任何东西,因为mainloop()负责这个问题。这是我的代码:

在主.py公司名称:

from SimpleInterface import SimpleInterface
from ADC import Converter, Differential

adc = Converter(channelNums = [2])

root = SimpleInterface(adc)
root.title = ("Test Interface")

root.mainloop()

在简单接口.py公司名称:

^{pr2}$

因此,当代码最初运行时,显示正确地显示displayText,但是在我手动操作输入的值时,同样没有任何变化。我需要创建Update()方法吗?如果是这样的话,我将把said方法调用到哪里?在


Tags: 方法代码frompyimport名称应用程序公司
1条回答
网友
1楼 · 发布于 2024-05-16 00:38:53

是的,您需要创建一个方法来更新值,并使用after将该方法添加到tkinter主循环中。我建议用其他名称命名它,因为update已经是一个tkinter方法。在

作为一个完全未经测试的猜测:

class Screen(tk.Frame):
    def __init__(self, ADC, parent, controller):
        tk.Frame.__init__(self, parent)
        self.ADC = ADC
        lbl = ttk.Label(self, text = "Test Display", background = "grey")
        lbl.grid(column = 7, row = 8)
        self.lblTestDisplay = ttk.Label(self, foreground = "lime", background = "black")
        self.lblTestDisplay.grid(column = 7, row = 9, sticky = "ew")

        self.adc_update() # start the adc loop

    def adc_update(self):
        displayText = self.ADC.ReadValues() #this method returns a list of values
        for i in range(len(displayText)):
            displayText[i] = round(displayText[i], 2)
        self.lblTestDisplay.config(text = str(displayText)) # update the display
        self.after(1000, self.adc_update) # ask the mainloop to call this method again in 1,000 milliseconds

注意,我还将标签创建分成两行,一行初始化,一行布局。你拥有它的方式是非常糟糕的;它会导致变量赋值给None,从而导致bug。在

相关问题 更多 >