Tkinter entrybox, not allowing typing and showing one string at a time Tkinter entrybox, not allowing typing and showing one string at a time tkinter tkinter

Tkinter entrybox, not allowing typing and showing one string at a time


To get all the features in an Entry widget you need to modify it.

  1. Unbind the sequence <Key> and also the <BackSpace> from the Entry widget.

  2. Justify the text to align in center by configure justify='center'.

  3. To get the desired key name, you have to bind <Key> to the Entry widget and get event.keysym as it gives you the name of the key pressed.

  4. If you don't want to see the insert blinking in the Entry widget you can try insertwidth=0 but for me it doesn't work not sure why, so I switch between 'readonly' and 'normal' states just like in the function self._display(..) as when the Entry widget is on 'readonly' state it doesn't allow any text inserts.

Here is the custom class Entry_Box inherited from Entry widget.

import tkinter as tkclass EntryBox(tk.Entry):    def __init__(self, master=None, cnf={}, **kw):        kw = tk._cnfmerge( (kw, cnf) )        kw['justify'] = kw.get('justify', 'center')        kw['state'] = 'readonly'         super(EntryBox, self).__init__(master=master, **kw)        self.bind_class(self, '<Key>', self._display)    def _display(self, evt):        self['state'] = 'normal'        self.delete('0', 'end')        self.insert('0', str(evt.keysym))        self['state'] = 'readonly'if __name__ == "__main__":    root = tk.Tk()    EntryBox().pack()    root.mainloop()

Brief explanation of the code:

tk._cnfmerge() is an internal function of tkinter library the purpose of this function is to combine multiple dictionaries together. Now you might be wondering we can combine dictionaries without this function. Yes, we can but this way we won't get any errors like if any of the dictionaries is None. Here is the source code to the function.

The bind_class is just like bind function but it is referred to the internal class name for example Entry widget has binds like <Key>, <BackSpace>, <Return>, ... which are internal binds, so if a user tries to bind or unbind any sequence it won't interfere with the internal binds until they use unbind_class with the same className (className is like a tag) given internally. This post can explain better.