pygame能不能把按钮键放在循环之外
时间: 2023-09-24 21:11:50 浏览: 34
可以的,你可以在主循环之前定义按钮对象,然后在主循环中检查按钮是否被按下或释放。下面是一个简单的例子:
```python
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 400))
# 定义按钮对象
button_rect = pygame.Rect(150, 150, 100, 50)
button_color = pygame.Color('gray')
button_down_color = pygame.Color('red')
button_text = pygame.font.Font(None, 25).render('Click me!', True, pygame.Color('white'))
button_text_rect = button_text.get_rect(center=button_rect.center)
button_down = False # 记录按钮是否被按下
# 主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if button_rect.collidepoint(event.pos):
button_down = True
elif event.type == pygame.MOUSEBUTTONUP:
button_down = False
# 绘制按钮
if button_down:
pygame.draw.rect(screen, button_down_color, button_rect)
else:
pygame.draw.rect(screen, button_color, button_rect)
screen.blit(button_text, button_text_rect)
pygame.display.flip()
pygame.quit()
```
在这个例子中,我们定义了一个按钮对象,然后在主循环中检查按钮是否被按下或释放。通过设置 `button_down` 变量来记录按钮是否被按下,我们可以在绘制按钮时改变按钮的颜色。