【发布时间】:2018-09-10 13:12:38
【问题描述】:
我是 python 新手,一直试图通过单击暂停按钮来暂停我的代码,并在单击恢复按钮后立即恢复它。但是即使我在函数调用之前定义了按钮,但在执行过程中也不会出现。我的代码如下:
from tkinter import *
from time import sleep
master = Tk()
frame = Frame(master)
frame.grid()
global is_asleep
def important_function():
i=0
while(True):
print(i)
i = i+1
sleep(1)
def pause():
#pause the execution
try:
is_asleep = True
while(is_asleep):
sleep(1)
except:
print('Error Occured')
def resume():
is_asleep = False
def stop():
#stop the execution
try:
print('Stop')
exit()
except:
print('Error Occured')
pause = Button(frame, text = "Pause", command = pause).grid()
stop = Button(frame, text = "Stop", command = stop).grid()
resume = Button(frame, text = "Resume", command = resume).grid()
important_function()
master.mainloop()
请帮助我了解我哪里出错了。
【问题讨论】:
-
看起来您将陷入
important_function内的while 循环,永远无法到达master.mainloop()。是否有任何窗口出现或只是没有按钮? -
只是没有窗口,也没有任何按钮出现。@busybear
-
您需要执行
master.mainloop()才能让您的 GUI 工作/显示。如果不清楚为什么会发生这种情况,我建议查看 tkinter 的工作原理。我不确定你想用important_function完成什么,但使用after可能有用:stackoverflow.com/questions/25753632/… -
嘿,谢谢@busybear!我这样做了:
pause = Button(master, text = "Pause", command = pause).grid() \n stop = Button(master, text = "Stop", command = stop).grid()\n resume = Button(master, text = "Resume", command = resume).grid() \n master.after(100,important_function) \n master.mainloop()它似乎可以帮助我显示按钮! -
sleep就像它所说的那样:它使整个应用程序进入睡眠状态。这意味着它不能处理事件、刷新屏幕等。
标签: python events button tkinter event-handling