Reading input using pygame

Is it possible to use pygame to input input from the console, instead of displaying a separate window for inputting input? I use pygame to track how long the keys on the keyboard have been pressed.

The following code does not work (this is just a minimal example, it does not actually track the elapsed time):

pygame.init() while 1: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: print event.key, 'pressed' 

It doesn't seem like any pygame event is being raised. If I add

 screen = pygame.display.set_mode((640, 480)) 

After

  pygame.init () 

then the event will be raised, but I have this terrible window that I do not want to deal with.

To explain why I do not want this window, I imagine that this application is a command line utility, so I can not do this. Is there any functional reason preventing pygame from running on the command line?

Thanks!

EDIT: I assumed that the problem was pygame.init (), and that I only needed to initialize the key and event modules. According to http://www.pygame.org/docs/tut/ImportInit.html I should have called

  pygame.key.init () 
pygame.event.init ()
but that didn't work.
+4
source share
5 answers

Pygame is designed to create (graphic) games, so it only captures keystrokes when a window is displayed. As Ignacio said in his answer, reading from the command line and from another window are two different things.

If you want to create a command line application, try curses:

http://docs.python.org/library/curses.html

Unfortunately, it only works on Linux and Mac OS X.

+2
source

If you just make the window really small using

screen = pygame.display.set_mode ((1, 1))

you do not see it. Thus, you get into the window, but do not notice.

If you click somewhere, of course, it will stop working. You need to click on the pygame window icon for it to work again.

+1
source

Login to the console comes through stdin, which pygame is not ready for processing. There is no reliable way to receive press / release messages via stdin, since it depends on the terminal sending it keystrokes.

0
source

If you just don't want windows of any type, you can use PyHook. If you just want a console application, get a user login with the Python built-in command "raw_input (...)".

0
source

Try pygame.display.iconify() . This will hide the pygame screen and you can still detect keystrokes.

0
source

Source: https://habr.com/ru/post/1402797/


All Articles