Home > front end >  Returning the month index/number instead of month name
Returning the month index/number instead of month name

Time:09-02

self.months = ('January', 'February', 'March',
                        'April', 'May', 'June', 'July', 'August',
                        'September', 'October', 'November', 'December')

self.option_var = tk.StringVar(self)

        # option menu
        option_menum = ttk.OptionMenu(
            self,
            self.option_var,
            self.months[0],
            *self.months,
            )

birth_month = self.option_var.get()

so, I'm programming an age calculator in python tkinter and I'm wondering if instead of returning the month name ("Jan"...), I can return a number, or rather the month's index in the list.

CodePudding user response:

How about making self.months a list?

self.months = ['January', 'February', 'March',
                        'April', 'May', 'June', 'July', 'August',
                        'September', 'October', 'November', 'December'] 

and then use .index(), e.g.

month_you_are_looking_for = "March"

month_as_integer = self.months.index(month_you_are_looking_for) 1

As @h4z3 pointed out in the comments, the same works if you want to use your months in a tuple, as you originally did!

  • Related