Search code examples
python-2.7tkinteroptionmenutkinter-entry

How to delete Entry text when disabling and re-enabling widget


Is there any way that i can delete the user input in an entry widget when it's state is disabled and re-enabled? The user input stays as is, I would like to it without having to add a button event.

 from Tkinter import *

 class Interface():
     def __init__(self, window):
        frame = Frame(window)
        frame.pack()

        self.hopLabel = Label(frame, text="Number:", anchor=E)
        self.hopLabel.grid(row=0, column=0, sticky=EW)

        options = range(0,6)
        options.append("Other")

        self.variable = StringVar(frame)
        self.variable.set(options[0])
        self.options = OptionMenu(frame, self.variable, *options, command=self.this)
        self.options.grid(row=0, column=2, sticky=EW)

        self.button = Button(frame,text = "Print Value",width=20,command = self.printit(self.variable.get()))
        self.button.grid(row=1)

        self.otherEntry = Entry(frame, state=DISABLED)
        self.otherEntry.grid(row=0, column=1, sticky=EW)

    def this(self, value):
        if value == "Other":
            self.otherEntry.config(state=NORMAL)
        else:
            self.otherEntry.config(state=DISABLED)

    def printit(self,value):
        print value

if __name__ == "__main__":
    root = Tk()
    app = Interface(root)
    root.mainloop()

In order to save space, i didn't add the function that prints the value of the "Other" option. My question again is: Is there anyway to delete the value in the entry box when the state of the widget goes from DISABLED to NORMAL without having to press a button?


Solution

  • To delete the text in an entry widget when the state is disabled, you simply need to set the state to normal first and then call the delete method:

    def this(self, value):
        if value == "Other":
            self.otherEntry.config(state=NORMAL)
            self.otherEntry.delete(0, "end")
        ...