Search code examples
pythonpython-2.7tkinteroptionmenutkinter-entry

Create an Entry box if a specific item on Optionmenu is selected


I'm trying to create an entry box for a user to manually input a variable that doesn't exist in a list of a optionmenu widget. is this possible?

from Tkinter import *
import Tkinter as tk

class Demo1:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        x = (master.winfo_screenwidth() - master.winfo_reqwidth()) / 2
        y = (master.winfo_screenheight() - master.winfo_reqheight()) / 2
        master.geometry("+%d+%d" % (x, y))
        master.deiconify()

        self.subtests = StringVar()
        self.subtests.set("Enter Test Type")

        choices = ['Potato','Tomato','Onion','Other']
        self.testnumber = OptionMenu(master, self.subtests, *choices).grid(row = 2, column = 3)
        self.confirmbutton = Button (master, text="Confirm Test", width=20, command =lambda: self.confirmsubtest(master))
        self.confirmbutton.grid(row = 5, sticky = E)

def main(): 
    root = tk.Tk()
    app = Demo1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

As mentioned, if the user needs to select a variable that is not on the list. Is it possible to allow the user to manually enter the variable through an entry box in the same window (ex: Selecting "Other" in the list that generates an entry/widget/something)?


Solution

  • If anyone searches for the same thing. The process is to add the command variable to the optionmenu and disable the entry widget once the desired highlighted choice is on. This is done by configuring the button/widget/anything with a .config(state=NORMAL) or .config(state=DISABLED).

     self.testnumber = OptionMenu(master, self.subtests, *choices, command = self.optupdate).grid(row = 2, column = 3)
     self.testnumber.grid(row = 4, column = 1)
    
      def optupdate(self,value):
        if value == "Other":
            self.otherEntry.config(state=NORMAL)
        else:
            self.otherEntry.config(state=DISABLED)
        return