如何将回车键绑定到 tkinter 按钮

How to bind enter key to a tkinter button

我正在尝试将 Enter 键 按钮 绑定。

在下面的代码中,我试图从条目小部件中获取条目, 当按下按钮 bt 时,它会调用 enter() 获取条目的方法。

我也希望通过按 Enter 键 来调用它,但我没有得到想要的结果。

The values entered in the entry widget is not being read and the enter method is called and just an empty space is inserted in my Database

帮我解决我的问题,谢谢!

from tkinter import *
import sqlite3

conx = sqlite3.connect("database_word.db")

def count_index():
    cur = conx.cursor()
    count = cur.execute("select count(word) from words;")
    rowcount = cur.fetchone()[0]
    return rowcount

def enter():  #The method that I am calling from the Button
    x=e1.get()
    y=e2.get()
    ci=count_index()+1
    conx.execute("insert into words(id, word, meaning) values(?,?,?);",(ci,x,y))
    conx.commit()

fr =Frame()  #Main
bt=Button(fr)  #Button declaration
fr.pack(expand=YES)
l1=Label(fr, text="Enter word").grid(row=1,column=1)
l2=Label(fr, text="Enter meaning").grid(row=2,column=1)
e1=Entry(fr)
e2=Entry(fr)
e1.grid(row=1,column=2)
e2.grid(row=2,column=2)
e1.focus()
e2.focus()
bt.config(text="ENTER",command=enter)
bt.grid(row=3,column=2)
bt.bind('<Return>',enter)   #Using bind

fr.mainloop()

2 件事:

您需要修改函数以接受 bind 传递的参数。 (你不需要使用它,但你需要接受它)。

def enter(event=None):

并且您需要将函数而不是结果传递给 bind 方法。所以删除 ()

bt.bind('<Return>',enter)

请注意,这会将 Return 绑定到 Button,因此如果其他对象具有焦点,则这将不起作用。您可能希望将其绑定到 Frame

fr.bind('<Return>',enter)

如果您想要一种方法来按下焦点按钮,space 栏已经可以做到这一点。

在问题和 Novel 的回答中,首先,按钮使用 bt.config(text="ENTER",command=enter) 绑定到 enter 函数。之后,功能绑定到enter/return键,但实际上按钮和enter/return键还是相当独立的。

对于这个问题,我假设这不是真正的问题,但是如果您经常想要更改按钮的命令,那么还必须更改绑定到 enter/return 键每次。

所以您可能会想:有没有办法让回车键自动与按钮执行相同的命令?

是的,有!

Tkinter 按钮有 invoke() 方法,它调用按钮的命令和 return 命令的 return 值:

import tkinter as TK

def func():
    print('the function is called!')

root = TK.Tk()
button= TK.Button(root, text='call the function', command=func) # not func()!
button.pack()
button.invoke() # output: 'the function is called!'
root.mainloop()

我们可以简单地将此方法绑定到回车键:

root.bind('<Return>', button.invoke) # again without '()'!

但是等等,这会产生与之前相同的问题:button.invoke() 方法不接受来自绑定的 event 参数,但我们不能(轻易地)更改该方法。解决方案是使用 lambda:

root.bind('<Return>', lambda event=None: button.invoke()) # This time *with* '()'!!!

为了完整起见,我将在下面举一个例子:

import tkinter as TK

root = TK.Tk()
button= TK.Button(root)
button.pack()

def func1():
    print('func1 is called!')
    button.config(text='call func2', command=func2)
def func2():
    print('func2 is called!')

button.config(text='call func1', command=func1)

root.bind('<Return>', lambda event=None: button.invoke())
root.mainloop()

解释:

  • 第一次按回车键或点击按钮时,会打印'func1 is called!'。
  • 第二次按回车键或点击按钮时,会打印'func2 is called!'。回车键应该和按钮一样,尽管键的绑定没有改变。