简体   繁体   中英

Assigning values to optionmenu in tkinter

I have a list of months which I want to show in an option menu. When I select a month, I want get the number of month it is. Like if Apr is selected, I want an answer that This is the fourth month

I have written code as follows:

months = {'Jan' : '1', 'Feb' : '2', 'March' : '3' , 'Apr' : '4'}
var = StringVar(root)
var.set('Jan')

OptionMenu1 = OptionMenu(root, var, *months)
OptionMenu1.pack();

I want to know, how to trigger a function on selecting a particular entry

You can use the .trace method on the StringVar()

from tkinter import *

root = Tk()

months = {'Jan' : '1', 'Feb' : '2', 'March' : '3' , 'Apr' : '4'}    
var = StringVar(root)
var.set('Jan')

def changing(*event):
    print(months[var.get()])
var.trace("w", changing)

OptionMenu1 = OptionMenu(root, var, *months)
OptionMenu1.pack();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM