Home > Back-end >  how to solve this: how to clear the tkinter label with button
how to solve this: how to clear the tkinter label with button

Time:01-20

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

CodePudding user response:

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

CodePudding user response:

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!')

  • Related