回答編集履歴
2
変更!
test
CHANGED
@@ -40,9 +40,9 @@
|
|
40
40
|
|
41
41
|
self.pack()
|
42
42
|
|
43
|
-
self.task = tk.Button(self, text='task', command=self.task)
|
43
|
+
self.btn_task = tk.Button(self, text='task', command=self.task)
|
44
44
|
|
45
|
-
self.task.pack()
|
45
|
+
self.btn_task.pack()
|
46
46
|
|
47
47
|
|
48
48
|
|
1
ThreadPoolExecutorのサンプルを記載。
test
CHANGED
@@ -1,3 +1,95 @@
|
|
1
1
|
過去に回答したスレッドを使ったサンプルへのリンクを投下しておきます。
|
2
2
|
|
3
3
|
[Python/tkinterのフォームでメニューにより内容を消したり点けたりしたい](https://teratail.com/questions/111565)
|
4
|
+
|
5
|
+
|
6
|
+
|
7
|
+
---
|
8
|
+
|
9
|
+
スレッド生成のコストを気にしてらっしゃるみたいなので、`ThreadPoolExecutor`を使ったサンプルを記載します。
|
10
|
+
|
11
|
+
|
12
|
+
|
13
|
+
```Python
|
14
|
+
|
15
|
+
# -*- coding: utf-8 -*-
|
16
|
+
|
17
|
+
from concurrent.futures import ThreadPoolExecutor, Future, as_completed
|
18
|
+
|
19
|
+
from contextlib import closing
|
20
|
+
|
21
|
+
from threading import current_thread, get_ident
|
22
|
+
|
23
|
+
from time import sleep
|
24
|
+
|
25
|
+
from random import randint
|
26
|
+
|
27
|
+
import tkinter as tk
|
28
|
+
|
29
|
+
|
30
|
+
|
31
|
+
|
32
|
+
|
33
|
+
class MyFrame(tk.Frame):
|
34
|
+
|
35
|
+
def __init__(self, root):
|
36
|
+
|
37
|
+
super().__init__(root)
|
38
|
+
|
39
|
+
self.executor = ThreadPoolExecutor()
|
40
|
+
|
41
|
+
self.pack()
|
42
|
+
|
43
|
+
self.task = tk.Button(self, text='task', command=self.task)
|
44
|
+
|
45
|
+
self.task.pack()
|
46
|
+
|
47
|
+
|
48
|
+
|
49
|
+
def task(self):
|
50
|
+
|
51
|
+
seconds = randint(0, 10)
|
52
|
+
|
53
|
+
self.executor.submit(self.hardtask, seconds)
|
54
|
+
|
55
|
+
|
56
|
+
|
57
|
+
def hardtask(self, seconds):
|
58
|
+
|
59
|
+
print(f'tid:{get_ident()}, {current_thread().getName()}, {seconds}')
|
60
|
+
|
61
|
+
sleep(seconds)
|
62
|
+
|
63
|
+
|
64
|
+
|
65
|
+
def close(self):
|
66
|
+
|
67
|
+
self.executor.shutdown(wait=False)
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
|
72
|
+
|
73
|
+
def main() ->None:
|
74
|
+
|
75
|
+
root = tk.Tk()
|
76
|
+
|
77
|
+
root.title("ThreadPoolExecutor")
|
78
|
+
|
79
|
+
root.geometry("400x200")
|
80
|
+
|
81
|
+
with closing(MyFrame(root)) as f:
|
82
|
+
|
83
|
+
root.mainloop()
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
|
88
|
+
|
89
|
+
if __name__ == '__main__':
|
90
|
+
|
91
|
+
main()
|
92
|
+
|
93
|
+
|
94
|
+
|
95
|
+
```
|