detect key press in python?

detect key press in python?

I am making a stopwatch type program in python and I would like to know how to detect if a key is pressed such as p for pause and s for stop, and I would not like it to be something like raw_input that waits for the users input before continuing execution. Anyone know how to do this in a while loop Also, I would like to make this cross-platform, but if that is not possible, then my main development target is linux

Python has a keyboard module with many features. Install it, perhaps with this command: pip3 install keyboard Then use it in code like: import keyboard Using module keyboard while True:making a loop try: used try so that if user pressed other than the given key error will not be shown if keyboard.is_pressedq:if key q is pressed printYou Pressed A Key breakfinishing the loop else: pass except: break if user pressed a key other than the given key the loop will break

As OP mention about raw_input - that means he want cli solution. Linux: curses is what you want windows PDCurses. Curses, is an graphical API for cli software, you can achieve more than just detect key events. This code will detect keys until new line is pressed. import curses def mainwin: win.nodelayTrue key win.clear win.addstrDetected key: while 1: try: key win.getkey win.clear win.addstrDetected key: win.addstrstrkey if key os.linesep: break except Exception as e: No input pass curses.wrappermain

For Windows you could use msvcrt like this: import msvcrt while True: if msvcrt.kbhit: key msvcrt.getch printkey just to show the result

Use PyGame to have a window and then you can get the key events. For the letter p: import pygame, sys import pygame.locals pygame.init BLACK 0,0,0 WIDTH 1280 HEIGHT 1024 windowSurface pygame.display.set_modeWIDTH, HEIGHT, 0, 32 windowSurface.fillBLACK while True: for event in pygame.event.get: if event.key pygame.K_p: Do what you want to here pass if event.type pygame.locals.QUIT: pygame.quit sys.exit

It wouldnt be that difficult to use tKinter or some other GUI like wxPython or pyQT to implement a listener or other interface to detect a keypress. Check out this thread.

I would suggest you use PyGame and add an event handle. http:www.pygame.orgdocsrefevent.html

Комментарии

Популярные сообщения из этого блога

Как преобразовать вертикальную запись в горизонтальную?

Skipping acquire of configured file 'contrib/binary-i386/Packages' as repository … doesn't support architecture 'i386'

How to delete a folder in remote Windows from Linux