I can't get the input from OptionMenu in tkinter

Question:

I made a simple code, where the user selects an option from the OptionMenu, then this option gets print, when I use .get() I get the error
AttributeError: 'OptionMenu' object has no attribute 'get'

Full Code:

from tkinter import *

root = Tk()

def printtxt():
    x = menu.get()
    print(x)

menu_txt = StringVar(root)
menu_txt.set('Text')

texts = ['Blue', 'Red', 'Green', 'Yellow']

menu = OptionMenu(root, menu_txt, *texts)
menu.pack()

bttn = Button(root, text='Submit', command=printtxt)
bttn.pack()

root.mainloop()
Asked By: TheDiamondCreeper

||

Answers:

You need to call get() on the associated variable, not the widget itself.

def printtxt():
    x = menu_txt.get()
    print(x)
Answered By: Bryan Oakley
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.