簡體   English   中英

Tkinter python多線程(避免“無響應”)

[英]Tkinter python multithread (avoid “Not Responding”)

我正在嘗試使用tkinter編寫Python GUI程序。

我想做兩個線程。 一種與main_form函數一起運行,以防止tkinter保持更新和循環(避免“無響應”)。

另一個,當單擊button1(btn1)時,使函數sci_thread()開始運行,並啟動執行帶有長時間代碼的main_scikit的thread2。

但是,tkinter保持不響應。

下面是我的代碼:

import threading

class class_one:
    def main_scikit(seft):
        ######
        code_take_loooong_time
        ######
    def save(seft):
        pass

    def main_form(seft):
        root = Tk(  )
        root.minsize(width=300, height=500)
        ent1 = Entry(width=30)
        ent1.grid(row=0,column=1,padx = 10,pady=5)
        bnt1 = Button(root,text = "Start",command=lambda : seft.sci_thread())
        bnt1.grid(row=5,column=0,padx = 10) 

        root.update() 
        root.mainloop()

    def sci_thread(seft):
        maincal = threading.Thread(2,seft.main_scikit())
        maincal.start()

co = class_one()
mainfz = threading.Thread(1,co.main_form());
mainfz.start() 

您的應用沒有響應,因為您的目標參數在聲明時執行,並將該結果作為target傳遞。 而且,很顯然,由於這個原因,在GUI線程中執行code_take_loooong_time時,GUI沒有響應。 要處理它-刪除多余的括號。

試試以下代碼片段:

import threading

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk


class class_one:
    def main_scikit(self):
        ######
        # code_take_loooong_time
        # same as sleep
        threading.Event().wait(5)
        # some print
        self.print_active_threads_count()

        ######
    def save(self):
        pass

    def main_form(self):

        self.root = tk.Tk()
        self.root.minsize(width=300, height=500)
        self.ent1 = tk.Entry(self.root, width=30)
        self.ent1.grid(row=0, column=1, padx=10, pady=5)
        self.bnt1 = tk.Button(self.root, text="Start", command=self.sci_thread)
        self.bnt1.grid(row=5, column=0, padx=10)

        self.root.update()
        self.root.mainloop()

    def sci_thread(self):
        maincal = threading.Thread(target=self.main_scikit)
        maincal.start()

    def print_active_threads_count(self):
        msg = 'Active threads: %d ' % threading.active_count()

        self.ent1.delete(0, 'end')
        self.ent1.insert(0, msg)
        print(msg)


co = class_one()
mainfz = threading.Thread(target=co.main_form)
mainfz.start() 

鏈接:

PS:另外,在不在主線程中啟動tkinter應用程序時要小心,因為mainloop期望(一般而言) mainloop是最外層循環,並且所有Tcl命令都是從同一線程調用的。 因此, 即使您只是試圖退出GUI ,所有這些同步問題也可能會越來越多。 總之,也許會給你一些新的思路。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM