2012-03-19 3 views
6

'피드'를 중지하는 데 문제가 있습니다. cancel 인수는 after 메서드에 영향을 미치지 않는 것 같습니다. "피드 중지됨"이 콘솔에 인쇄되지만.기능 후에 tkinter를 중지하려면 어떻게합니까?

피드를 시작하는 버튼 하나와 피드를 중지시킬 버튼이 하나 있습니다. 출력과

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

: 당신이 root.after(...)를 호출 할 때

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

tkinter의 작동 방식에 대해서는 완전히 확신 할 수 없지만이 문제는 나에게 스레딩 문제와 매우 유사합니다. a (thread safe) 전역을 취소 할 경우 문제가 해결됩니까? – mklauber

+0

@mklauber : 아니오, 스레딩 문제가 아닙니다. Tkinter는 단일 스레드입니다. –

+0

@BryanOakley : 감사합니다. 이것이 제가 코멘트로 올린 이유입니다. 나는 그 질문을 제기하기를 원했기 때문에 확실하지 않았다. – mklauber

답변

13

print_sleepTrue으로 지정하여주기를 중지해도 이미 대기중인 대기중인 작업이 있습니다. 중지 단추를 눌러도 새 작업이 실행되지 않지만 이전 작업은 그대로 남아 있으며 자신을 호출하면 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를 초기화해야합니다.

13

,이 식별자를 반환합니다. 해당 식별자를 추적해야합니다 (예 : 인스턴스 변수에 저장). 나중에 root.after_cancel(after_id)으로 전화하여이를 취소 할 수 있습니다.

관련 문제