gpt4 book ai didi

python - 我如何在 python 中编写按钮(没有 Tkinter)?

转载 作者:行者123 更新时间:2023-11-28 22:19:46 25 4
gpt4 key购买 nike

我最近开始学习 Python3,我试图通过导入 pygame 用 Python3 制作游戏。我试着做一个菜单,但我遇到了一些困难。当您将鼠标悬停在矩形上但它不起作用时,我只是试图通过让矩形改变颜色来让它看起来像一个按钮。我已经尝试了一些东西,但它不起作用。无论如何这里是完整的代码:hastebin link.

这是我尝试制作按钮的部分:

def game_intro():
intro = True

gameDisplay.fill(white)
largeText = pygame.font.Font('freesansbold.ttf', 90)
TextSurf, TextRect = text_objects("Run Abush Run!", largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)

mouse = pygame.mouse.get_pos()

if 150+100 > mouse[0] > 150 and 430+50 > mouse[1] > 430:
pygame.draw.rect(gameDisplay, bright_green, (150,430,100,50))
else:
pygame.draw.rect(gameDisplay, green, (150, 430, 100, 50))

smallText = pygame.font.Font('freesansbold.ttf' ,20)
textSurf, textRect = text_objects("START!", smallText)
textRect.center = ( (150+(100/2)), (450+(430/2)) )
gameDisplay.blit(textSurf, textRect)

pygame.draw.rect(gameDisplay, red, (550, 430, 100, 50))

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

while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()

最佳答案

这里的问题是您只在函数开始时进行一次鼠标悬停测试。如果鼠标稍后移动到您的矩形中,那也没有关系,因为您再也不会进行测试了。

您要做的是将其移至事件循环中。 PyGame 事件循环中的一个棘手问题是您希望每个事件运行一次哪些代码(内部 for event in ... 循环),以及您只想在每个批处理运行一次(外部 while intro 循环)。在这里,我假设您想在每个事件中执行一次。所以:

def game_intro():
intro = True

# ... other setup stuff

while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()

mouse = pygame.mouse.get_pos()

if 150+100 > mouse[0] > 150 and 430+50 > mouse[1] > 430:
pygame.draw.rect(gameDisplay, bright_green, (150,430,100,50))
else:
pygame.draw.rect(gameDisplay, green, (150, 430, 100, 50))

看起来你只做一次的其他一些事情也属于循环,所以你的游戏可能仍然存在一些问题。但这应该会让您越过卡住的障碍,并向您展示如何着手解决其他问题。

关于python - 我如何在 python 中编写按钮(没有 Tkinter)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49468589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com