周期性中断 Python

发布于 2025-01-11 16:09:22 字数 503 浏览 0 评论 0原文

我通过这段代码总结了我的问题。当我通过关闭 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半世蒼涼 2025-01-18 16:09:22

处理这个问题的另一种方法是使线程成为“守护进程”。当应用程序退出时,守护线程将被强制关闭;它不会阻止该应用程序。

threading.Thread(target=loop1_10, daemon=True).start()
threading.Thread(target=loop1_10_b, daemon=True).start()

请注意,我并不是说其中一个比另一个更好或更差。每个选项都有其用途。

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.

threading.Thread(target=loop1_10, daemon=True).start()
threading.Thread(target=loop1_10_b, daemon=True).start()

Note that I'm not saying one is better or worse than the other. Each option has its uses.

稚气少女 2025-01-18 16:09:22

将协议 WM_DELETE_WINDOW 添加到您的 MainWindow,您可以在其中定义您定义的函数 on_close(),一旦 tkinter 窗口被调用,该函数就会被调用已关闭。

on_close() 函数会将全局变量 endFalse 重新定义为 True,并且在每个 for循环中,如果end变量的值为True,则return出其中:

import threading
import time
from tkinter import *

def loop1_10():
    for i in range(1, 11):
        if end:
            return
        time.sleep(1)
        print(i)

def loop1_10_b():
    for i in range(1, 11):
        if end:
            return
        time.sleep(2)
        print(i)

end = False
def on_closing():
    global end
    end = True
    MainWindow.destroy()

threading.Thread(target=loop1_10).start()
threading.Thread(target=loop1_10_b).start()

MainWindow = Tk()
MainWindow.protocol("WM_DELETE_WINDOW", on_closing)
MainWindow.mainloop()

但是上面还是有问题代码;如果 end = True 发生在 time.sleep() 调用之前,则最后一次 time.sleep()仍然会让程序在终止之前等待一两秒钟。

要解决此问题,请使用 time.time()while 循环在继续每个 for 循环之前手动检查已经过去了多少时间:

import threading
import time
from tkinter import *

def loop1_10():
    for i in range(1, 11):
        old_time = time.time()
        while True:
            if end:
                return
            if time.time() - old_time < 1:
                continue
            break
        print(i)

def loop1_10_b():
    for i in range(1, 11):
        old_time = time.time()
        while True:
            if end:
                return
            if time.time() - old_time < 2:
                continue
            break
        print(i)

end = False
def on_closing():
    global end
    end = True
    MainWindow.destroy()

threading.Thread(target=loop1_10).start()
threading.Thread(target=loop1_10_b).start()

MainWindow = Tk()
MainWindow.protocol("WM_DELETE_WINDOW", on_closing)
MainWindow.mainloop()

但是请注意@kindall 的评论:

使用 time.time() 和 while 循环——不要这样做,它会耗尽整个 CPU 核心来等待循环退出。这不仅会不必要地消耗电池,而且由于全局解释器锁,Python 仅使用一个 CPU 核心,它也会使程序的其余部分变得缓慢

Add a protocol, WM_DELETE_WINDOW, to your MainWindow, 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 variable end from False into True, and in each for loop, if the end variable's value is True, return out of them:

import threading
import time
from tkinter import *

def loop1_10():
    for i in range(1, 11):
        if end:
            return
        time.sleep(1)
        print(i)

def loop1_10_b():
    for i in range(1, 11):
        if end:
            return
        time.sleep(2)
        print(i)

end = False
def on_closing():
    global end
    end = True
    MainWindow.destroy()

threading.Thread(target=loop1_10).start()
threading.Thread(target=loop1_10_b).start()

MainWindow = Tk()
MainWindow.protocol("WM_DELETE_WINDOW", on_closing)
MainWindow.mainloop()

But there is still a problem with the above code; if the end = True happened right before the time.sleep() call(s), the last time.sleep()(s) will still make the program wait for a second or two before terminating.

To fix this, use time.time() and a while loop to manually check how much time has passed before continuing each for loop:

import threading
import time
from tkinter import *

def loop1_10():
    for i in range(1, 11):
        old_time = time.time()
        while True:
            if end:
                return
            if time.time() - old_time < 1:
                continue
            break
        print(i)

def loop1_10_b():
    for i in range(1, 11):
        old_time = time.time()
        while True:
            if end:
                return
            if time.time() - old_time < 2:
                continue
            break
        print(i)

end = False
def on_closing():
    global end
    end = True
    MainWindow.destroy()

threading.Thread(target=loop1_10).start()
threading.Thread(target=loop1_10_b).start()

MainWindow = Tk()
MainWindow.protocol("WM_DELETE_WINDOW", on_closing)
MainWindow.mainloop()

But do note from this comment by @kindall:

use time.time() and a while loop -- don't do this, it'll use up an entire CPU core waiting for the loop to exit. this will not only eat battery unnecessarily, but since Python only uses one CPU core due to the Global Interpreter Lock, it will make the rest of the program sluggish, too

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文