0

I want to overwrite/replace the text Label with a button. If I try to make a new label and place it at the same location, the previous text is still visable since it is longer than the new text. Is it possible to delete the previous text first? any hints

root = tk.Tk()

tabControl = ttk.Notebook(root)
tab1 = ttk.Frame(tabControl)

def changetext():
        labeltest = Label(tab1, text="short text").place(x=20, y=20)

labeltest = Label(tab1, text="long long long text").place(x=20, y=20)

button1 = Button(tab1, text="Change text pls", command=changetext)
button1.place(x=20, y=50)
root.mainloop()
GCMeccariello
  • 339
  • 2
  • 13
  • 1
    You don't need to delete the label. Just use `labeltest.config(text="short text")` to update the label inside `changetext()`. – acw1668 Jul 05 '21 at 08:59
  • Right now you have [this](https://stackoverflow.com/questions/1101750/tkinter-attributeerror-nonetype-object-has-no-attribute-attribute-name) problem with your code. – TheLizzard Jul 05 '21 at 09:00

1 Answers1

0

Your code has this mistake. You shouldn't define a widget and pack/place/grid it on the same line. It's bad practise and you loose the reference to that widget. And as @acw1668 pointed out you can use <tkinter.Label>.config(text=<new text>) like this:

import tkinter as tk

def changetext():
        labeltest.config(text="short text")

root = tk.Tk()

labeltest = tk.Label(root, text="long long long text")
labeltest.pack()

button1 = tk.Button(root, text="Change text pls", command=changetext)
button1.pack()

root.mainloop()
TheLizzard
  • 7,248
  • 2
  • 11
  • 31
  • This is the error message I get: AttributeError: 'NoneType' object has no attribute 'config' – GCMeccariello Jul 05 '21 at 09:05
  • @caarloXY As I said in the first sentence from my answer: *Your code has [this](https://stackoverflow.com/questions/1101750/tkinter-attributeerror-nonetype-object-has-no-attribute-attribute-name) mistake.* You should split the `.place(...)` in a new line. – TheLizzard Jul 05 '21 at 09:07