Year Combobox (Python Tkinter)

vegaseat 2 Tallied Votes 1K Views Share

An example how to use Tkinter's OptionMenu() as a combobox to allow one year to be selected from an option list of let's say the past 15 years.

''' tk_OptionMenu_year.py
using Tkinter's OptionMenu() as a combobox
allows one year to be selected from an option list of 15 years
use trace() and globalgetvar(name) to show selected choice
tested with Python2 and Python3  by  vegaseat  11dec2014
'''

import datetime as dt
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def show_choice(name, index, mode):
    year_selected = root.globalgetvar(name)
    sf = "year selected = {}".format(year_selected)
    # show the result in the window title
    root.title(sf)


root = tk.Tk()

# get current year
year_now = dt.date.today().year
# start list 15 years ago
choices = list(range(year_now-15, year_now+1))
year = tk.StringVar(root)
year.trace('w', show_choice)

# optionally preselect a choice
year.set(choices[0])

year_option = tk.OptionMenu(root, year, *choices)
year_option.pack(padx=100, pady=10)

root.mainloop()