2017-04-18 76 views
0

私は単純な例でtKinterでPython GUIを作成しました。カウンタをインクリメントする単純なループをトリガするボタンがあります。私はGUIが凍結しないようにカウンタをスレッド化しましたが、カウントを止めることに問題があります。私のコードは次のとおりです:tKinterマルチスレッドスレッドを停止する

# threading_example.py 
import threading 
from threading import Event 
import time 
from tkinter import Tk, Button 


root = Tk() 

class Control(object): 

    def __init__(self): 
     self.my_thread = None 
     self.stopThread = False 

    def just_wait(self): 
     while not self.stopThread: 
      for i in range(10000): 
       time.sleep(1) 
       print(i) 

    def button_callback(self): 
     self.my_thread = threading.Thread(target=self.just_wait) 
     self.my_thread.start() 

    def button_callbackStop(self): 
     self.stopThread = True 
     self.my_thread.join() 
     self.my_thread = None 


control = Control() 
button = Button(root, text='Run long thread.', command=control.button_callback) 
button.pack() 
button2 = Button(root, text='stop long thread.', command=control.button_callbackStop) 
button2.pack() 


root.mainloop() 

カウンタを増分して正常に閉じることができますか?

答えて

1

あなたはあなたがループとwhileループのために並列に実行したいforループ

+0

どうすればよいですか? – Vince

2

self.stopThreadをチェックする必要がありますか?まあ、彼らはできません。あなたが持っているので、forループは実行されており、whileループ条件には注意を払わないでしょう。

ループを1つだけ作成する必要があります。スレッドを10000サイクル後に自動的に終了させたい場合は、次のようにしてください:

def just_wait(self): 
    for i in range(10000): 
     if self.stopThread: 
      break # early termination 
     time.sleep(1) 
     print(i) 
+0

こんにちはJohnathanありがとう、私は脳のおならの瞬間を持っていた。 – Vince

関連する問題