简体   繁体   中英

How to get selected value from the Tkinter OptionMenu

I am trying to get the selected option from the given below OptionMenu, but I am not able to use the selected value globally.

def callback(selection):
    print(selection)
    return selection 
yearl=Label(Frame1, text='Select Year ',font=("Helvetica", 10) ).place(relx=-0.3, rely=-1.40)
valueyear= ['2018', '2019', '2020','2021', '2022', '2023']
n =StringVar(Frame1) 
n.set(valueyear[0])
yearchoosen = OptionMenu(Frame1, n, *valueyear, command=callback).place(relx=0.3, rely=-1.45, 
width=160)

In callback function I am getting the correct selected value but, I want to use selection value in other function as well.

You can use the value outside the function or anywhere in the code and its all fine, because your defining it on the main block:

def callback(selection):
    print(n.get())
 
yearl = Label(Frame1, text='Select Year ',font=("Helvetica", 10) )
yearl.place(relx=-0.3, rely=-1.40)

valueyear = ['2018', '2019', '2020','2021', '2022', '2023']
n = StringVar(Frame1) 
n.set(valueyear[0])

yearchoosen = OptionMenu(Frame1, n, *valueyear, command=callback,variable=n)
yearchoosen.place(relx=0.3, rely=-1.45, width=160) #so yearchoosen wont return None

n and n.get() is accessible anywhere from your code.

To test this, just make a dummy function:

def dummy():
    print('This is the value from the option menu',n.get())

dummy_b = Button(Frame1, text='Dummy',command=dummy)
dummy_b.pack()

When clicked, this button will also return the value chosen from the OptionMenu .

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