1

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

stovfl
  • 14,998
  • 7
  • 24
  • 51
adam Wadsworth
  • 774
  • 1
  • 8
  • 26
  • 2
    The code you posted creates an empty window. Could you fix that so we can actually see the OptionMenu? – Aran-Fey Apr 13 '18 at 12:21
  • You should call `.get()` on the StringVar that actually holds the selected item, NOT the OptionMenu itself. – jasonharper Apr 13 '18 at 12:25
  • And to see the optionmenu, simply change the first argument to root `StudentLoanLi = Tk.OptionMenu(root, StudentLoanOp, ...)` – Ron Norris Apr 13 '18 at 12:32
  • What is this lambda _ (underscore): in StudentLoanLi = Tk.OptionMenu(Placeholder2, StudentLoanOp, "No", "Plan 1", "Plan 2", command=lambda _: getStudentLoan()) – THEODOROPOULOS DIMITRIS Aug 27 '21 at 14:03

1 Answers1

7

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()
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149