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.
Year Combobox (Python Tkinter)
''' 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()
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.