使用 after() 方法更新标签值。

Updating label values using after() method .

我正在尝试创建一个包含十个标签的页面,然后使用 after() 方法更新值。但是屏幕挂起。 开始定义绑定到创建标签的按钮,然后使用 after 方法我试图以递归方式调用更新方法来更新标签值。 他们是从主函数调用 update() 方法的另一种方法 (main) .

 def update(self,i):



        self.lab_hold_X=25

        self.data_hold_mL_screen[i].place(x=self.lab_hold_X,y=self.y_place)
        self.data_hold_mL_screen[i]['text']=str(int(self.data_hold_mL_screen[i]['text']) + 1)

        self.y_place +=30
        self.valuess=i+1

        if self.valuess <=10:
            self.after(1000,self.update(self.valuess))
        else :
            self.valuess=0
            self.after(1000,self.update(self.valuess))
    def start(self):
        self.lab_hold_X=25
        self.lab_hold_Y=10


        for i in range(0,10):
            self.lab_hold_Y +=30
            self.data_hold_mL_screen[i].place(x=self.lab_hold_X,y=self.lab_hold_Y)  
            self.lab_hold_X =25

            self.after(1000,update(0))

我基本上希望创建一个页面,其中我可以从任何外部设备获取值,然后将其显示在屏幕上,屏幕显示 10 个值,在第 11 次迭代时收到一个值,屏幕向上移动,第一个值是丢弃,第二个值显示在第一个标签位置..

这个:

self.after(1000,update(0))

...需要这样:

self.after(1000,lambda: update(0))

你调用的其他地方也是如此afterafter 需要对函数的 引用 ,但您正在 调用 函数并将函数的结果传递给 after.由于你的函数 returns 什么都没有,所以在 1000 毫秒后什么也没有执行。

一个简单的示例,使用一个列表来保存最后 10 个值,并使用第二个列表来保存已更新的 Label 的 StringVars。并且请不要使用 "i"、"l" 或 "O" 作为单字符变量名,因为它们看起来像数字。

from Tkinter import *
from functools import partial

class LabelTest():
    def __init__(self, master):
        self.master=master
        self.string_vars=[]  ## contains pointers to the label vars
        self.values=[]
        self.start()
        Button(self.master, text="Quit", bg="orange", width=15,
               command=self.master.quit).grid(row=20)
        self.update(1)

    def update(self, ctr):
        """ Change the StringVars to the new values
        """
        if len(self.values) > 9:
            ## full so delete the first one
            del self.values[0]
        self.values.append(ctr)
        ## update the StringVar with the corresponding
        ## value from self.values
        for offset in range(len(self.values)):
            self.string_vars[offset].set(self.values[offset])

        ctr += 1

        if ctr < 20:  ## let's put a limit on this
            self.master.after(1000, partial(self.update, ctr))

    def start(self):
        """ create 10 labels with StringVars that can be changed
            each time a new value is created
        """
        for ctr in range(10):
            var=StringVar()
            lab=Label(self.master, textvariable=var).grid(row=ctr)
            self.string_vars.append(var) ## the variables to be updated
            ## initial variable value
            self.values.append("***")  ## the values

master=Tk()
LabelTest(master)
master.mainloop()