数字键字典 [英] Number To Key Dictionary

查看:69
本文介绍了数字键字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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

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

这篇关于数字键字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆