如何在 tkinter Entry 小部件中仅插入一些指定的字符 [英] How to insert only some specified characters in a tkinter Entry widget

查看:24
本文介绍了如何在 tkinter Entry 小部件中仅插入一些指定的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 n 个 Entry 小部件的列表.用户应该只能键入以下字符:V"、F"、".如果用户键入其中一个字符,焦点应从条目 #x 传递到条目 #x+1,否则焦点应留在原处(在条目 #x 上)并且输入应被丢弃.

I have a list of n Entry widgets. The user should be able to type only the following charaters: "V", "F", " ". If the user types one of those characters, the focus should pass from Entry #x to Entry #x+1, otherwise the focus should stay where it is (on Entry #x) and the input should be discarded.

我无法丢弃错误的输入:如果用户按下的键与允许的键不同,则输入字段会获取该键,但命令 .delete(0,END) 不起作用,因为小部件本身还没有记住按下的键.

I am not able to discard the wrong input: if the user presses a key different from those allowed, the Entry field get that key, but the command .delete(0,END) doesn't work, as the widget itself hasn't yet memorized the key pressed.

我该怎么办?

推荐答案

import Tkinter as tk

def keyPress(event):
    if event.char in ('V', 'F', ' '):
        print event.char
    elif event.keysym not in ('Alt_r', 'Alt_L', 'F4'):
        print event.keysym
        return 'break'


root = tk.Tk()
entry = tk.Entry()
entry.bind('<KeyPress>', keyPress)
entry.pack()
entry.focus()

root.mainloop()

您可以轻松地拆分语句,以便根据键转到不同的形式.

You can easily break up the statement so it will go to a different form based on the key.

event.keysym 部分就在那里,所以当你在那个小部件中时,你可以按 ALT-F4 来关闭应用程序.如果您只是 else: return 'break' 那么它也会捕获所有其他按键.

The event.keysym part is in there so you can ALT-F4 to close the app when you're in that widget. If you just else: return 'break' then it will capture all other keystrokes as well.

这也是区分大小写的捕获.如果您想要不区分大小写,只需将其更改为 event.char.upper()

This also is a case sensitive capture. If you want case insensitive, just change it to event.char.upper()

这篇关于如何在 tkinter Entry 小部件中仅插入一些指定的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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