William Kennedy William Kennedy - 7 months ago 15
Python Question

Tkinter button not defined

from tkinter import *
class Mybuttons():
def __init__(self, master):
self.frm= Frame(master)
self.frm.grid()
self.count= 0
self.mybuttons()
self.base=0
self.exponent=0
self.result=0
def doonebase(self):
self.base+=1
self.btn1['text']= 'the base is ' + str(self.base)
def dooneexponent(self):
self.exponent+=1
self.btn2['text']= 'the base is ' + str(self.exponent)
def getresult(self):
self.result= self.base * self.exponent
self.btn3['text']= 'the answer is ' + str(self.result)
def mybuttons(self):
self.btn1=Button(self.frm)
self.btn1['text']='base'
self.btn1['command']=doonebase
self.btn2=Button(self.frm)
self.btn2['text']='exponent'
self.btn2['command']=dooneexponent
self.btn3=Button(self.frm)
self.btn3['text']='result'
self.btn3['command']=getresult
self.btn1.grid(row=0, column=0)
self.btn2.grid(row=0, column=2)
self.btn3.grid(row=1, column=1)

def try1():
root= Tk()
root.title('Compute an exponent!')
root.geometry("200x300")
threebuttons= Mybuttons(root)
root.mainloop()
try1()


When I run this I get the error:

File "/home/goofy/Documents/lab10-1.py", line 23, in mybuttons
self.btn1['command']=doonebase
NameError: name 'doonebase' is not defined


It does produce a window, but the buttons are not there.

When I comment out each of the lines that assign the 'command' to the functions, the code runs, and the buttons appear, but they don't do anything. I had tried defining each of the functions before the constructor and also tried after the
def mybuttons(self)
. I cannot seem to figure out why the code doesn't see the defined functions.

Answer

When you define functions within a class, they are called "methods" and they are no longer in the global scope. That means that you can't use doonebase or doonexponent. They are now class attributes and should be accessed as such. Since instance methods are given the instance as their first argument (self), you can use that to get the attributes. Therefore, change doonebase to self.doonebase, dooneexponent to self.dooneexponent, and getresult to self.getresult

Comments