我无法使用 pygame 移动图像

I can't move an image with pygame

import pygame
import sys
pygame.init()
weight=550
height=400
screen = pygame.display.set_mode((weight,height))
image=pygame.image.load("Capture.jpg").convert()
ix= 70
iy = 80
speed =10
imageplace = screen.blit(image,(ix,iy))
pygame.display.update()
running=True
while running:
    for event in pygame.event.get():
        pygame.time.delay(10)
        if event.type == pygame.QUIT:
            running=False
        keys=pygame.key.get_pressed()
        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            pos_x = pos[0]
            pos_y = pos[1]
            if (keys[pygame.K_LEFT] or keys[pygame.K_a]) and ix > 0:
                ix-=speed
            if (keys[pygame.K_RIGHT] or keys[pygame.K_d]) and ix > 0:
                ix+=speed
            if (keys[pygame.K_UP] or keys[pygame.K_w]) and ix > 0:
                iy-=speed
    
            if (keys[pygame.K_DOWN] or keys[pygame.K_s]) and ix > 0:
                iy+=speed
            
            
            if imageplace.collidepoint(pos_x,pos_y):
                print("You have clicked on button")
            else:
                print("Wrong Direction")

我尝试使用 pygame 移动图像,但没有成功。我是新来的。我在网上找不到任何东西,我也不明白。

参见 How can I make a sprite move when key is held down,您必须在每一帧中重绘场景。典型的 PyGame 应用程序循环必须:


基于您的代码的示例:

import pygame

pygame.init()
width, height = 550, 400
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
image = pygame.image.load("Capture.jpg").convert()
imageplace = image.get_rect(topleft = (70, 80))
speed = 5

running=True
while running:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running=False
        if event.type == pygame.MOUSEBUTTONDOWN:
            if imageplace.collidepoint(event.pos):
                print("You have clicked on button")
            else:
                print("Wrong Direction")

    keys = pygame.key.get_pressed()        
    if (keys[pygame.K_LEFT] or keys[pygame.K_a]) and imageplace.left > 0:
        imageplace.x -= speed
    if (keys[pygame.K_RIGHT] or keys[pygame.K_d]) and imageplace.right < width:
        imageplace.x += speed
    if (keys[pygame.K_UP] or keys[pygame.K_w]) and imageplace.top > 0:
        imageplace.y -= speed
    if (keys[pygame.K_DOWN] or keys[pygame.K_s]) and imageplace.bottom < height:
        imageplace.y += speed

    screen.fill((0, 0, 0))
    screen.blit(image, imageplace)
    pygame.display.update()

pygame.quit()