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