python-3.x - 向上和向下箭头在 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 不会发生这种情况,我找不到其他人遇到这个问题。
通过绑定print
up 和 down 事件,我已经能够看到与这些事件关联的字符确实是0xF700
and 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>
有谁知道这个问题的简单解决方案?
解决方案
验证条目有帮助吗?下面的代码验证 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()
这可能有点矫枉过正,但应该适用于所有平台。
推荐阅读
- python - pandas 按日期和值比较某些列条目
- javascript - 使用 Cytoscape 限制放置区域
- java - Spring MVC - 在 POJO 中使用连字符查询参数
- selenium - Selenium navigate().to() 卡住没有错误
- sql - 将查询中的空值替换为以前的值
- wiremock - 使用wiremock中请求url的查询参数从jsonBody获取特定对象
- r - 如果 id 是“重复的”,那么在给定一些标准的情况下,我如何才能只保留一个观察结果
- c - 如何处理内存访问冲突?
- node.js - 如何在 Mocha 中创建具有特定大小的模拟帖子对象
- python - 纸浆调度优化问题 - 随着时间的推移,多个供应输入