回答編集履歴

1

補足

2018/09/19 06:24

投稿

umyu
umyu

スコア5846

test CHANGED
@@ -9,3 +9,173 @@
9
9
  th.Thread(target = self.loop).start()
10
10
 
11
11
  ```
12
+
13
+
14
+
15
+ ---
16
+
17
+
18
+
19
+ 別解)スレッドを使わなくても、[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)などでも。
20
+
21
+
22
+
23
+ 以下は`after`を使ったサンプルコードです。
24
+
25
+
26
+
27
+ ```Python
28
+
29
+ # -*- coding: utf8 -*-
30
+
31
+ # coding=UTF-8
32
+
33
+ import sys
34
+
35
+ import time
36
+
37
+ import tkinter as tk
38
+
39
+
40
+
41
+ stop_flg = False
42
+
43
+ ROOT = tk.Tk()
44
+
45
+
46
+
47
+
48
+
49
+ def stop_watch():
50
+
51
+ timer_start = time.time()
52
+
53
+
54
+
55
+ def elapsed():
56
+
57
+ timer_lap = time.time() - timer_start
58
+
59
+ out_lap = round(timer_lap, 2)
60
+
61
+ return out_lap
62
+
63
+ return elapsed
64
+
65
+
66
+
67
+
68
+
69
+ class SSW(tk.Frame):
70
+
71
+ def __init__(self, master = None):
72
+
73
+ super().__init__(master)
74
+
75
+ self.master.title("Sample Stop Watch")
76
+
77
+ self.master.bind("<Control-q>", self.quit)
78
+
79
+ self.master.geometry("280x160")
80
+
81
+ # masterではなく、親コンポーネントはselfで。
82
+
83
+ self.lbl_msg = tk.Label(self, text="<quit:Control-q>")
84
+
85
+ self.lbl_msg.pack(side = "top")
86
+
87
+ self.lbl_lap = tk.Label(self, text="0.00")
88
+
89
+ self.lbl_lap.pack(side = "top")
90
+
91
+
92
+
93
+ self.btn_run = tk.Button(self, text="run", command = self.run)
94
+
95
+ self.btn_run.pack()
96
+
97
+ self.btn_end = tk.Button(self, text="end", command = self.end)
98
+
99
+ self.btn_end.pack()
100
+
101
+ self.btn_quit = tk.Button(self, text="quit", command = self.quit)
102
+
103
+ self.btn_quit.pack()
104
+
105
+
106
+
107
+ def loop(self):
108
+
109
+ self.lbl_lap.configure(text=self.clock())
110
+
111
+ if not stop_flg:
112
+
113
+ # 次のイベント呼び出しを予約
114
+
115
+ self.after(1000, self.loop)
116
+
117
+
118
+
119
+ def run(self):
120
+
121
+ global stop_flg
122
+
123
+ print('Start!')
124
+
125
+ stop_flg = False
126
+
127
+ self.clock = stop_watch()
128
+
129
+ #
130
+
131
+ self.after(0, self.loop)
132
+
133
+
134
+
135
+ def end(self):
136
+
137
+ global stop_flg
138
+
139
+ print('Stop!')
140
+
141
+ stop_flg = True
142
+
143
+
144
+
145
+ def quit(self):
146
+
147
+ sys.exit()
148
+
149
+
150
+
151
+
152
+
153
+ # main
154
+
155
+ if __name__ == '__main__':
156
+
157
+ ss = SSW(ROOT)
158
+
159
+ ss.pack()
160
+
161
+ ss.mainloop()
162
+
163
+ ```
164
+
165
+
166
+
167
+ Python言語のスレッドは他の言語と違って、IO律速の処理の高速化に使われることが多いです。
168
+
169
+ ■参考情報
170
+
171
+ |並列方法|律速ポイント|GILの制限|データの受け渡し|
172
+
173
+ |:--|:--:|:--:|:--|
174
+
175
+ |プロセス|演算律速|影響を受けない|pickle可能なオブジェクト|
176
+
177
+ |スレッド|IO律速|影響を受ける|制約なし|
178
+
179
+
180
+
181
+ ※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)といいます。