【问题标题】:Is it posible to update a label in tkinter?是否可以在 tkinter 中更新标签?
【发布时间】:2021-02-23 18:44:43
【问题描述】:

我编写了一个可以求平方根的程序,但我注意到在找到 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

【问题讨论】:

  • 这可以通过阅读可用的文档来回答。目前尚不清楚您为什么需要我们的帮助。

标签: python tkinter canvas label tk


【解决方案1】:

您应该只有 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()

【讨论】:

  • @GideonLyhne 如果这是您正在寻找的答案,请接受它,以免其他人浪费时间回答您的问题。
  • @TheLizzard 聪明的家伙,嗯? xD
猜你喜欢
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多