복붙노트

[PYTHON] 기능 후에 tkinter를 중지하려면 어떻게합니까?

PYTHON

기능 후에 tkinter를 중지하려면 어떻게합니까?

'먹이'를 멈추는 데 문제가 있습니다. cancel 인수는 after 메서드에 영향을 미치지 않는 것 같습니다. "피드 중지됨"이 콘솔에 인쇄되지만.

피드를 시작하는 버튼 하나와 피드를 멈추게 할 버튼이 하나 있습니다.

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

해결법

  1. ==============================

    1.문제는주기를 멈추기 위해 print_sleep을 True로 호출하더라도 발포 대기중인 대기중인 작업이 이미 있다는 것입니다. 중지 단추를 눌러도 새 작업이 실행되지 않지만 이전 작업은 그대로 남아 있으며 자신을 호출하면 False로 전달되어 루프가 계속됩니다.

    문제는주기를 멈추기 위해 print_sleep을 True로 호출하더라도 발포 대기중인 대기중인 작업이 이미 있다는 것입니다. 중지 단추를 눌러도 새 작업이 실행되지 않지만 이전 작업은 그대로 남아 있으며 자신을 호출하면 False로 전달되어 루프가 계속됩니다.

    보류 중 작업이 실행되지 않도록 취소해야합니다. 예 :

    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을 어딘가에 초기화해야합니다.

  2. ==============================

    2.root.after (...)를 호출하면 식별자를 반환합니다. 해당 식별자를 추적해야합니다 (예 : 인스턴스 변수에 저장). 그런 다음 나중에 root.after_cancel (after_id)을 호출하여이를 취소 할 수 있습니다.

    root.after (...)를 호출하면 식별자를 반환합니다. 해당 식별자를 추적해야합니다 (예 : 인스턴스 변수에 저장). 그런 다음 나중에 root.after_cancel (after_id)을 호출하여이를 취소 할 수 있습니다.

  3. from https://stackoverflow.com/questions/9776718/how-do-i-stop-tkinter-after-function by cc-by-sa and MIT license