首页 > 解决方案 > Pygame 在 pycharm 中不起作用,只是弹出一个黑色窗口

问题描述

我在 pycharm 中使用了这段代码,但没有任何打印事件有效(退出、鼠标按钮单击或键盘上的按键)

虽然我看到了 pygame 窗口,但这些事件不起作用。

我也使用了 get() 而不是 wait() 但仍然没有运气。

有任何想法吗?

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))

while True:
    event = pygame.event.wait()

    if event.type == pygame.QUIT:
        print('Quit')

    if event.type == pygame.KEYDOWN:
        print('Key Down')
        print(event.key)
        print(event.unicode)

    if event.type == pygame.KEYUP:
        print('Key Up')
        print(event.key)

    if event.type == pygame.MOUSEBUTTONDOWN:
        print('Mouse Button Down')
        print(event.pos)
        print(event.button == pygame.BUTTON_RIGHT)
        print(event.button == pygame.BUTTON_LEFT)

    if event.type == pygame.MOUSEBUTTONUP:
        print('Mouse Button Up')
        print(event.pos)
        print(event.button == pygame.BUTTON_RIGHT)
        print(event.button == pygame.BUTTON_LEFT)

    if event.type == pygame.MOUSEMOTION:
        print('Mouse Motion')
        print(event.pos)
        print(event.rel)

更新我发现这是pycharm的问题。当我用 pygame 运行任何代码时,只会弹出一个黑色的 pygame 窗口,它不会运行任何其他代码(事件,用颜色填充窗口,...)。甚至 pygame 窗口也不是我给出的尺寸。

这是另一个代码示例。

import pygame

pygame.init()
screen = pygame.display.set_mode((200, 200))

red = (255, 0, 0)
screen.fill(red)
pygame.display.update()
pygame.time.delay(10000)

当我在 VS 代码中运行它时:

vs code pygame 测试

当我在 pycharm 中运行它时:(:

Pycharm pygame 测试

我还为 VS 代码和 pycharm 定义了相同的解释器,并且我已经重新安装了 pygame 包。

标签: pythoneventspygame

解决方案


您可以尝试使用完整的游戏循环,因为这会重复更新窗口。

尝试:

import pygame

pygame.init()
screen = pygame.display.set_mode((200, 200))

red = (255, 0, 0)
running = True
while running:
    screen.fill(red)
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type = pygame.QUIT:
            running = False
pygame.quit()

推荐阅读