首页 > 解决方案 > 如何检查,如果按钮按下两次?

问题描述

我可以使用 Pygame 在 Python 中按下 Enter 按钮。现在,每次我按下按钮时,它都会在控制台中打印“一次”。如何检测按钮是否被多次按下并打印“多次”?

  press = False
  if event.key == pygame.K_RETURN:
      press = True

      print("once")
  if press == True:
      print("more than once")

标签: pythonif-statementbuttonpygame

解决方案


你快到了。只需使用if/else块并在打印后设置press为:True

import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
run = True
press = False

while run:
  for e in pygame.event.get():
    if e.type == pygame.QUIT: 
        run = False
    if e.type == pygame.KEYDOWN:
        if e.key == pygame.K_RETURN:
            if not press:
                print('once')
            else:
                print('more than once')
            press = True

  screen.fill((30, 30, 30))
  pygame.display.flip()

推荐阅读