类对象没有属性tk?

时间:2016-08-28 13:41:57

标签: python tkinter python-3.4

我是python的新手,在教程的帮助下,我正在尝试创建一个计算器但由于我无法纠正的错误而卡住了,当我按下一个数字按钮时会出现错误

from tkinter import *
root=Tk()
root.title("Yuvi's CAl")
global char

class cal():

    def __init__(self):
        self.string= StringVar()
        root=Tk()
        root.title("Yuvi's CAl")
        self.string=StringVar
        enter=Entry(root,textvariable=self.string)
        enter.grid(row=0,column=0,columnspan=6)
        values=["1","2","3","4","5","+","6","7","=","8","9","c"]
        row=1
        col=0
        i=0
        for txt in values:
            if i==3:
                row=3
                col=0
            if i==6:
                row=4
                col=0
            if i==9:
                row=5
                col=0

            if txt=="+":
                but=Button(root,text=txt)
                but.grid(row=row,column=col)
            elif txt=="=":
                but=Button(root,text=txt,command=lambda:self.equals)
                but.grid(row=row,column=col) 
            elif txt=="c":
                but=Button(root,text=txt,command=lambda:self.clr)
                but.grid(row=row,column=col)
            else:
                but=Button(root,text=txt,command=lambda txt=txt:self.add(txt))
                but.grid(row=row,column=col) 

            col+=1
            i+=1
    def add(self,char):
            meet=self.string.get(self)
            self.string.set((str(meet)) + (str(char)))


    def equals(self):
            result=eval(self.string.get())
            self.string.set(result)
    def clr(self):
            self.string.set("")

ent=cal()

root.mainloop()

这是我按下数字按钮时的错误

Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1541, in __call__
    return self.func(*args)
  File "/home/yuvi/Documents/LiClipse Workspace/GUI/src/Misiio_calcuator.py", line 40, in <lambda>
    but=Button(root,text=txt,command=lambda txt=txt:self.add(txt))
  File "/home/yuvi/Documents/LiClipse Workspace/GUI/src/Misiio_calcuator.py", line 46, in add
    meet=self.string.get(self)
  File "/usr/lib/python3.4/tkinter/__init__.py", line 339, in get
    value = self._tk.globalgetvar(self._name)
AttributeError: 'cal' object has no attribute '_tk'

如果有任何错误,请纠正 提前谢谢

1 个答案:

答案 0 :(得分:2)

您的代码存在多个问题,首先应删除在__init__中隐藏全局变量,因为它会创建两个窗口并且只为其中一个窗口运行mainloop。此外,在首次创建实例后,使用self.string类对象覆盖StringVar。所以你的__init__可能是这样的

...
def __init__(self):
    self.string=StringVar()
    enter=Entry(root,textvariable=self.string)
    enter.grid(row=0,column=0,columnspan=6)
    values=["1","2","3","4","5","+","6","7","=","8","9","c"]
    row=1
    col=0
    i=0
...

然后在您的add中,您不必将self传递给self.string.get,也就是说它应该是

...
def add(self,char):
    meet=self.string.get()
    self.string.set((str(meet)) + (str(char)))
...

这些更改修复了您的异常,但我猜计算器中还存在其他逻辑错误,但这不是问题所在,修复它们无助于您学习python。