Tkinter OptionMenu cant use .get in a function

烂漫一生 提交于 2020-06-09 06:58:28

问题


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


回答1:


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()


来源:https://stackoverflow.com/questions/49816795/tkinter-optionmenu-cant-use-get-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!