问题
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