在Tkinter,Python上从键盘输入两位数字

时间:2016-01-07 17:57:29

标签: python events tkinter

所以我使用以下内容启用单位数字来移动游戏板上的编号图块。但是,我不能使用相同的方法输入双位数字。你有什么想法,我怎么能让Tkinter等我输入几个数字作为一个数字?

def key(event):
    if event.char.isdigit():
        for j, row in enumerate(board):
            for i, char in enumerate(row):
                if char.get() == event.char:
                play(i,j)
                return

root.bind('<Key>', key)

1 个答案:

答案 0 :(得分:0)

正如我在上一个问题中提到的那样 - 你可以把钥匙放在列表上,等一下,检查是否有两个或更多的字符。

import tkinter as tk

''' catch two (or more) keys pressed in short time and tread it as one text '''
''' http://pastebin.com/WHQKcJkW '''

# --- functions ---

# keys buffer
keybuf = []


def test_after():

    # check if buffer is not empty
    if keybuf:

        # get all keys in buffer as one text
        text = ''.join(keybuf)

        # clear buffer
        keybuf.clear()

        # run some function here
        print('after:', text)    


def get_key(event):

    # save key in buffer    
    keybuf.append(event.char)

    # check buffer after 500ms (0.5s)
    root.after(500, test_after)

# --- main ---

root = tk.Tk()

root.bind('<Key>', get_key)

root.mainloop()