pycode81
pycode81

Reputation: 174

Binding 'Return' press to Button in Python

I am trying to get the Return/Enter key to do the same thing as the 'Enter' button in my program. I have looked at other answers on StackOverflow but none of them solved my problem.

from tkinter import *
from tkinter import messagebox
import random

class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()
        self.number = random.randrange(10)
    def create_widgets(self):
        self.guess_lbl = Label(self, text = "Enter a Guess:")
        self.guess_lbl.grid(row = 2, column = 0, sticky = W)

        self.guess_ent = Entry(self, width = 10)
        self.guess_ent.grid(row = 2, column = 1, sticky = W)

        self.submit_bttn = Button(self, text = "Enter", command = self.reveal)
        self.submit_bttn.grid(row = 6, column = 0, sticky = W)
        self.submit_bttn.bind('<Return>', self.reveal)

    def reveal(self):
        guess = self.guess_ent.get()
        if int(guess) == int(self.number):
            messagebox.showinfo("Guessing game ", "Good Guess, that is correct!")

# Main
root = Tk()
root.title("Guessing Game")
root.geometry("300x100")
app = Application(root)
root.mainloop()

Upvotes: 3

Views: 91

Answers (1)

probat
probat

Reputation: 1532

You need to add this to your def __init__(self, master) function:

master.bind('<Return>', self.reveal)

And you need to update your def reveal(self): method to:

def reveal(self, event=None):

Finally you need to remove the last line under your def create_widgets(self): method.

self.submit_bttn.bind('<Return>', self.reveal)  # delete this

Afterwards, you will be able to press your Enter key on your keyboard and it should work for you.

Upvotes: 3

Related Questions