数字到键字典

时间:2017-09-09 17:41:17

标签: python python-3.x pygame

对于使用pygame的程序,我需要一个输入框。我试图自己制作一个,但我需要一个将数字从pygame转换为键的字典。我曾经有一个包含数字和字符的字典,但我需要符号。

1 个答案:

答案 0 :(得分:0)

这是一个简单的文本输入框示例。您只需将.unicode个事件的KEYDOWN属性添加到字符串中即可。

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()