Read console input using pygame

2020-03-21 09:48发布

问题:

Is there anyway to use pygame to get input from the console, rather than having to display a separate window to get input? I'm using pygame to track how long the keys on the keyboard are pressed.

The following code doesn't work (this is just a minimal example, it doesn't actually keep track of time elapsed):

pygame.init()

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

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

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

After

pygame.init()

then the event is raised, but I have that ghastly window I don't want to deal with.

To explain why I don't want the window, I envision this application being a command-line utility, so I can't have that. Is there any functional reason preventing pygame from running on the command-line?

Thanks!

EDIT: I speculated 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 been able to call

pygame.key.init()
pygame.event.init()
but it didn't work.

回答1:

Pygame is designed for making (graphical) games, so it only captures key presses when there is a window displayed. As Ignacio said in his answer, reading from the command line and from another window are very 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:

If you just make the window really small using

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

you can't see it. So you are clicked into the window but you don't notice.

If you click anywhere of course it stops working. You have to click on the pygame window icon for it to work again.



回答3:

Console input comes in via stdin, which pygame is not prepared to handle. There is no reliable way to get press/release events via stdin since it's dependent on the terminal sending it keypresses.



回答4:

If you just plain don't want a window of any kind at all, you can use PyHook. If you just want a console application, get user input with the built-in Python command "raw_input(...)".



回答5:

Try pygame.display.iconify(). This will hide the pygame screen, and you will still be able to detect keypresses.



标签: python pygame