Remove label text and set new label text on button click

狂风中的少年 提交于 2019-12-20 07:47:44

问题


I have made a smaller program to help troubleshoot for the main program. In this program I want the previous label text to be deleted before the new label text is displayed. This is important because if you leave the old label text in the label, the text ends up overlaping eachother.

from tkinter import *

root = Tk()

root.geometry("400x200")

def onButtonClick():
    while True:
        answerLabel = Label(root, text=wordEntry.get())
        answerLabel.grid(row=1, column=1)
        break


enterWordLabel = Label(root, text="Enter a word")
enterWordLabel.grid(row=0, column=0)

wordEntry = Entry(root)
wordEntry.grid(row=0, column=1)

enterButton = Button(root, text="Enter", command=onButtonClick)
enterButton.grid(row=0, column=2)

root.mainloop()


回答1:


Every widget has a configure method which allows you to change its attributes. The problem in your code is that you create new labels rather than changing the text of an existing label.

The proper solution is to create answerLabel once, and then call the configure method in your script:

...
answerLabel = Label(root, text="")
answerLabel.grid(row=1, column=1)
...

def onButtonClick():
    answerLabel.configure(text=wordEntry.get())


来源:https://stackoverflow.com/questions/54329525/remove-label-text-and-set-new-label-text-on-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!