首页 > 解决方案 > 向上和向下箭头在 tkinter.Entry 小部件中插入不需要的字符

问题描述

以下代码生成具有单个Entry小部件的应用程序。在 MacOS 上使用来自 Homebrew 的 Python 3.7.3 运行时,在输入框内按向上或向下箭头会导致插入字符 0xF701:

向下键介绍字符

import tkinter as tk

root = tk.Tk()
app = tk.Frame(master=root)
app.pack()

entry = tk.Entry(app)
entry.pack()

app.mainloop()

Anaconda Python 不会发生这种情况,我找不到其他人遇到这个问题。

通过绑定printup 和 down 事件,我已经能够看到与这些事件关联的字符确实是0xF700and 0xF701

entry.bind('<Down>', print)
entry.bind('<Up>', print)

上下按下后输出:

<KeyPress event state=Mod3|Mod4 keysym=Up keycode=8320768 char='\uf700' delta=8320768 x=-5 y=-50>
<KeyPress event state=Mod3|Mod4 keysym=Down keycode=8255233 char='\uf701' delta=8255233 x=-5 y=-50>

Anaconda Python 版本的输出略有不同:

<KeyPress event state=Mod3|Mod4 keysym=Up keycode=8320768 char='\uf700' x=-5 y=-50>
<KeyPress event state=Mod3|Mod4 keysym=Down keycode=8255233 char='\uf701' x=-5 y=-50>

有谁知道这个问题的简单解决方案?

标签: python-3.xmacostkinter

解决方案


验证条目有帮助吗?下面的代码验证 Entry 中的结果字符串仅包含valid_chars. 如果需要,可以编写更复杂的验证规则。

import tkinter as tk
import re

valid_chars = re.compile(r'^[0-9A-Za-z ]*$') # Accept Alphanumeric and Space

class ValidateEntry(tk.Entry):
    def __init__(self, parent, regex):
        self.valid = regex
        validate_cmd = (parent.register(self.validate),'%P') # %P pass the new string to validate
        super().__init__( parent, validate = 'key', validatecommand = validate_cmd)
        #  validate = 'key' runs the validation at each keystroke.

    def validate(self, new_str):
        if self.valid.match(new_str): return True
        return False

def do_key(ev):
    print(ev.widget, ev, entry.get())

root= tk.Tk()
root.title("Validation")
fram = tk.Frame(root)
fram.grid()

entry = ValidateEntry(fram, valid_chars)
entry.grid()
entry.bind('<Down>', do_key)
entry.bind('<Up>', do_key)

root.mainloop()

这可能有点矫枉过正,但应该适用于所有平台。


推荐阅读