【发布时间】:2021-07-17 19:59:13
【问题描述】:
我正在学习 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()
【问题讨论】:
-
你应该知道
update()是一个通用的方法。每个小部件都有这个方法。你甚至可以使用self.my_label.update()。您应该做的是,按照 helloworld14751 的回答
标签: python class user-interface tkinter label