【问题标题】:How to update gui using class in python如何在python中使用类更新gui
【发布时间】: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


【解决方案1】:

我想你的意思是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()

【讨论】:

  • 感谢您的帮助。这种方法是有效的。但是,我的真实代码会比这长得多,我将不得不多次更新标签。每次更新标签时,我都不想停止该功能并启动新功能。是否有在“计算”功能中更新 GUI 的方法?
  • @SiriwatSoontaranon 该功能不会停止。 after() 是非阻塞代码。在after() 后面加上print('Blocker') 你会注意到的。
猜你喜欢
  • 2020-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 2014-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多