如何将回车键绑定到 tkinter 按钮 [英] How to bind enter key to a tkinter button
问题描述
我正在尝试将 Enter 键与按钮绑定.
I am trying to bind the Enter key with a button.
在下面的代码中,我试图从条目小部件中获取条目,当按下按钮 bt
时,它会调用获取条目的 enter()
方法.
In the bellow code, I am trying to get entries from the entry widget,
when the button bt
is pressed, it calls theenter()
method which gets the entries.
我也希望通过按回车键来调用它,但我没有得到想要的结果.
I also want it to be called by pressing the Enter key, I am not getting the desired results.
未读取在条目小部件中输入的值,并且调用了 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
帮我解决我的问题,谢谢!
Help me figure out my problem, thank you!
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
传递的参数.(你不需要使用它,但你需要接受它).
You need to modify your function to accept the argument that bind
passes. (You don't need to use it, but you need to accept it).
def enter(event=None):
并且您需要将函数而不是结果传递给 bind
方法.所以删除()
.
And you need to pass the function, not the result, to the bind
method. So drop the ()
.
bt.bind('<Return>',enter)
注意这将 Return 绑定到 Button,所以如果其他东西有焦点,那么这将不起作用.您可能希望将其绑定到 Frame.
Note this binds Return to the Button, so if something else has focus then this won't work. You probably want to bind this to the Frame.
fr.bind('<Return>',enter)
如果你想要一种方法来推动一个焦点按钮,空格键已经做到了.
If you want a way to push an in focus Button the space bar already does that.
这篇关于如何将回车键绑定到 tkinter 按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!