用python将键盘键绑定到按钮的命令

2024-05-01 21:59:42 发布

您现在位置:Python中文网/ 问答频道 /正文

不!不是一个函数,而是在程序中的任何特定时刻按按钮指定的“命令”选项。我有一个代码块,按钮在其中更改其功能和外观,但我希望Enter键绑定到它,无论它调用什么函数。程序中有一些点禁用了按钮,但将enter键绑定到该点仍会激活该功能,即使按钮已禁用。必须有办法做到这一点,或者有办法绕过它。也许有一种方法可以模拟按钮点击事件。我真不敢相信没有直接的方法可以做到这一点。目前我看到的唯一选择是为每个函数和按钮保持绑定和解除绑定。这看起来很不合宜


Tags: 方法函数代码命令程序功能选项事件
2条回答

按钮的命令可以按以下方式调用:

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()

它调用函数。即使按钮实际上不在屏幕上,这也可以工作,如代码段所示

但是,如果按钮状态为"disabled",它将不起作用。在这种情况下,我建议将函数存储在单独的变量中

在下面的示例中,按钮的命令只调用属于该类的方法。这意味着您可以通过按下按钮或直接调用该方法来调用该函数,即使该按钮已被禁用、隐藏或删除。该按钮只查看函数的当前定义并调用它

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()

尝试单击该按钮和/或按enter键几次,以查看它是否更改了回调函数,并且即使该按钮被遗忘或禁用,它仍能工作

如果绑定调用按钮的invoke方法,那么当按钮被禁用时,它将什么也不做。如果该按钮已启用,它将执行该按钮设计的任何操作。当然,您也可以绑定到一个函数,该函数在执行任何操作之前检查按钮的状态

这里有一个人为的例子。它包含一个标记为“计数”的按钮,用于增加计数器并更新显示。有两个其他按钮用于启用或禁用第一个按钮

一旦窗口具有焦点,如果您按下返回键,它将调用该按钮。请注意,禁用按钮后,返回键不起任何作用。当您重新启用按钮时,返回键再次工作

screenshot of example

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()

相关问题 更多 >