Home > other >  Is there a way to read keypresses from the Enter key?
Is there a way to read keypresses from the Enter key?

Time:02-11

I have been fooling around in python (v3.9.10) and I have found no way to read keypresses from the enter key and have tkinter do something with that keypress. I am trying to make a dumb little program to show some numbers on my screen for school and want to be able to do it quickly. this is my code so far:

from tkinter import *



#DEFS
def submit():
    submitted=entrybox.get()
    display.config(text=submitted)

app=Tk()

entrybox=Entry(width=10)

entrybox.place(x=10,y=10)

#display label
display=Label(text=' ')
display.place(x=50,y=50)
display.config(font='Arial 72')

#submit button
subbutton=Button(text='SUBMIT',command=submit)
subbutton.place(x=70,y=10)

(Sorry if my code looks really bad I am quite new to python and everything it has to offer) (I am also sorry for sounding repetitive and/or dumb. Forums such as this aren't familiar to me either)

is there any way to read key presses from the enter key while allowing the rest of my tkinter stuff to run as intended? thanks in advance.

CodePudding user response:

You can use .bind() to do this like so:

app.bind('<Return>', function)

This will call function when enter is pressed. '<return>' denotes the return or enter key, and it calls function when the event of a return keypress occurs.

You could add it to your code like so:

from tkinter import *

def submit():
    submitted=entrybox.get()
    display.config(text=submitted)

app=Tk()

entrybox=Entry(width=10)

entrybox.place(x=10,y=10)

#display label
display=Label(text=' ')
display.place(x=50,y=50)
display.config(font='Arial 72')

#submit button
subbutton=Button(text='SUBMIT',command=submit)
subbutton.place(x=70,y=10)

app.bind('<Return>', lambda x: submit())
app.mainloop()

This will do what you are looking for...

CodePudding user response:

How to bind and handle events

Use bind(sequence, func) method on your widget (like Button or even the root app Tk).

The parameter sequence is one of the predefined events, a string name for keys, mouse-events, etc. The parameter func is a callback or handler function, given by name only (without parentheses or arguments), which must have one positional parameter for Event.

Demo

See this minimal example:

from tkinter import *

def callback(event):
    print(event)


def quit():   # did we miss something ?
    print("Escape was pressed. Quitting.. Bye!")
    exit()

app = Tk()
app.bind('<Return>', callback)  # on keypress of Enter or Return key
app.bind('<Enter>', callback)  # on mouse-pointer entering the widget - here the app's root window (not confuse with Enter key of keyboard)
app.bind('<Escape>', quit)  # on keypress of Escape key

app.mainloop()  # to start the main loop listening for events

Prints after following keys pressed:

  1. Enter key was pressed
  2. Escape key was pressed
<KeyPress event keysym=Return keycode=36 char='\r' x=-583 y=-309>
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: quit() takes 0 positional arguments but 1 was given

Note:

  1. The Enter key was caught and bound callback/handler function (callback) invoked which prints the passed event.
  2. The Escape key was caught and bound callback/handler function (quit) invoked. But since it hasn't the required parameter (like event) the invocation failed with a TypeError.

When adding the parameter def quit(event): it succeeds:

<Enter event focus=True x=6 y=188>
<Enter event focus=True x=182 y=45>
<KeyPress event keysym=Return keycode=36 char='\r' x=-583 y=-309>
<Enter event state=Button1 focus=True x=123 y=68>
Escape was pressed. Quitting.. Bye!

Note:

  1. The <Enter> event is when the mouse-pointer enters the (visible) widget frame, here of the application's root window.
  2. The <Escape> event exits the application

Further reading

RealPython: Python GUI Programming With Tkinter is a rich tutorial to learn more, especially on Using .bind().

  • Related