過去に回答したスレッドを使ったサンプルへのリンクを投下しておきます。
Python/tkinterのフォームでメニューにより内容を消したり点けたりしたい
スレッド生成のコストを気にしてらっしゃるみたいなので、ThreadPoolExecutor
を使ったサンプルを記載します。
Python
1# -*- coding: utf-8 -*-
2from concurrent.futures import ThreadPoolExecutor, Future, as_completed
3from contextlib import closing
4from threading import current_thread, get_ident
5from time import sleep
6from random import randint
7import tkinter as tk
8
9
10class MyFrame(tk.Frame):
11 def __init__(self, root):
12 super().__init__(root)
13 self.executor = ThreadPoolExecutor()
14 self.pack()
15 self.btn_task = tk.Button(self, text='task', command=self.task)
16 self.btn_task.pack()
17
18 def task(self):
19 seconds = randint(0, 10)
20 self.executor.submit(self.hardtask, seconds)
21
22 def hardtask(self, seconds):
23 print(f'tid:{get_ident()}, {current_thread().getName()}, {seconds}')
24 sleep(seconds)
25
26 def close(self):
27 self.executor.shutdown(wait=False)
28
29
30def main() ->None:
31 root = tk.Tk()
32 root.title("ThreadPoolExecutor")
33 root.geometry("400x200")
34 with closing(MyFrame(root)) as f:
35 root.mainloop()
36
37
38if __name__ == '__main__':
39 main()
40
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/04/22 02:41
2018/04/22 06:32