2

How do you call a function when the Enter key is pressed in a python guizero application?

For reference I've created a form that takes input from a barcode scanner and on the event of the Enter key being pressed it will insert the input into a database.

Here is an example of the TextBox and how the function should work.

def enterKeyClicked():
    dbInsert()

input = TextBox(app, width=30, align="top")

I checked the guizero github pages documentation for events, but I have not been able to figure it out.

martineau
  • 119,623
  • 25
  • 170
  • 301
NicLovin
  • 317
  • 3
  • 20

1 Answers1

2

You can call a function on key press using .when_key_pressed as mentioned in the docs.

def enterKeyClicked(event):
    if event.key == "\r":
        dbInsert()

input = TextBox(app, width = 30, align = "top")
input.when_key_pressed = enterKeyClicked

When you press any key, enterKeyClicked is called and a guizero EventData object is passed to it. You can use the .key attribute of the event to get the character of the key pressed. If the key pressed is Enter then the character is "\r". This is the python character for a carriage return, which is returned when you press Enter. Once you've checked the Enter key has been pressed, you can then call dbInsert().

Henry
  • 3,472
  • 2
  • 12
  • 36