如何在python中使用类更新gui



我正在学习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()

我想你指的是root.after(1000):

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()

最新更新