如何解决是否可以在 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()
解决方法
你应该只有 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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。