<Key> 事件的按键代码是否与平台无关?

nbr*_*bro 5 python tkinter line python-3.x

我想为我的文本编辑器创建行号,但这有点复杂:Tkinter将行号添加到文本小部件

所以我决定创建一个行和列计数器,就像在IDLE. 为了实现这个目标,我决定监听小部件<Key>上生成的事件tkinter.Text我不知道事件对象有哪些属性,所以我决定查看该类的源代码Event(最好的教程之一:D),我发现有两个主要属性对我来说很有趣目标,即keycodechar

我的问题是,这个keycodes平台是独立的吗?我希望我的文本编辑器可以在所有平台上工作,而不会出现未定义的行为,因为keycodes.

这是我想做的一个简单实用的功能示例:

from tkinter import *

lines = 1
columns = 0

ARROWS = (8320768, 8124162, 8255233, 8189699)

def on_key_pressed(event=None):
    global columns, lines

    if event.keycode == 3342463: # return
        if columns > 0 and lines > 0:
            columns -= 1
            if columns < 0: # decrease lines if columns < 0
                columns = 0
                lines -= 1
        if columns == 0 and lines > 1:
            lines -= 1

    elif event.keycode == 2359309: # newline
        columns = 0
        lines += 1
    else:
        if event.keycode not in (ARROWS) and event.char != '':
            columns += 1

    print("Lines =", lines)
    print("Columns =", columns, '\n\n')
    print(event.keycode, ' = ', repr(event.char))

root = Tk()

text = Text(root)

text.pack(fill='both', expand=1)
text.bind('<Key>', on_key_pressed)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

这种方法有什么问题(在回答我的第一个问题之后)?

Ter*_*edy 4

在我的 win7 罗技键盘上,箭头键码是 37、38、39 和 40,带有 repr '',回车键是 13,带有 repr '\r'。这些密钥代码与您显示的内容或本页的声明不匹配。

但是,同一页面建议使用 event.keysym 或 event.keysym_num。它没有指出的是,在“私人使用区域”中,非 unicode 字符键(如 Shift、Up、F1 等)的数字略低于 2**16 (65536)。ascii 字符的数字是它们的 ascii 代码,等于它们的 unicode 序数。我怀疑所有 BMP unicode 字符的编号都是它们的 unicode 序数(tk 仅对 BMP 进行编码)。

我能看到的键码的唯一用途是区分数字键盘键和其他地方的相同键之间的区别。