如何在功能后停止 tkinter? [英] How do I stop tkinter after function?

查看:29
本文介绍了如何在功能后停止 tkinter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在停止提要"时遇到问题;取消参数似乎对 after 方法没有任何影响.尽管进给停止"被打印到控制台.

I'm having a problem stopping the 'feed'; the cancel argument doesn't seem to have any impact on the after method. Although "feed stopped" is printed to the console.

我正在尝试使用一个按钮来启动提要,另一个按钮可以停止提要.

I'm attempting to have one button that will start the feed and another that will stop the feed.

from Tkinter import Tk, Button
import random

    def goodbye_world():
        print "Stopping Feed"
        button.configure(text = "Start Feed", command=hello_world)
        print_sleep(True)

    def hello_world():
        print "Starting Feed"
        button.configure(text = "Stop Feed", command=goodbye_world)
        print_sleep()

    def print_sleep(cancel=False):
        if cancel==False:
            foo = random.randint(4000,7500)
            print "Sleeping", foo
            root.after(foo,print_sleep)
        else:
            print "Feed Stopped"


    root = Tk()
    button = Button(root, text="Start Feed", command=hello_world)

    button.pack()


    root.mainloop()

输出:

Starting Feed
Sleeping 4195
Sleeping 4634
Sleeping 6591
Sleeping 7074
Stopping Feed
Sleeping 4908
Feed Stopped
Sleeping 6892
Sleeping 5605

推荐答案

问题在于,即使您使用 True 调用 print_sleep 来停止循环,已经有一个待处理的工作等待解雇.按下停止按钮不会触发新作业,但旧作业仍然存在,当它调用自己时,它传入 False 导致循环继续.

The problem is that, even though you're calling print_sleep with True to stop the cycle, there's already a pending job waiting to fire. Pressing the stop button won't cause a new job to fire but the old job is still there, and when it calls itself, it passes in False which causes the loop to continue.

您需要取消挂起的作业,使其不运行.例如:

You need to cancel the pending job so that it doesn't run. For example:

def cancel():
    if self._job is not None:
        root.after_cancel(self._job)
        self._job = None

def goodbye_world():
    print "Stopping Feed"
    cancel()
    button.configure(text = "Start Feed", command=hello_world)

def hello_world():
    print "Starting Feed"
    button.configure(text = "Stop Feed", command=goodbye_world)
    print_sleep()

def print_sleep():
    foo = random.randint(4000,7500)
    print "Sleeping", foo
    self._job = root.after(foo,print_sleep)

注意:确保在某处初始化 self._job,例如在应用程序对象的构造函数中.

Note: make sure you initialize self._job somewhere, such as in the constructor of your application object.

这篇关于如何在功能后停止 tkinter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆