是否可以在 tkinter 中更新标签?

问题描述

我制作了一个可以求平方根的程序,但是我发现在找到 3 和 4 的平方根时,它没有改变标签,而是在旧标签之上创建了一个标签(请参阅图片)。 这是我的代码的样子:

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

解决方法

你应该只有 1 个标签,你应该更新结果,就像这样:

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