I keep reveicing the error "NameError: name 'labelAns' is not defined",

Basically all I have to do is change the text on labelAns to a value that I insert by pressing a button, but I keep receiving an error and I don't know how I could fix it.

All I need to do now is change the label on command.

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Differentiation Calculator", font=LARGE_FONT)

        button1 = tk.Button(self, text="Main Menu",
                            command=lambda: controller.show_frame(StartPage))

        button2 = tk.Button(self, text="Integration",
                            command=lambda: controller.show_frame(PageTwo))

        self.num = tk.IntVar()
        self.entry = tk.Entry(self, textvariable=self.num)
        self.button = tk.Button(self, text='Differentiate', command=self.calc)

        labelAns = tk.Label(self,text = "0", width = 15)
        labelAns.pack(side = 'right')

        self.entry.pack(side = 'left')
        self.button.pack(side = 'left')

    def calc(self):
        Jack = (self.entry.get())

        x = sp.Symbol('x')

        res = (sp.diff(Jack,x))

        global labelAns

        labelAns(text = res)


2 answers

  • answered 2018-07-15 16:15 Shock9616

    I think what you need to do is call labelAns global in the initial declaration of the variable. You should be able to change

    labelAns = tk.Label(self,text = "0", width = 15)


    global labelAns = tk.Label(self,text = "0", width = 15)

    and it should work then. Also, you should be able to reference labelAns afterwards without using global labelAns.

  • answered 2018-07-16 03:58 busybear

    You're better off doing something like this, so you'll have an easy reference to your label:

    class PageOne(tk.Frame):
        def __init__(self, parent, controller):
            self.labelAns = tk.Label(self,text = "0", width = 15)
            self.labelAns.pack(side = 'right')
        def calc(self):
            self.labelAns['text'] = res

    Also notice how I changed the text for label self.labelAns. I don't think what you have will work--it's not something I've seen before (although it doesn't mean it wouldn't work).