Squeeps
Squeeps

Reputation: 23

Python: tkinter AttributeError

I'm working on an assignment for class and I keep getting an AttributeError. Here is my code:

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()

And the error:

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'

If I remove the

self.base['variable'] = self.basevalue

line, then I still get the error with the self.expvalue and the self.strvalue lines as well. I'm not really sure what is causing this issue, so any advice helps.

Upvotes: 0

Views: 536

Answers (2)

nino_701
nino_701

Reputation: 692

You should call the method buttons after the attribute declaration in the __init__ method.

    ...
    self.basevalue = IntVar()
    self.expvalue = IntVar()
    self.strvalue = StringVar()

    self.buttons()
    ...

Upvotes: 1

tobias_k
tobias_k

Reputation: 82899

You initialize those attributes only after you call self.buttons(). Reverse the order in the __init__ method, then it will work:

def __init__(self, master):
    self.frm = Frame(master)
    self.frm.grid()
    self.basevalue = IntVar()
    self.expvalue = IntVar()
    self.strvalue = StringVar()
    self.buttons() # call buttons after initializing above attributes

Upvotes: 0

Related Questions