单击图像将显示

2024-05-20 09:09:44 发布

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

我使用pygame在python中创建了一个完全可定制的enigma机器。我决定尽早实现的一件事是帮助功能。当我测试这个的时候,控制台上什么都不会显示。以下是图像点击的代码(不是全部代码)

while True:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        pygame.quit()
        pygame.display.quit()
    if event.type == pygame.MOUSEBUTTONDOWN:
        x, y = event.pos
        if img.get_rect().collidepoint(x, y):
            print('test')

我该怎么做?所有的帮助都是有用的。你知道吗


Tags: 代码in图像功能机器eventtruefor
1条回答
网友
1楼 · 发布于 2024-05-20 09:09:44

当您调用img.get_rect()时,您将创建一个pygame.Rect图像/曲面的大小和默认的topleft坐标(0,0),即您的rect位于屏幕的左上角。我建议在程序开始时为img创建一个rect实例,并将其用作blit位置和碰撞检测。可以将^{}centerx, y等坐标作为参数直接传递给^{}rect = img.get_rect(topleft=(200, 300))。你知道吗

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')

img = pg.Surface((100, 50))
img.fill((0, 100, 200))
# Create a pygame.Rect with the size of the surface and
# the `topleft` coordinates (200, 300).
rect = img.get_rect(topleft=(200, 300))
# You could also set the coords afterwards.
# rect.topleft = (200, 300)
# rect.center = (250, 325)

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.MOUSEBUTTONDOWN:
            if rect.collidepoint(event.pos):
                print('test')

    screen.fill(BG_COLOR)
    # Blit the image/surface at the rect.topleft coords.
    screen.blit(img, rect)
    pg.display.flip()
    clock.tick(60)

pg.quit()

相关问题 更多 >