Master Noob
Master Noob

Reputation: 725

How to get a piece of code to run when a specific key is pressed? (python)

So what I am trying to get to happen is when the space bar is pressed the function will run, currently I am having to have the user input 'yes' or 'no' to a question. I would like to reduced to a single specified keystroke.

  1. How can this be done in python?

  2. Are there multiple ways of doing this if any?

Edit: I have seen how to do this for Enter and (anything else) but I wasn't able to specify the key specifically

    doing = True
    while doing:
        do_again = input('ready to do? Enter = to do. Q = quit')
        if do_again.lower() != 'q':
            # do thing # 
        else:
            doing = False

Edit 2: I have downloaded keyboard and have been looking around the table of contents for a long time now and have played around with alot of the functions that i would expect to work, but I'm still having no luck. here are a couple of my recent atempts

Recent attempt 1

  while True:
        roll = keyboard.is_pressed('57')
        if roll is True:
            print('you rolled a', randint(0, sides))
            input('would you like to roll again?\r\n')
            continue

recent attempt 2

    while True:
        roll = keyboard.send('57', do_release=True)
        if roll is True:
            print('you rolled a', randint(0, sides))
            input('would you like to roll again?\r\n')
            continue

Upvotes: 0

Views: 2262

Answers (1)

Mohd
Mohd

Reputation: 5613

There are two packages that you can use to achieve what you want, one of them is keyboard and the other is PyHook. I didn't use them but from what the description says, you can set particular keybinds (hotkeys) to do specific commands.

Upvotes: 2

Related Questions