使用Tkinter创建按键绑定

时间:2019-02-01 14:13:03

标签: python python-3.x tkinter

我正在尝试使用按钮创建按键绑定。

def LoginSQLEvent(event):
    print("In Keybinded Function")
    LoginSQL()

def LoginSQL():
    ...

LoginButton = tk.Button(Login, command=LoginSQL, text="Login", font=ButtonFont, bg=ScoutPurple, fg="white")
LoginButton.grid(row=4, column=3)
LoginButton.bind('<Return>',LoginSQLEvent)

预期结果: 登录功能在按下回车/回车键时执行 实际结果: 登录功能不执行,按回车/回车键时不产生错误代码

1 个答案:

答案 0 :(得分:2)

要同时获取按钮和Enter / Return键以调用该函数,我们可以在代码中更改2项内容。

首先将event更改为event=None。通过将默认情况下定义的参数更改为“无”,您可以调用此函数weather或不传递参数。

接下来,将绑定更改为按钮的容器上。在这种情况下,登录窗口。 (为清楚起见,焦点需要与按钮位于同一容器中,以便绑定在不是根窗口的容器上起作用)

import tkinter as tk


Login = tk.Tk()

def LoginSQL(event=None):
    print("Testing")

LoginButton = tk.Button(Login, command=LoginSQL, font=ButtonFont,
                        bg=ScoutPurple, text="Login", fg="white")
LoginButton.grid(row=4, column=3)

Login.bind('<Return>', LoginSQL)

Login.mainloop()
相关问题