前提・実現したいこと
ボタンを押すとループで1から3までカウントし始めて、ボタンを押しなおすとカウントを中止し、また最初から1から3までカウントする といったプログラムを作っています
ボタンを押すとthreadingでループするメソッドを呼び出し、ボタンをもう一度押すとループを停止するフラグを成立させてまたループするメソッドを呼び出そうとしていますがうまく行きません
該当のソースコード
python3
1import threading 2import tkinter as tk 3import time 4 5LoopFlg=True 6 7def Count(): 8 global LoopFlg 9 LoopFlg=True 10 while LoopFlg==True: 11 if LoopFlg!=True: 12 break 13 time.sleep(1) 14 if LoopFlg!=True: 15 break 16 print(1) 17 18 time.sleep(1) 19 if LoopFlg!=True: 20 break 21 print(2) 22 23 if LoopFlg!=True: 24 break 25 time.sleep(1) 26 print(3) 27 28def Call_Count(): 29 global LoopFlg 30 LoopFlg=False 31 threading.Thread(target=Count).start() 32 33root=tk.Tk() 34button=tk.Button(root,text="Count",command=Call_Count) 35button.pack() 36root.mainloop() 37
発生している問題・エラーメッセージ
ボタンを押しなおすと以前のループは停止せず、そのままカウントし始めるのでその結果複数のループが発生してしまいます
試したこと
https://qiita.com/xeno1991/items/b207d55a413664513e5f
のサイトをちょっと読んで真似てみたのですがうまく行きませんでした。
多分、time.sleep()によって処理が止まっている間にボタン押してもループはフラグ成立したことが分からないからなのかなぁ・・・?
import threading import tkinter as tk import time class App(): def __init__(self): self.stop_event = threading.Event() #停止させるかのフラグ root=tk.Tk() button=tk.Button(root,text="Count",command=self.call_count) button.pack() root.mainloop() def call_count(self): self.stop_event.set() self.stop_event = threading.Event() threading.Thread(target = self.target).start() def target(self): while not self.stop_event.is_set(): time.sleep(1) if self.stop_event.is_set(): break print(1) if self.stop_event.is_set(): break time.sleep(1) if self.stop_event.is_set(): break print(2) time.sleep(1) if self.stop_event.is_set(): break print(3) app=App()
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/01 06:58