0
def InputBox():
font = pygame.font.Font(None, 32)
inputBox = pygame.Rect(50, 50, 140, 32)
colourInactive = pygame.Color('lightskyblue3')
colourActive = pygame.Color('dodgerblue2')
colour = colourInactive
text = ''
active = False
isBlue = True
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if inputBox.collidepoint(event.pos):
active = not active
else:
active = False
colour = colourActive if active else colourInactive
if event.type == pygame.KEYDOWN:
if active:
if event.key == pygame.K_RETURN:
print(text)
text = ''
elif event.key == pygame.K_BACKSPACE:
text = text[:-1]
else:
text += event.unicode
screen.fill(screenGray)
txtSurface = font.render(text, True, colour)
width = max(200, txtSurface.get_width()+10)
inputBox.w = width
screen.blit(txtSurface, (inputBox.x+5, inputBox.y+5))
pygame.draw.rect(screen, colour, inputBox, 2)
if isBlue:
color = (0, 128, 255)
else:
color = (255, 100, 0)
pg.display.flip()
clock.tick(60)
InputBox()
上面是一個工作函數,使屏幕上有一個文本框。現在,你如何在同一屏幕上創建兩個文本框,而不是隻複製並粘貼相同的代碼兩次?如何在pygame中實現兩個輸入框,而不必重複代碼
我的想法是,單擊或激活的文本框將執行事件部分中的內容,因此您不必重複所有內容。但是,我不知道如何實現它。
在此先感謝