我是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()**
。我怎样才能解决这个问题?一旦我开始工作,我想用图像向用户显示其OFF ON和BUSY。请帮帮我
答案 0 :(得分: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建议的线程。
答案 1 :(得分:0)
您必须创建一个主题,以便在界面工作时使您充当“后台事件”。考虑使用它:
from threading import Thread
然后:
my_thread=Thread(target=start())
my_thread.start()
第一个“start()”是你的函数的名字,第二个是调用线程的开始。