How to bind enter key to a tkinter button

Rahul picture Rahul · Nov 24, 2017 · Viewed 22.1k times · Source

I am trying to bind the Enter key with a button.

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.

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

Answer

Novel picture Novel · Nov 24, 2017

2 things:

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

And you need to pass the function, not the result, to the bind method. So drop the ().

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

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.