#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2022/03/26 21:13:13 +0900> u""" OptionMenu test. * Windows10 x64 21H2 + Python 2.7.18 32bit + tkinter * Windows10 x64 21H2 + Python 3.9.11 64bit + tkinter """ try: # Python 2.7 import Tkinter as tk except: # Python 3.x import tkinter as tk OPT_KIND = [ "Lines", "Boxs", "Rect only" ] root = tk.Tk() root.geometry("320x240") # reserve variable opt = tk.StringVar(root) opt.set(OPT_KIND[0]) lbl = tk.StringVar(root) lbl.set("Please select") # create widget and layout optmenu = tk.OptionMenu(root, opt, *OPT_KIND).pack(side = tk.TOP) label = tk.Label(root, textvariable=lbl).pack(side = tk.BOTTOM) def callback(*args): """set lbl value from opt.""" v = opt.get() if v in OPT_KIND: idx = OPT_KIND.index(v) else: idx = -1 lbl.set("Select [%s], index = %d" % (v, idx)) # Call callback when variable opt is updated opt.trace("w", callback) root.mainloop()