【问题标题】:AttributeError: 'tkapp' object has no attribute 'var'AttributeError:“tkapp”对象没有属性“var”
【发布时间】:2015-04-11 23:09:22
【问题描述】:

我正在尝试编写一个程序,因此每次单击复选框时都会打印“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()

【问题讨论】:

  • 您是否阅读过有关如何从IntVar 获取值的文档?
  • 是的,你使用get方法不是吗?

标签: python checkbox tkinter boolean output


【解决方案1】:

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

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

因为一旦__init__ 方法终止执行,var 就会被垃圾回收。您应该将var 更改为self.var,以使其成为类的字段(属性)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 2021-04-19
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多