Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

python - How do I stop tkinter after function?

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()

With the output:

Starting Feed
Sleeping 4195
Sleeping 4634
Sleeping 6591
Sleeping 7074
Stopping Feed
Sleeping 4908
Feed Stopped
Sleeping 6892
Sleeping 5605
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...