How do I use the Python keyboard module to detect a key press?
Question:
I am working on a self challenge of making a cash register in Python, and I’m looking to use the keyboard module for inputting values instead of typing them into the console. However, I think the keyboard module command I’m using to detect key presses is not becoming false after pressing the key, meaning the number I just typed is being inserted again and again. What is the proper command to use? Here is the code to test out the input before incorporating it into my main code:
import keyboard
running =True
price=""
while running:
if keyboard.is_pressed("1"):
price+="1"
if keyboard.is_pressed("2"):
price+="2"
if keyboard.is_pressed("3"):
price+="3"
if keyboard.is_pressed("4"):
price+="4"
if keyboard.is_pressed("5"):
price+="5"
if keyboard.is_pressed("6"):
price+="6"
if keyboard.is_pressed("7"):
price+="7"
if keyboard.is_pressed("8"):
price+="8"
if keyboard.is_pressed("9"):
price+="9"
if keyboard.is_pressed("0"):
price+="0"
if keyboard.is_pressed("Enter"):
running=False
subtotal=int(price)
print(subtotal)
subtotal=float(subtotal)/100
print("Subtotal: {}".format(subtotal))
Answers:
There are usually many different ways to code something. Some are better than others. In a problem that is based on keyboard input, like your cash register/adding machine project, I would go with an event-driven approach. Your sample code represents a polling approach. It can work, but it may not be as efficient.
I’ve never used the keyboard module before, but I did some quick research and came up with the below program, which may give you guidance. Every time a key in the keyboard is pressed, the key_pressed()
routine is triggered. Digits are stored, and the Enter key causes an addition and then clearing of the stored digits.
import keyboard
sin = ""
val = 0.0
def key_pressed(e, *a, **kw):
global sin, val
# print(e, a, kw)
k = e.name
if k in "0123456789":
sin += k
elif k == 'enter':
val += float(sin)/100.0
print("Entered: " + sin)
print('Value: ', val)
sin = ""
keyboard.on_press(key_pressed)
I took a look at the documentation located here https://github.com/boppreh/keyboard.
I ran and tested this code on python 3.9
import keyboard
from functools import partial
num = ""
def add(i):
global num
num += str(i)
print(num, end='r')
for i in range(10): # numbers 0...9
keyboard.add_hotkey(str(i), partial(add, i)) # add hotkeys
keyboard.wait('enter') # block process until "ENTER" is pressed
print("nNum:{}".format(num))
You could additionally unhook the hotkeys by calling keyboard.unhook_all_hotkeys()
after grabbing the number. I imagine you could wait on "+" and "-" if you wanted to implement addition and subtraction of numbers.
I like the last example from this snippet from the Github docs that I ended up using:
import keyboard
# Don't do this! This will call `print('space')` immediately then fail when the key is actually pressed.
#keyboard.add_hotkey('space', print('space was pressed'))
# Do this instead
keyboard.add_hotkey('space', lambda: print('space was pressed'))
# or this
def on_space():
print('space was pressed')
keyboard.add_hotkey('space', on_space)
# or this
while True:
# Wait for the next event.
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN and event.name == 'space':
print('space was pressed')
I am working on a self challenge of making a cash register in Python, and I’m looking to use the keyboard module for inputting values instead of typing them into the console. However, I think the keyboard module command I’m using to detect key presses is not becoming false after pressing the key, meaning the number I just typed is being inserted again and again. What is the proper command to use? Here is the code to test out the input before incorporating it into my main code:
import keyboard
running =True
price=""
while running:
if keyboard.is_pressed("1"):
price+="1"
if keyboard.is_pressed("2"):
price+="2"
if keyboard.is_pressed("3"):
price+="3"
if keyboard.is_pressed("4"):
price+="4"
if keyboard.is_pressed("5"):
price+="5"
if keyboard.is_pressed("6"):
price+="6"
if keyboard.is_pressed("7"):
price+="7"
if keyboard.is_pressed("8"):
price+="8"
if keyboard.is_pressed("9"):
price+="9"
if keyboard.is_pressed("0"):
price+="0"
if keyboard.is_pressed("Enter"):
running=False
subtotal=int(price)
print(subtotal)
subtotal=float(subtotal)/100
print("Subtotal: {}".format(subtotal))
There are usually many different ways to code something. Some are better than others. In a problem that is based on keyboard input, like your cash register/adding machine project, I would go with an event-driven approach. Your sample code represents a polling approach. It can work, but it may not be as efficient.
I’ve never used the keyboard module before, but I did some quick research and came up with the below program, which may give you guidance. Every time a key in the keyboard is pressed, the key_pressed()
routine is triggered. Digits are stored, and the Enter key causes an addition and then clearing of the stored digits.
import keyboard
sin = ""
val = 0.0
def key_pressed(e, *a, **kw):
global sin, val
# print(e, a, kw)
k = e.name
if k in "0123456789":
sin += k
elif k == 'enter':
val += float(sin)/100.0
print("Entered: " + sin)
print('Value: ', val)
sin = ""
keyboard.on_press(key_pressed)
I took a look at the documentation located here https://github.com/boppreh/keyboard.
I ran and tested this code on python 3.9
import keyboard
from functools import partial
num = ""
def add(i):
global num
num += str(i)
print(num, end='r')
for i in range(10): # numbers 0...9
keyboard.add_hotkey(str(i), partial(add, i)) # add hotkeys
keyboard.wait('enter') # block process until "ENTER" is pressed
print("nNum:{}".format(num))
You could additionally unhook the hotkeys by calling keyboard.unhook_all_hotkeys()
after grabbing the number. I imagine you could wait on "+" and "-" if you wanted to implement addition and subtraction of numbers.
I like the last example from this snippet from the Github docs that I ended up using:
import keyboard
# Don't do this! This will call `print('space')` immediately then fail when the key is actually pressed.
#keyboard.add_hotkey('space', print('space was pressed'))
# Do this instead
keyboard.add_hotkey('space', lambda: print('space was pressed'))
# or this
def on_space():
print('space was pressed')
keyboard.add_hotkey('space', on_space)
# or this
while True:
# Wait for the next event.
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN and event.name == 'space':
print('space was pressed')