teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

補足

2018/09/19 06:24

投稿

umyu
umyu

スコア5846

answer CHANGED
@@ -3,4 +3,89 @@
3
3
 
4
4
  ```Python
5
5
  th.Thread(target = self.loop).start()
6
- ```
6
+ ```
7
+
8
+ ---
9
+
10
+ 別解)スレッドを使わなくても、[after](http://www.geocities.jp/m_hiroi/light/pytk07.html)を使う形でも可能です。あとは[イベントスケジューラ](https://docs.python.org/ja/3.7/library/sched.html)、[dbader/schedule](https://github.com/dbader/schedule)などでも。
11
+
12
+ 以下は`after`を使ったサンプルコードです。
13
+
14
+ ```Python
15
+ # -*- coding: utf8 -*-
16
+ # coding=UTF-8
17
+ import sys
18
+ import time
19
+ import tkinter as tk
20
+
21
+ stop_flg = False
22
+ ROOT = tk.Tk()
23
+
24
+
25
+ def stop_watch():
26
+ timer_start = time.time()
27
+
28
+ def elapsed():
29
+ timer_lap = time.time() - timer_start
30
+ out_lap = round(timer_lap, 2)
31
+ return out_lap
32
+ return elapsed
33
+
34
+
35
+ class SSW(tk.Frame):
36
+ def __init__(self, master = None):
37
+ super().__init__(master)
38
+ self.master.title("Sample Stop Watch")
39
+ self.master.bind("<Control-q>", self.quit)
40
+ self.master.geometry("280x160")
41
+ # masterではなく、親コンポーネントはselfで。
42
+ self.lbl_msg = tk.Label(self, text="<quit:Control-q>")
43
+ self.lbl_msg.pack(side = "top")
44
+ self.lbl_lap = tk.Label(self, text="0.00")
45
+ self.lbl_lap.pack(side = "top")
46
+
47
+ self.btn_run = tk.Button(self, text="run", command = self.run)
48
+ self.btn_run.pack()
49
+ self.btn_end = tk.Button(self, text="end", command = self.end)
50
+ self.btn_end.pack()
51
+ self.btn_quit = tk.Button(self, text="quit", command = self.quit)
52
+ self.btn_quit.pack()
53
+
54
+ def loop(self):
55
+ self.lbl_lap.configure(text=self.clock())
56
+ if not stop_flg:
57
+ # 次のイベント呼び出しを予約
58
+ self.after(1000, self.loop)
59
+
60
+ def run(self):
61
+ global stop_flg
62
+ print('Start!')
63
+ stop_flg = False
64
+ self.clock = stop_watch()
65
+ #
66
+ self.after(0, self.loop)
67
+
68
+ def end(self):
69
+ global stop_flg
70
+ print('Stop!')
71
+ stop_flg = True
72
+
73
+ def quit(self):
74
+ sys.exit()
75
+
76
+
77
+ # main
78
+ if __name__ == '__main__':
79
+ ss = SSW(ROOT)
80
+ ss.pack()
81
+ ss.mainloop()
82
+ ```
83
+
84
+ Python言語のスレッドは他の言語と違って、IO律速の処理の高速化に使われることが多いです。
85
+ ■参考情報
86
+ |並列方法|律速ポイント|GILの制限|データの受け渡し|
87
+ |:--|:--:|:--:|:--|
88
+ |プロセス|演算律速|影響を受けない|pickle可能なオブジェクト|
89
+ |スレッド|IO律速|影響を受ける|制約なし|
90
+
91
+ ※GILは[グローバルインタプリタロック](https://ja.wikipedia.org/wiki/%E3%82%B0%E3%83%AD%E3%83%BC%E3%83%90%E3%83%AB%E3%82%A4%E3%83%B3%E3%82%BF%E3%83%97%E3%83%AA%E3%82%BF%E3%83%AD%E3%83%83%E3%82%AF)といいます。