I'm using tkinter. I have a button to create a label with text in it. I want to clear that label with another button. How can i do that? I'm pretty new on tkinter. ıs there somebody to lead me
Asked
Active
Viewed 54 times
0
-
Does this answer your question? [Making python/tkinter label widget update?](https://stackoverflow.com/questions/1918005/making-python-tkinter-label-widget-update) – Collaxd Jan 20 '23 at 12:34
2 Answers
1
Here are a few options
Option 1
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text='Clear Me!')
label.pack()
# define a function to set the label text to an empty string
def clear_label_text():
label.config(text='')
# set up a button to call the above function
btn_clear = tk.Button(
root,
text='Click to Clear Label',
command=clear_label_text # note the lack of '()' here!
)
btn_clear.pack()
if __name__ == '__main__':
root.mainloop() # start the app
Option 2
This is a similar approach, but instead of defining a function to clear the label, we'll use a lambda
(an anonymous function)
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text='Clear Me!')
label.pack()
# set up a button to clear the label
btn_clear = tk.Button(
root,
text='Click to Clear Label',
# lambdas make for clean code, but don't go crazy!
command=lambda: label.config(text='')
)
btn_clear.pack()
if __name__ == '__main__':
root.mainloop() # start the app
Neither of these methods will outright destroy the label
, so you can set it's text again at any time a la label.config(text='New and improved text!')

JRiggles
- 4,847
- 1
- 12
- 27
0
from tkinter import *
root = Tk()
lab1 = Label(root, text = "Hello World")
lab1.pack()
but1 = Button(root, text = "clear", command=lab1.destroy)
but1.pack()
root.mainloop()

TheLizzard
- 7,248
- 2
- 11
- 31

Gaurav Kushwaha
- 1
- 1
-
2Please don't write code only answers as they are less helpful. Also OP might have wanted to keep the label without text after the button press. – TheLizzard Jan 20 '23 at 13:10