如何在python中使用类更新gui

如何在python中使用类更新gui,python,class,user-interface,tkinter,label,Python,Class,User Interface,Tkinter,Label,我正在学习python,希望有一个GUI,当我按下按钮时,它可以将标签从一条消息更改为另一条消息。不使用类,我就可以编写这段代码,它工作得很好。该工作代码如下所示 from tkinter import * import time root = Tk() def calculate(): my_label.configure(text='Step 1...') root.update() time.sleep(1) my_label.configure(tex

我正在学习python,希望有一个GUI,当我按下按钮时,它可以将标签从一条消息更改为另一条消息。不使用类,我就可以编写这段代码,它工作得很好。该工作代码如下所示

from tkinter import *
import time

root = Tk()

def calculate():
    my_label.configure(text='Step 1...')
    root.update()
    time.sleep(1)
    my_label.configure(text='Step 2...')


my_button = Button(root,text='calculate',command=calculate)
my_button.pack()

my_label = Label(root,text='My label')
my_label.pack()

root.mainloop()
但是,当我想将其作为类时,我不知道如何更改行root.update()。 我认为它应该类似于master.update(),但这也会导致错误。如果没有这一行,我将只看到第二条消息(步骤2…),而无法看到第一条消息(步骤1…)。有人能帮我做这个吗。下面是我作为类创建的代码

from tkinter import *
import time

class Myclass:

    def __init__(self,master):
    
        self.my_button = Button(master,text='Calculate',command=self.calculate)
        self.my_button.pack()
    
        self.my_label = Label(master,text='My label')
        self.my_label.pack()
    
    def calculate(self):
        self.my_label.configure(text='Step 1...')
        time.sleep(1)

        # My problem is with this line. Don't know how to deal with it
        root.update()

        self.my_label.configure(text='Step 2...')

root = Tk()
b = Myclass(root)
root.mainloop()

我想你的意思是
根。在(1000)
之后:


谢谢你的帮助。这种方法是有效的。然而,我真正的代码将比这长得多,我将不得不多次更新标签。我不想每次更新标签时都停止函数并启动新函数。“计算”功能中是否有更新GUI的方法?@siriwatsoontaran该功能不会停止
after()
是非阻塞代码。在
after()之后放置
print('Blocker')
,您会注意到。您应该知道
update()
是一种通用方法。每个小部件都有这个方法。您甚至可以使用
self.my\u label.update()
。您应该做的是,按照helloworld14751的回答
from tkinter import *
import time


class Myclass:

    def __init__(self, master):
        self.my_button = Button(master, text='Calculate', command=self.calculate)
        self.my_button.pack()

        self.my_label = Label(master, text='My label')
        self.my_label.pack()

    def calculate(self):
        self.my_label.configure(text='Step 1...')
        # time.sleep(1)

        # My problem is with this line. Don't know how to deal with it
        # root.update()

        ## New code ##
        root.after(1000, self.config)

    def config(self):
        self.my_label.configure(text='Step 2...')


root = Tk()
b = Myclass(root)
root.mainloop()