周期性中断 Python
我通过这段代码总结了我的问题。当我通过关闭 tkinter 主窗口来结束程序时,我需要整个程序结束,但循环会继续执行,直到函数结束。我想也有一种方法可以强制这些功能结束。我认为有一种方法可以检测程序是否结束,这样我就可以结束这些功能。
import threading
import time
from tkinter import *
def loop1_10():
for i in range(1, 11):
time.sleep(1)
print(i)
def loop1_10_b():
for i in range(1, 11):
time.sleep(2)
print(i)
threading.Thread(target=loop1_10).start()
threading.Thread(target=loop1_10_b).start()
MainWindow = Tk()
MainWindow.mainloop()
I sumarize my problem through this piece of code. When I end my program by closing the tkinter main window, I need the whole program ends, but the loops goes on executing until the functions is over. I suppose there is a way to force these functions ends too. I think there is a way to detect the program was ended, so I could end the functions.
import threading
import time
from tkinter import *
def loop1_10():
for i in range(1, 11):
time.sleep(1)
print(i)
def loop1_10_b():
for i in range(1, 11):
time.sleep(2)
print(i)
threading.Thread(target=loop1_10).start()
threading.Thread(target=loop1_10_b).start()
MainWindow = Tk()
MainWindow.mainloop()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
处理这个问题的另一种方法是使线程成为“守护进程”。当应用程序退出时,守护线程将被强制关闭;它不会阻止该应用程序。
请注意,我并不是说其中一个比另一个更好或更差。每个选项都有其用途。
The other way to handle this is to make the threads "daemons". A daemon thread will be forcibly closed when the app exits; it doesn't block the app.
Note that I'm not saying one is better or worse than the other. Each option has its uses.
将协议
WM_DELETE_WINDOW
添加到您的MainWindow
,您可以在其中定义您定义的函数on_close()
,一旦 tkinter 窗口被调用,该函数就会被调用已关闭。on_close()
函数会将全局变量end
从False
重新定义为True
,并且在每个for
循环中,如果end
变量的值为True
,则return
出其中:但是上面还是有问题代码;如果
end = True
发生在time.sleep()
调用之前,则最后一次time.sleep()
仍然会让程序在终止之前等待一两秒钟。要解决此问题,请使用
time.time()
和while
循环在继续每个for
循环之前手动检查已经过去了多少时间:但是请注意@kindall 的评论:
Add a protocol,
WM_DELETE_WINDOW
, to yourMainWindow
, where you use define a function you defined,on_close()
that gets called once the tkinter window is closed.The
on_close()
function will redefine the global variableend
fromFalse
intoTrue
, and in eachfor
loop, if theend
variable's value isTrue
,return
out of them:But there is still a problem with the above code; if the
end = True
happened right before thetime.sleep()
call(s), the lasttime.sleep()
(s) will still make the program wait for a second or two before terminating.To fix this, use
time.time()
and awhile
loop to manually check how much time has passed before continuing eachfor
loop:But do note from this comment by @kindall: