Stuck when tkinter is running, and the interface is stuck when clicking the button to run the task

Add a button in tkinter, click the button, the tkinter interface will be stuck during the program running, when the button task is finished, it will be fine

I’m too lazy to write it myself. I searched the whole page on Baidu with the same answer. It’s not convenient at all. I have to do it myself to get enough food and clothing.

In this case, time-consuming operations should be performed in an independent thread, so as not to block the Tkinter main loop when performing these operations in the main thread, causing the interface to be unresponsive.

The following is an example of creating a new thread using the Threading module:

import threading

def long_task():
    # 执行一些耗时操作
    pass

def button_click():
    # 创建一个新线程
    t = threading.Thread(target=long_task)
    # 启动线程
    t.start()

# 创建Tkinter应用程序
app = Tk()
# 添加一个按钮
button = Button(app, text='Button', command=button_click)
button.pack()
# 启动Tkinter主循环
app.mainloop()

In the above example, we create a new thread when the button is clicked, and perform the time-consuming operation in this thread. Since performing operations in a separate thread does not block the Tkinter main loop, the interface will remain responsive. Note: The GUI cannot be updated in a new thread. We can use inter-thread communication to send the result back to the main thread after calculating the result in the new thread to update the GUI.

If you need to update the GUI in a new thread, use Tkinter's after() method to update the GUI in the main thread through a timer. If no timer is used, an attempt will be made to update the GUI in a new thread, which will cause Tkinter to throw an exception.

Here is sample code to update the GUI in a new thread:

import threading

def long_task():
    # 执行一些耗时操作
    result = calculated_result()
    # 通过定时器将结果发送回Tkinter主线程
    app.after(0, update_gui, result)

def update_gui(result):
    # 更新GUI
    label.config(text=result)

def button_click():
    # 创建一个新线程
    t = threading.Thread(target=long_task)
    # 启动线程
    t.start()

# 创建Tkinter应用程序
app = Tk()
# 添加一个标签
label = Label(app, text='Result')
label.pack()
# 添加一个按钮
button = Button(app, text='Button', command=button_click)
button.pack()
# 启动Tkinter主循环
app.mainloop()

In the above example, we perform time-consuming operations in a new thread, and after calculating the results, send the results back to the Tkinter main thread through a timer. Once the GUI is updated, the label will display the result of the calculation. This allows the GUI to be updated without time-consuming operations, thus avoiding Tkinter interface stuttering issues.

Guess you like

Origin blog.csdn.net/qq_27900321/article/details/130500739