在Python中结束函数

2024-09-28 01:32:45 发布

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

我在python中有一个使用Tkinter的循环函数,当我使用Tkinter按下按钮时,它不会结束。它继续执行按钮指定的新函数,但也继续执行旧函数

以下是代码(其中的一部分):

def countdown(self):

        if self.seconds <= 0:
            if self.minutes > 0:
                self.seconds += 59
                self.minutes -= 1
            elif self.minutes == 0:
                if self.hours != 0:
                    self.minutes += 59
                    self.seconds += 59
                    self.hours -= 1
                else:
                    self.timerLab.configure(text="Times Up!")

        self.timerLab.configure(text="Time Remaining: %d:%d:%d " % (self.hours,self.minutes,self.seconds))
        self.seconds -= 1
        self.after(1000, self.countdown)

一旦按下另一个按钮,我该如何结束这一切呢。是否有什么东西结束了当前的进程?在


Tags: 函数代码textselfiftkinterconfiguredef
3条回答

Tkinter用^{}方法提供了这个问题的解决方案。您必须存储after返回的“after identifier”并将其传递给after_cancel

def start_countdown(self):
    if self.after_id is not None:
        self.after_cancel(self.after_id)
    self.countdown()

def countdown(self):
    # ...
    self.after_id = self.after(1000, self.countdown)

有一个设置变量的按钮。让您的倒计时函数检查该变量,只有在变量设置为特定值时才重新调度自己。在

像这样:

def __init__(self):
    ...
    self.running = False

    start_button = Button(..., self.start, ...)
    quit_button = Button(..., self.stop, ...)

def start(self):
    self.running = True;
    self.countdown()

def stop(self):
    self.running = False;

def countdown(self):
    ...
    if (self.running):
        self.after(1000, self.countdown)

如果您可以用Ctrl+C停止它,有很多方法可以实现这一点。我不是这方面的专家,但从谷歌的一个快速搜索来看,类似这样的东西可能会奏效:

import signal 
import sys
import subprocess

def signal_handler(signal, frame):
    print 'You pressed Ctrl+C!'
    sys.exit(0)

还有一个this解决方案,它存在于ESC上(您只需将27更改为另一个键的编号即可更改):

^{pr2}$

我希望这有帮助。在

相关问题 更多 >

    热门问题