忙时设置按钮文本

2024-06-24 12:12:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我正在尝试创建一个程序,但我甚至不能正确地掌握基本知识。我有一个按钮应用程序,看起来像这样:

#simple GUI
from tkinter import *
import time

#create the window
root = Tk()

#modify root window
root.title("Button Example")
root.geometry("200x50")

button1state = 0

def start():
    count = 0
    button1["text"] ="Busy!"
    while (count < 5):
        root.after(1000)
        count = count + 1

def button1clicked():
    global button1state
    if button1state == 0:
        start()
        button1["text"] ="On!"
        button1state = 1
    else:
        button1["text"] ="Off!"
        button1state = 0

app = Frame(root)
app.pack()

button1 = Button(app, text ="Off!", command = button1clicked)
button1.pack()

#kick off the event loop
root.mainloop()

现在一切正常,除了它不会改变按钮文字忙而 **start()**被调用。我怎样才能解决这个问题?一旦我得到了它的工作,我想用图像来显示用户,它的关闭和繁忙。请帮帮我


Tags: thetextimportappdefcountbuttonroot
2条回答

在开始任务之前,需要强制更新GUI:

def start():
    count = 0
    button1.configure(text="Busy!")
    root.update()  # <  update window
    while (count < 5):
        root.after(1000)
        count = count + 1

但是,如果您不希望在执行任务时冻结GUI,则需要使用Dedi建议的线程。你知道吗

当你的接口工作时,你必须创建一个线程,使你成为一个“后台事件”。考虑使用:

from threading import Thread

然后:

my_thread=Thread(target=start())
my_thread.start()

其中第一个“start()”是函数名,第二个是线程开始调用。你知道吗

相关问题 更多 >