【问题标题】:Pygame window not intractablePygame 窗口不难处理
【发布时间】:2017-04-17 13:41:36
【问题描述】:

最近,我开始研究 pygame,但现在我面临一个严重的问题。我按照 Youtube 上“KidsCanCode”的教程,现在有了这个代码:

# Pygame template - skeleton for a new pygame project
import pygame
import random

WIDTH = 600
HEIGHT = 480
FPS = 30

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

class Player(pygame.sprite.Sprite):
    # sprite for the Player
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 50))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.centerx = WIDTH / 2
        self.rect.bottom = HEIGHT - 10
        self.speedx = 0

    def update(self):
        self.speedx = 0
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            self.speedx = -5
        if keystate[pygame.K_RIGHT]:
            self.speedx = 5
        self.rect.x += self.speedx
        if self.rect.right > WIDTH:
            self.rect.right = WIDTH
        if self.rect.left < 0:
            self.rect.left = 0

# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()

all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)

# Game loop
running = True
while running:
    # keep loop runnig at the right speed
    clock.tick(FPS)
    # Process input (events)
    for event in pygame.event.get():
        # check for closing window
        if event.type == pygame.QUIT:
            running = False
    # Update
    all_sprites.update()

    # Draw / render
    screen.fill(BLACK)
    all_sprites.draw(screen)
    # *after* drawing everything, flip the display
    pygame.display.flip()

pygame.quit()

代码本身运行良好,pygame 窗口出现,我可以看到绿色精灵。但是当我尝试通过箭头键控制精灵时,我只控制文本编辑器中的光标,我在其中编写了脚本。 如果我没有以全屏模式打开文本编辑器,pygame 窗口甚至会消失在编辑器窗口的后面。当我将编辑器移到一边/最小化它,然后单击 pygame 窗口时,它仍然没有获得焦点。 我正在使用 Mac、macOS 10.12.4、Python 3.6.0、Anaconda 4.3.1。 当我尝试通过“cmd + tab”进入 pygame 窗口时,它甚至没有出现在列表中。
我通过 pip 安装了 pygame。

我希望有人以前见过这个问题/有解决这个问题的想法。

【问题讨论】:

  • 这似乎是与here 报告的错误有关的问题。如果您在虚拟环境中运行 pygame,它似乎会阻止窗口成为焦点。当前提供的解决方案是在虚拟环境之外运行 pygame 并等待他们修复错误。

标签: python pygame


【解决方案1】:

我之前也遇到过这个错误。似乎 pygame 模块在 Mac OS 上存在错误,或者 Mac OS 正在防止难以处理。尝试在 Windows 上运行代码或安装不同版本的 pygame。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 2018-01-28
    • 2014-07-05
    相关资源
    最近更新 更多