How can I stop my Tkinter GUI from freezing when I click my button?

后端 未结 1 813
你的背包
你的背包 2021-01-18 18:47

As someone who is new to programming, I constantly find myself running into errors and issues and, while finding answers and solution, I rarely find out why it is that way.

相关标签:
1条回答
  • 2021-01-18 19:06

    the reason your Tk GUI freezes is because you have everything running on 1 thread. The mainloop is haulted by the submit function call which must be taking a "long time", so you probably see "Not Responding" appear in your Tk window when you click the button. To fix this, you need spawn a separate thread for submit to run in, so that the mainloop can keep doing it's thing and keep your Tk window from freezing.

    this is done using threading. Instead of your button directly calling submit, have the button call a function that starts a new thread which then starts submit. Then create another functions which checks on the status of the submit thread. You can add a status bar too

    import os
    import time
    from datetime import datetime
    import shutil
    import threading
    from Tkinter import *
    import ttk
    
    def submit():
        time.sleep(5) # put your stuff here
    
    
    def start_submit_thread(event):
        global submit_thread
        submit_thread = threading.Thread(target=submit)
        submit_thread.daemon = True
        progressbar.start()
        submit_thread.start()
        root.after(20, check_submit_thread)
    
    def check_submit_thread():
        if submit_thread.is_alive():
            root.after(20, check_submit_thread)
        else:
            progressbar.stop()
    
    root = Tk()
    frame = ttk.Frame(root)
    frame.pack()
    progressbar = ttk.Progressbar(frame, mode='indeterminate')
    progressbar.grid(column=1, row=0, sticky=W)
    
    ttk.Button(frame, text="Check",
           command=lambda:start_submit_thread(None)).grid(column=0,    row=1,sticky=E)
    root.mainloop()
    
    0 讨论(0)
提交回复
热议问题