Run Pygame without a window / GUI

2019-02-24 10:19发布

问题:

Is it possible to run pygame without creating a pygame window, surface or GUI? I want to utilize certain pygame functions, but I don't want a GUI popping up.

For example, this function won't work unless I have set up a window within pygame.

running = True

def mainloop():
while True:

    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ) or \
        ( event.type == pygame.KEYDOWN and \
        ( event.key == pygame.K_ESCAPE) ):
            running = False
            print "quit"
            pygame.quit()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                print "working"

回答1:

DrevanTronder is correct, but he does not answer the question correctly, as you are asking how to do events in pygame without a GUI, as seen in your example coding.

This is not possible. When running a Pygame program, it only detects events if the Pygame window is selected. If there is no Pygame window, there is nothing to select, so events won't work. The following is pulled directly from the Pygame documentation:

"If the display has not been initialized and a video mode not set, the event queue will not really work." https://www.pygame.org/docs/ref/event.html

But, of course, if you are not talking about event handling specifically, then DrevanTronder is correct; all you need to do is import the module with "import pygame" and initialize it with "pygame.init()".

Hope this helps!



回答2:

Yes you can.

import pygame

pygame.init()
while 1:
    print pygame.time.get_ticks()
    pygame.time.wait(10)

This will give you the time in milliseconds since pygame started without the GUI popping up.



回答3:

If you are running Linux, you can use Xvfb.

Basically, Xvfb "captures" all display-related computations and performs them in-memory without it ever going to a display.

It may not suit your purposes, depending on your OS' behavior. Capturing keys in PyGame works only if the PyGame window is the active window but seeing that you won't be able to set the active window here, this will probably not work without additional workarounds.