我想知道如何作業after()以及multiprocessing使用 tkinter。這是一個偽示例
import asyncio
import tkinter as tk
import multiprocessing as mp
class pseudo_example():
def app(self):
self.root = tk.Tk()
self.root.minsize(100,100)
# multiprocessing
start_button = tk.Button(self.root, text="start", command=lambda: mp.Process(target=self.create_await_fun).start())
# regular call
#start_button = tk.Button(self.root, text="start", command = self.create_await_fun())
start_button.pack()
self.testfield = tk.Label(self.root, text="test")
self.testfield.pack()
self.root.mainloop()
def create_await_fun(self):
asyncio.run(self.await_fun())
async def await_fun(self):
# cross communication between two threads doesn't work jet
#self.testfield["text"] = "start waiting"
#self.root.update_idletasks()
print("start waiting")
await asyncio.sleep(10)
print("end waiting")
#self.testfield["text"] = "end waiting"
#self.root.update_idletasks()
if __name__ == '__main__':
gui = pseudo_example()
gui.app()
現在我有幾個問題。當我像這樣運行程式時,GUI 不會凍結,我會得到“列印”輸出。現在我不想獲得列印輸出,但我想與 GUI 通信并更新標簽而不凍結 GUI。現在我聽說了這個after()方法,但我也讀到這個方法不會呼叫新執行緒,而是延遲了 GUI 的阻塞。如果我正確理解了這一點。此外,我還讀到 tkinter 通常是單執行緒。盡管如此,是否有可能將 IO 任務與 GUI 分離?為此,我必須使用 mainloop() 之外的任務嗎?
在此條目Tkinter 理解 mainloop中有一個 after()方法示例,但我無法為我派生應用程式。這是另一個處理該主題的鏈接,但無法具體幫助我。
uj5u.com熱心網友回復:
關于https://stackoverflow.com/a/47920128/15959848我解決了我的問題。
class pseudo_example():
def app(self,async_loop):
self.root = tk.Tk()
self.root.minsize(100,100)
self.start_button = tk.Button(self.root, text="start", command=lambda: self.create_await_fun(async_loop))
self.start_button.pack()
self.testfield = tk.Label(self.root, text="output")
self.testfield.pack()
self.root.mainloop()
def create_await_fun(self,async_loop):
threading.Thread(target=self.asyncio_thread, args=(async_loop,)).start()
self.start_button["relief"] = "sunken"
self.start_button["state"] = "disabled"
def asyncio_thread(self, async_loop):
async_loop.run_until_complete(self.await_fun())
async def await_fun(self):
self.testfield["text"] = "start waiting"
self.root.update_idletasks()
await asyncio.sleep(2)
self.testfield["text"] = "end waiting"
self.root.update_idletasks()
await asyncio.sleep(1)
self.testfield["text"] = "output"
self.root.update_idletasks()
self.start_button["relief"] = "raised"
self.start_button["state"] = "normal"
if __name__ == '__main__':
gui = pseudo_example()
async_loop = asyncio.get_event_loop()
gui.app(async_loop)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/455123.html
