Search code examples
pythontkintertkinter-entry

Restricting user entry in Entry field in Tkinter without 'disabled' method


I want to restrict the user from entering into the tkinter Entry field. But I dont want to disable to the widget entirely. The main reason is I have 4924 commands that include the insertion of characters into the Widget, I cant just change every single of those line of code to the following. I only have enough time to do school.

field.configure(state='mormal')
field.insert(0, "example word")
field.configure(state='disabled')

I would really appreciate any way (including inefficient ways too) that helps me with this issue. My source code is has approximately has 10100 lines of code btw.( I am making an advanced calculator)

Maybe is there any alternative to the entry field that can help me achieve this mammoth of a problem.


Solution

  • One of the way is to create a custom class inherited from Entry and override the insert():

    import tkinter as tk
    ...
    
    class MyEntry(tk.Entry):
        def __init__(self, master=None, **kw):
            super().__init__(master, **kw)
            # make it disabled, but with black on white like in normal state
            self.config(state='disabled', disabledforeground='black', disabledbackground='white')
    
        def insert(self, pos, value):
            self.config(state='normal')
            super().insert(pos, value)
            self.config(state='disabled')
    
        def delete(self, first, last=None):
            self.config(state='normal')
            super().delete(first, last)
            self.config(state='disabled')
    
    ...
    
    field = MyEntry(...)  # use MyEntry instead of tk.Entry
    ...
    

    It still uses 'disabled' state, but you don't need to change the other parts of your application.