我使用 tkinter 创建了一个按钮,并使用 command
参数为其分配了一个功能。但这个函数包含一些需要时间执行的代码。我在这里使用 time.sleep() 进行了模拟。我想在单击此按钮时删除此按钮。为此,我在函数内调用了按钮的全局变量,然后使用了 pack_forget()
。
from tkinter import *
import time
def signIn():
global login_button
login_button.pack_forget()
# code after this takes some time to run.
time.sleep(10)
login_screen = Tk()
login_button = Button(login_screen, text="Login", width=10, height=1, command=signIn)
login_button.pack()
login_screen.mainloop()
但问题是按钮只有在函数执行完成后(即 10 秒后)才会被删除。有什么方法可以在 pack_forget()
行执行后立即删除按钮,而不是等待完整函数完成执行?
最佳答案
调用update_idletasks删除按钮后 login_screen 窗口的方法。
来自effbot:
update_idletasks()
Calls all pending idle tasks, without processing any other events. This can be used to carry out geometry management and redraw widgets if necessary, without calling any callbacks.
def signIn():
global login_button, login_screen
login_button.pack_forget()
login_screen.update_idletasks()
# code after this takes some time to run.
time.sleep(10)
关于python - 如何在单击按钮时调用的函数仍在执行时删除 Tkinter 中的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61558488/