btn = tkinter.Button(command=lambda: print("Hello!"), text="Press me for greeting")
btn.pack() # This is not required to allow invoke() to work
btn.invoke()
import tkinter as tk
class Window(tk.Tk):
def __init__(self):
super().__init__()
self.bind("<Return>", lambda event: self.current_button_function())
self.btn = tk.Button(self, text="Press me!", command=lambda: self.current_button_function())
# command=self.current_button_function won't work since it won't update when the function updates
self.btn.pack()
self.mainloop()
def current_button_function(self):
print("This is a function. Button click is now disabled but function is still callable and enter still works")
self.btn.configure(state="disabled")
#self.current_button_function = lambda: print("This is simple lambda") # For easily returning single expression
def tmp(): # For a multi-line function
print("This is another function which works even though the button is disabled! The button is no longer on the page but the function is still callable and enter still works")
self.btn.forget()
def tmp():
print("The button is not on the page but it doesn't matter!")
#Could continue adding nested 'def' and/or 'lambda'
self.current_button_function = tmp
self.current_button_function = tmp
if __name__ == "__main__":
window = Window()
按钮的命令可以按以下方式调用:
它调用函数。即使按钮实际上不在屏幕上,这也可以工作,如代码段所示
但是,如果按钮状态为
"disabled"
,它将不起作用。在这种情况下,我建议将函数存储在单独的变量中在下面的示例中,按钮的命令只调用属于该类的方法。这意味着您可以通过按下按钮或直接调用该方法来调用该函数,即使该按钮已被禁用、隐藏或删除。该按钮只查看函数的当前定义并调用它
尝试单击该按钮和/或按enter键几次,以查看它是否更改了回调函数,并且即使该按钮被遗忘或禁用,它仍能工作
如果绑定调用按钮的
invoke
方法,那么当按钮被禁用时,它将什么也不做。如果该按钮已启用,它将执行该按钮设计的任何操作。当然,您也可以绑定到一个函数,该函数在执行任何操作之前检查按钮的状态这里有一个人为的例子。它包含一个标记为“计数”的按钮,用于增加计数器并更新显示。有两个其他按钮用于启用或禁用第一个按钮
一旦窗口具有焦点,如果您按下返回键,它将调用该按钮。请注意,禁用按钮后,返回键不起任何作用。当您重新启用按钮时,返回键再次工作
相关问题 更多 >
编程相关推荐