''' 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()
1
Contributor
0
Replies
12
Views
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.