How to insert only some specified characters in tkinter input widget

I have a list of n input widgets. The user should be able to enter only the following characters: "V", "F", "". If the user types one of these characters, the focus should go from Entry #x to Entry # x + 1, otherwise the focus should remain where it is (at input #x), and the input should be discarded.

I cannot reject the wrong entry: if the user presses a key other than allowed, the input field receives this key, but the .delete (0, END) command does not work, because the widget itself has not yet remembered the key pressed.

How could I do this?

0
source share
2 answers
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 split the statement so that it changes to another form based on the key.

The event.keysym part is located event.keysym , so you can ALT-F4 close the application when you are in this widget. If you just else: return 'break' , then it will capture all other keystrokes.

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

+5
source

Using the validate and validatecommand parameters, this creates tk.Entry , which accepts characters only in 'VF ' , but can tell you which key is pressed and what is the value of the current record:

 import Tkinter as tk def validate(char, entry_value): if char in 'VF ': print('entry value: {P}'.format(P = entry_value)) return True else: print('invalid: {s}'.format(s = char)) return False root = tk.Tk() vcmd = (root.register(validate), '%S', '%P') entry = tk.Entry(root, validate = 'key', validatecommand = vcmd) entry.pack() entry.focus() root.mainloop() 

I do not have a link to the documentation; I found out about it here .

+3
source

Source: https://habr.com/ru/post/906578/


All Articles