Search code examples
pythonuser-interfacewidgettkinteroptionmenu

Python - Updating contents of option menu


So the problem I am currently having is that I want to update the second option menu, based on what the user selected in the first. I think I have to use a lambda function here to make it so that the frame updates or something, but I am unsure of how exactly to do this. Here is my code so far:

from tkinter import *
import time
class CustomerEntryForm(Frame):
    def __init__(self):

        Frame.__init__(self)
        self.master.title("Customer Entry form:")
        self.pack()

        execute = True
        thirtyMonthList = [4,6,9,11]
        thirtyOneMonthList = [1,2,6,7,8,10,12]
        monthList = []
        dayList = []

        for i in range(1,13):
            monthList.append(i)

        initialMonth = IntVar(self)
        initialMonth.set(monthList[0])
        initialDay = IntVar(self)

        def resetDayOptionMenu():
            for i in range(1,len(dayList)+1):
                dayList.remove(i)

        def setDayList():
            resetDayOptionMenu()
            if initialMonth.get() == 2:
                for i in range(1, 29):
                    dayList.append(i)
                    initialDay.set(dayList[0])
            elif initialMonth.get() in thirtyMonthList:
                for i in range(1, 31):
                    dayList.append(i)
                    initialDay.set(dayList[0])
            elif initialMonth.get() in thirtyOneMonthList:
                for i in range(1, 32):
                    dayList.append(i)
                    initialDay.set(dayList[0])


        self.om2 = OptionMenu(self, initialMonth, *monthList, command = setDayList())
        self.om2.grid(row=0)
        self.om = OptionMenu(self, initialDay, *dayList)
        self.om.grid(row=1)



root = CustomerEntryForm()
root.mainloop()

I appreciate any help. Thanks.


Solution

  • It would be easier to remove and then just add the second OptionMenu field after the month changes.

    Like this:

        ...
    
        thirtyMonthList = [4,6,9,11]
    
        initialMonth = IntVar(self)
        initialMonth.set(1)
        initialDay = IntVar(self)
        initialDay.set(1)
    
        def removeDayOptionMenu():
            self.om.destroy()
    
        def setDayList(event):
            removeDayOptionMenu()
            if initialMonth.get() == 2:
                addDayOptionMenu(range(1,29))
            elif initialMonth.get() in thirtyMonthList:
                addDayOptionMenu(range(1,31))
            else:
                addDayOptionMenu(range(1,32))
    
        def addDayOptionMenu(dayList):
            self.om = OptionMenu(self, initialDay, *dayList)
            self.om.grid(row=1)
    
        self.om2 = OptionMenu(self, initialMonth, *range(1,12), command = setDayList)
        self.om2.grid(row=0)
        self.om = OptionMenu(self, initialDay, *range(1,32))
        self.om.grid(row=1)