Python Forum

Full Version: Trying to display a variable in a label
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
When I run this the answer prints into the python console but not in the label:

import tkinter as tk

HEIGHT = 300
WIDTH = 300
answer = ""



def calculate():
    global answer
    answer = str(eval(entry.get()))
    print(answer)
    return answer


root = tk.Tk()
# Creates canvas
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

# Background
# background_image = tk.PhotoImage(file="landscape.png")
# background_label = tk.Label(root, image=background_image)
# background_label.place(relwidth=1, relheight=1)

# Creates frame and shows it
frame = tk.Frame(root, bg="gray")
frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8)

# Creates label and shows it
label = tk.Label(frame, text="CALCULATOR V0.1")
label.pack(side="bottom")
# Creates entry and shows it
entry = tk.Entry(frame, bd=5)
entry.place(relx=0, rely=0, relwidth=1, relheight=0.2)

# Creates button and shows it
button = tk.Button(frame, text="CALCULATE", bg="white", fg="blue", command=calculate)
button.pack(side="bottom", fill="both")
# Answer label  shows and places it, I made it text=answer why isnt it showing it on the label?
answer_label = tk.Label(frame, text=answer)
answer_label.place(rely=0.5, relwidth=1)

root.mainloop()
I get no errors from this.
(Oct-31-2019, 03:44 PM)Jordansonatina Wrote: [ -> ]answer = str(eval(entry.get()))
Because you bind the variable answer to a new value, which is unrelated to the old value that was assigned to answer. In order to have a bind-able variable that can change, you should use something like StringVar: https://effbot.org/tkinterbook/variable.htm

Here's a short example showing IntVar with a label showing it's value:
>>> import tkinter as tk
>>> root = tk.Tk()
>>> def increment(var):
...     var.set(var.get() + 1)
...
>>> answer = tk.IntVar()
>>> tk.Button(root, text="Click Me!", command=lambda: increment(answer)).pack()
>>> tk.Label(root, textvariable=answer).pack()
>>> root.mainloop()
Thank you very much! I got it to work and added a clear function so you can clear the answer variable. Pretty sure I understand it now. Thanks again for answering so quickly :D