简体   繁体   中英

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)
        label.pack(pady=10,padx=10)

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

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

        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)


        print(res)

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)

into

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM