Trying to fix tkinter GUI freeze-ups (using threads)

前端 未结 3 531
谎友^
谎友^ 2020-12-04 02:57

I have a Python 3.x report creator that is so I/O bound (due to SQL, not python) that the main window will \"lock up\" for minutes while the reports are being creat

3条回答
  •  长情又很酷
    2020-12-04 03:43

    You'll need two functions: the first encapsulates your program's long-running work, and the second creates a thread that handles the first function. If you need the thread to stop immediately if the user closes the program while the thread is still running (not recommended), use the daemon flag or look into Event objects. If you don't want the user to be able to call the function again before it's finished, disable the button when it starts and then set the button back to normal at the end.

    import threading
    import tkinter as tk
    import time
    
    class App:
        def __init__(self, parent):
            self.button = tk.Button(parent, text='init', command=self.begin)
            self.button.pack()
        def func(self):
            '''long-running work'''
            self.button.config(text='func')
            time.sleep(1)
            self.button.config(text='continue')
            time.sleep(1)
            self.button.config(text='done')
            self.button.config(state=tk.NORMAL)
        def begin(self):
            '''start a thread and connect it to func'''
            self.button.config(state=tk.DISABLED)
            threading.Thread(target=self.func, daemon=True).start()
    
    if __name__ == '__main__':
        root = tk.Tk()
        app = App(root)
        root.mainloop()
    

提交回复
热议问题