Python/Pygame鼠标位置不更新(blit函数)

2024-10-01 22:40:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Pygame制作一个简单的菜单,但是我发现每当我使用pygame.mouse.get_位置,它确实是我想要的,但我必须不断移动我的鼠标,使我的图片不断闪动。在

import pygame
import sys

pygame.init()

screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('cursor test')

cursorPng = pygame.image.load('resources/images/cursor.png')
start = pygame.image.load('resources/images/menuStart.jpg')
enemy = pygame.image.load('resources/images/enemy-1.png')

white = (255,255,255)
black = (0,0,0)

clock = pygame.time.Clock()
FPS = 60

while True:
    screen.fill(white)
    pygame.mouse.set_visible(False)

    x,y = pygame.mouse.get_pos()
    x = x - cursorPng.get_width()/2
    y = y - cursorPng.get_height()/2
    screen.blit(cursorPng,(x,y))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()

        elif event.type == pygame.MOUSEMOTION:
            if x < 50 and y < 250:
                screen.blit(enemy,(100,100))

    clock.tick(FPS)
    pygame.display.update()

怎么了?在


Tags: imageeventgetifdisplaysysloadscreen
2条回答

看看你的代码:

for event in pygame.event.get():
    ...
    elif event.type == pygame.MOUSEMOTION:
        if x < 50 and y < 250:
            screen.blit(enemy,(100,100))

您检查事件,如果您检测到鼠标正在移动(而且只有在那时),您就将图像绘制到屏幕上。在

如果要在不移动鼠标的情况下绘制图像,请停止检查MOUSEMOTION事件,只需始终绘制图像:

^{pr2}$

你需要把一个曲面和一个矩形投影到屏幕上。在

首先,使用这个我用来加载图像的片段。它确保正确加载图像:

def loadImage(name, alpha=False):
"Loads given image"

    try:
        surface = pygame.image.load(name)
    except pygame.error:
        raise SystemExit('Could not load image "%s" %s' %
                     (name, pygame.get_error()))
    if alpha:
        corner = surface.get_at((0, 0))
        surface.set_colorkey(corner, pygame.RLEACCEL)

    return surface.convert_alpha()

第二,当你得到曲面时,像这样得到它的矩形:

^{pr2}$

然后,在更新中执行以下操作:

cursorRect.center = pygame.mouse.get_pos()

最后,像这样在屏幕上播放:

screen.blit(cursorSurf, cursorRect)

现在,您将注意到您的鼠标被正确渲染,而不必移动鼠标。在

相关问题 更多 >

    热门问题