AttributeError: 'tkapp' object has no attribute 'var'

AttributeError: 'tkapp' object has no attribute 'var'

我正在尝试编写一个程序,因此每次单击复选框时都会打印 "hello world to the output file"。

到目前为止,我已经打印了条目小部件中的内容,但是我如何获取复选框的状态,以便在单击它时打印 "hello world" 而在未单击时它什么都不做?

import Tkinter as Tk
from Tkinter import StringVar

class SampleApp(Tk.Tk):

    def __init__(self):
        Tk.Tk.__init__(self)
        self.button = Tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()

        labelText=StringVar()
        labelText.set(" First Name")
        labelDir=Tk.Label(self, textvariable=labelText, height=1)
        labelDir.pack()

        directory=StringVar(None)
        self.can_fname =Tk.Entry(self,textvariable=directory,width=50)
        self.can_fname .pack()

        labelText=StringVar()
        labelText.set(" Last Name")
        labelDir=Tk.Label(self, textvariable=labelText, height=1)
        labelDir.pack()

        directory=StringVar(None)
        self.can_lname =Tk.Entry(self,textvariable=directory,width=50)
        self.can_lname .pack()

        var = Tk.IntVar()
        cb = Tk.Checkbutton(self, text="here", variable=var)
        cb.pack()

    def on_button(self):
      if self.var.get():
           print "the lights are on"
      else:
           print "the lights are off"

      a=self.can_fname.get()
      b='hello %s' %(a)

      with open('filename.txt', 'w') as myfile:
          myfile.write(b)


app = SampleApp()
app.mainloop()

var__init__ 方法或构造函数的局部变量。您基本上收到以下错误:

AttributeError: 'tkapp' object has no attribute 'var'

因为一旦 __init__ 方法终止执行,var 就会被垃圾回收。您应该将 var 更改为 self.var,以使其成为 class.

的字段 (属性)