Tkinter 将键盘键绑定到 python 中的按钮命令
Tkinter Binding a keyboard key to a button's command in python
没有!不是功能,而是程序中任何特定时刻按钮的指定“命令”选项。我有一个代码块,其中按钮改变了它的功能和外观,但我希望将 Enter 键绑定到它,无论它调用的是什么功能。程序中有些地方按钮被禁用,但将回车键绑定到它仍然激活该功能,即使按钮被禁用。必须有办法做到这一点,或者绕过它。也许有一种方法可以以某种方式模拟按钮单击事件。我简直不敢相信没有直接的方法可以做到这一点。我目前看到的唯一选择是对每个功能和按钮保持绑定和解除绑定。它看起来很不pythonic。
如果您的绑定调用了按钮的 invoke
方法,那么当按钮被禁用时它不会执行任何操作。如果启用该按钮,它将执行按钮设计的任何操作。当然,您也可以只绑定一个函数,在执行任何操作之前检查按钮的状态。
这是一个人为的例子。它包含一个标记为“计数”的按钮,该按钮会增加计数器并更新显示。还有两个其他按钮用于启用或禁用第一个按钮。
一旦 window 获得焦点,如果您按下 return 键,它将调用该按钮。请注意,在禁用按钮后,return 键什么都不做。当您 re-enable 按钮时, return 键再次起作用。
import tkinter as tk
COUNT = 0
def count():
global COUNT
COUNT += 1
label.configure(text=f"Count: {COUNT}")
root = tk.Tk()
label = tk.Label(root, text="Count: 0")
button = tk.Button(root, text="Count", command=count)
enable_btn = tk.Button(root, text="Enable Count", command=lambda: button.configure(state="normal"))
disable_btn = tk.Button(root, text="Disable Count", command=lambda: button.configure(state="disabled"))
label.pack(side="top", fill="x", pady=20)
button.pack(side="left", padx=(0,10))
disable_btn.pack(side="right")
enable_btn.pack(side="right")
root.bind_all("<Return>", lambda event: button.invoke())
root.mainloop()
按钮的命令可以调用为
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()
调用函数。即使按钮实际上不是 on-screen,也能正常工作,如代码片段所示。
但是,如果按钮状态为"disabled"
,它将不起作用。在这种情况下,我建议将使用的函数存储在单独的变量中。
在下面的示例中,按钮的命令仅调用属于 class 的方法。这意味着您可以通过按下按钮或直接调用方法来调用函数,即使按钮被禁用、隐藏或删除也是如此。该按钮只是查看函数的当前定义并调用它。
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()
尝试点击按钮 and/or 按几次回车键,看看它会改变回调函数,即使按钮被遗忘或禁用,它仍然有效。
没有!不是功能,而是程序中任何特定时刻按钮的指定“命令”选项。我有一个代码块,其中按钮改变了它的功能和外观,但我希望将 Enter 键绑定到它,无论它调用的是什么功能。程序中有些地方按钮被禁用,但将回车键绑定到它仍然激活该功能,即使按钮被禁用。必须有办法做到这一点,或者绕过它。也许有一种方法可以以某种方式模拟按钮单击事件。我简直不敢相信没有直接的方法可以做到这一点。我目前看到的唯一选择是对每个功能和按钮保持绑定和解除绑定。它看起来很不pythonic。
如果您的绑定调用了按钮的 invoke
方法,那么当按钮被禁用时它不会执行任何操作。如果启用该按钮,它将执行按钮设计的任何操作。当然,您也可以只绑定一个函数,在执行任何操作之前检查按钮的状态。
这是一个人为的例子。它包含一个标记为“计数”的按钮,该按钮会增加计数器并更新显示。还有两个其他按钮用于启用或禁用第一个按钮。
一旦 window 获得焦点,如果您按下 return 键,它将调用该按钮。请注意,在禁用按钮后,return 键什么都不做。当您 re-enable 按钮时, return 键再次起作用。
import tkinter as tk
COUNT = 0
def count():
global COUNT
COUNT += 1
label.configure(text=f"Count: {COUNT}")
root = tk.Tk()
label = tk.Label(root, text="Count: 0")
button = tk.Button(root, text="Count", command=count)
enable_btn = tk.Button(root, text="Enable Count", command=lambda: button.configure(state="normal"))
disable_btn = tk.Button(root, text="Disable Count", command=lambda: button.configure(state="disabled"))
label.pack(side="top", fill="x", pady=20)
button.pack(side="left", padx=(0,10))
disable_btn.pack(side="right")
enable_btn.pack(side="right")
root.bind_all("<Return>", lambda event: button.invoke())
root.mainloop()
按钮的命令可以调用为
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()
调用函数。即使按钮实际上不是 on-screen,也能正常工作,如代码片段所示。
但是,如果按钮状态为"disabled"
,它将不起作用。在这种情况下,我建议将使用的函数存储在单独的变量中。
在下面的示例中,按钮的命令仅调用属于 class 的方法。这意味着您可以通过按下按钮或直接调用方法来调用函数,即使按钮被禁用、隐藏或删除也是如此。该按钮只是查看函数的当前定义并调用它。
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()
尝试点击按钮 and/or 按几次回车键,看看它会改变回调函数,即使按钮被遗忘或禁用,它仍然有效。