简体   繁体   中英

Is it posible to update a label in tkinter?

I made a program that could find square roots, but I noticed when finding the square root of 3 and then 4, that it didn't change the label, instead it made a new one on top of the old one (see pics). This is how my code looks:

import tkinter as tk

root= tk.Tk()

canvas1 = tk.Canvas(root, width = 400, height = 300)
canvas1.pack()

entry1 = tk.Entry (root) 
canvas1.create_window(200, 140, window=entry1)

def getSquareRoot ():  
    x1 = entry1.get()
    
    label1 = tk.Label(root, text= float(x1)**0.5)
    canvas1.create_window(200, 230, window=label1)
    
button1 = tk.Button(text='Get the Square Root', command=getSquareRoot)
canvas1.create_window(200, 180, window=button1)

root.mainloop()

This is what it looks like

You should only have 1 label that you should update with the result as it comes in like this:

import tkinter as tk

root= tk.Tk()

canvas1 = tk.Canvas(root, width = 400, height = 300)
canvas1.pack()

entry1 = tk.Entry (root) 
canvas1.create_window(200, 140, window=entry1)

# Create the results label
results_label = tk.Label(root)
canvas1.create_window(200, 230, window=results_label)

def getSquareRoot():
    x1 = entry1.get()
    # Update the label with the new result:
    results_label.config(text=float(x1)**0.5)
    
button1 = tk.Button(text='Get the Square Root', command=getSquareRoot)
canvas1.create_window(200, 180, window=button1)

root.mainloop()

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