MyApp "instance has no attribute 'var'" 错误

MyApp "instance has no attribute 'var'" error

我有一个应用程序,用户应该在其中选择一个选项,然后在按下按钮后打印该值。但是,当我尝试 运行 时出现错误 AttributeError: MyApp instance has no attribute 'var'。有什么想法吗?

class MyApp(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)  

        self.execute = Button(root, text="Convert", command=self.convert())
        self.execute.grid(row=4, column=3, pady=9, padx=3)

        self.var = StringVar()
        rb1 = Checkbutton(root, text="Path", variable=self.var, offvalue='marker', onvalue='path')#, value='path'
        rb1.grid(row=4, column=1, padx=3, sticky=W)
        rb2 = Checkbutton(root, text="Markers", variable=self.var, offvalue='path', onvalue='marker')
        rb2.grid(row=5, column=1, padx=3, sticky=W)

    def convert(self):
        print self.var.get()

问题出在这一行:

self.execute = Button(root, text="Convert", command=self.convert())

您正在调用 self.convert 因为尾随 (),此方法取决于 self.var,但您尚未设置 self.var

您需要删除 ():

self.execute = Button(root, text="Convert", command=self.convert)