pythontkinteroptionmenutkinter.optionmenu

Tkinter OptionMenu cant use .get in a function


I'm writing some code and i need a variable to change when the optionMenu is changed here is some of my code below

#!/user
# -*- coding: utf-8 -*-

import locale
import Tkinter as Tk

root = Tk.Tk()
root.title("My Tax Calculator")
root.geometry("700x225")

def getStudentLoan():
    global StudentLoan
    StudentLoan = StudentLoanLi.get()

LeftFrame = Tk.Frame(root, width=300, height=200, pady=3)

Placeholder2 = Tk.Label(LeftFrame, text="")
Placeholder2.grid(row=2, column=1)

StudentLoanOp = Tk.StringVar()
StudentLoanOp.set("No")

StudentLoanLi = Tk.OptionMenu(Placeholder2, StudentLoanOp, "No", "Plan 1", "Plan 2", command=lambda _: getStudentLoan())
StudentLoanLi.grid(row=2, column=1)

Tk.mainloop()

This will not work in pycharm editor i get this error "unresolved attribute reference error on 'get' for Class 'OptionMenu'"

and when i execute the code and try and change the OptionMenu i get this error in the console

"StudentLoan = StudentLoanLi.get() AttributeError: OptionMenu instance has no attribute 'get'"

any help will greatly appreciated


Solution

  • The OptionMenu class has no get method. The correct way to get the selected item from an OptionMenu is to use the get method of the OptionMenu's StringVar, which you named StudentLoanOp:

    def getStudentLoan():
        global StudentLoan
        StudentLoan = StudentLoanOp.get()