-1

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

This is what happens when I enter "Goodbye" first, then "Hello"

CEsmonde
  • 35
  • 4
  • 1
    It has been several years since I used python, but why do you have a while statement? it appears to me that it doesn't do anything as you break it on the first run, so effectively it would work the same to take the loop out. Also, you may find your answer in this one: https://stackoverflow.com/a/17126015/2793683 – dmoore1181 Jan 23 '19 at 14:38
  • 2
    Possible duplicate of [Changing the text on a label](https://stackoverflow.com/questions/17125842/changing-the-text-on-a-label) – fhdrsdg Jan 23 '19 at 14:39
  • *"ends up overlaping eachothe"*: You are stacking `Label`'s over an over on every `command=onButtonClick`. You have to create the `Label` **once** or `.destroy()` the previos `Label` before creating a new on. – stovfl Jan 23 '19 at 14:50

1 Answers1

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())
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685