For a program using pygame, I need an input box. I tried to make one myself, but I need a dict which translates the numbers from pygame to keys. I used to have a dict which included numbers and characters, but I need symbols.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Here's a simple text input box example. You can just add the .unicode
attribute of KEYDOWN
events to a string.
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
font = pg.font.Font(None, 32)
clock = pg.time.Clock()
input_box = pg.Rect(100, 100, 140, 32)
color_unfocused = pg.Color('lightskyblue3')
color_focused = pg.Color('dodgerblue2')
color = color_unfocused
focused = False
text = ''
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
if event.type == pg.MOUSEBUTTONDOWN:
if input_box.collidepoint(event.pos):
focused = not focused
else:
focused = False
color = color_focused if focused else color_unfocused
if event.type == pg.KEYDOWN:
if focused:
if event.key == pg.K_RETURN:
print(text)
text = ''
elif event.key == pg.K_BACKSPACE:
text = text[:-1]
else:
text += event.unicode
screen.fill((30, 30, 30))
txt_surface = font.render(text, True, color)
width = max(200, txt_surface.get_width()+10)
input_box.w = width
screen.blit(txt_surface, (input_box.x+5, input_box.y+5))
pg.draw.rect(screen, color, input_box, 2)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()