【问题标题】:Image Loading by keystrokes in Python with pygame使用 pygame 在 Python 中通过击键加载图像
【发布时间】:2017-12-02 05:14:45
【问题描述】:

我正在尝试制作一个简单的图片库,在 python 中使用 pygame 加载带有击键的图片,这就是我得到的结果

import pygame

pygame.init()
width=1366;
height=768
screen = pygame.display.set_mode((width, height ), pygame.NOFRAME)
pygame.display.set_caption('Katso')
penguin = pygame.image.load("download.png").convert()
mickey = pygame.image.load("mickey.jpg").convert()

x = 0; # x coordnate of image
y = 0; # y coordinate of image

*keys = pygame.event.get()
for event in keys:
    if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
            screen.blit(mickey,(x,y)); pygame.display.update()
    if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
            screen.blit(penguin,(x,y)); pygame.display.update()*

running = True
while (running): # loop listening for end of game
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
#loop over, quit pygame

pygame.quit()

我希望按箭头键来加载某些图像

屏幕打开,但没有加载图像

【问题讨论】:

  • 只使用一个 for event 循环 - 在 while running 内。首先for event 不会等待您的按键。它将直接转到不检查密钥的while running

标签: python image keyboard pygame


【解决方案1】:

程序从不等待按键,因此您必须检查 while 循环中的键。

import pygame

# --- constants --- (UPPER_CASE)

WIDTH = 1366
HEIGHT = 768

# --- main ---

# - init -

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.NOFRAME)
pygame.display.set_caption('Katso')

# - objects -   

penguin = pygame.image.load("download.png").convert()
mickey = pygame.image.load("mickey.jpg").convert()

x = 0 # x coordnate of image
y = 0 # y coordinate of image

# - mainloop - 

running = True

while running: # loop listening for end of game
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                #screen.fill( (0, 0, 0) )
                screen.blit(mickey,(x,y))
                pygame.display.update()
            elif event.key == pygame.K_RIGHT:
                #screen.fill( (0, 0, 0) )
                screen.blit(penguin,(x,y))
                pygame.display.update()

# - end -

pygame.quit()

【讨论】:

  • 谢谢我错过了 while 循环修复它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多