我正在为课程分配工作而且我一直在获得一个AttributeError。这是我的代码:
from tkinter import *
class Lab12():
def __init__(self, master):
self.frm = Frame(master)
self.frm.grid()
self.buttons()
self.basevalue = IntVar()
self.expvalue = IntVar()
self.strvalue = StringVar()
def buttons(self):
self.base = Scale (self.frm)
self.base['orient'] = 'horizontal'
self.base['length'] = 10
self.base['from'] = 1
self.base['to'] = 10
self.base['variable'] = self.basevalue
self.exp = Scale (self.frm)
self.exp['orient'] = 'horizontal'
self.exp['length'] = 25
self.exp['from'] = 1
self.exp['to'] = 25
self.exp['variable'] = self.expvalue
self.lbl = Label (self.frm)
self.lbl['textvariable'] = self.strvalue
self.result = Button (self.frm)
self.result['text'] = "Click to get result"
self.result['command'] = self.do_res
self.base.grid(row = 0, column = 0)
self.exp.grid(row = 1, column = 0)
self.lbl.grid(row = 2, column = 1)
self.result.grid(row = 2, column = 1)
def do_res(self):
x = self.basevalue.get()
y = self.expvalue.get()
self.strvalue.set(str(x) + ' raised to ' + str(y) + ' is ' + str(x ** y))
def py_lab():
lab = Tk()
lab.title("lab12")
lab.geometry("400x400")
labclass = Lab12(lab)
lab.mainloop()
py_lab()
错误:
Traceback (most recent call last):
File "E:\CS 232\Lab 12\Lab12.py", line 53, in <module>
py_lab()
File "E:\CS 232\Lab 12\Lab12.py", line 51, in py_lab
labclass = Lab12(lab)
File "E:\CS 232\Lab 12\Lab12.py", line 10, in __init__
self.buttons()
File "E:\CS 232\Lab 12\Lab12.py", line 21, in buttons
self.base['variable'] = self.basevalue
AttributeError: 'Lab12' object has no attribute 'basevalue'
如果我删除
self.base['variable'] = self.basevalue
行,然后我仍然得到self.expvalue和self.strvalue行的错误。我不确定是什么导致了这个问题,所以任何建议都有帮助。
答案 0 :(得分:1)
您应该在__init__
方法中的属性声明后调用方法 ...
self.basevalue = IntVar()
self.expvalue = IntVar()
self.strvalue = StringVar()
self.buttons()
...
。
{{1}}
答案 1 :(得分:0)
在中调用(foldl * 1 '(1 2 3 4 5)) == 120
(foldr * 1 '(1 2 3 4 5)) == 120
后,只能初始化这些属性。在self.buttons()
方法中反转顺序,然后它将起作用:
__init__