Hasan Abdul Ghaffar
Hasan Abdul Ghaffar

Reputation: 107

How to remove and replace the label everytime the button is pressed | TKINTER

For my program, when I click "SHOW SELECTION" after selecting from the dropdown menu, the label shows the result. But when I do it again, it will write the next label in bottom of the first label and so on and so forth. The code is:

from tkinter import *
from PIL import ImageTk,Image
from tkinter import messagebox
from tkinter import filedialog

root = Tk()
root.title('First Window')
root.iconbitmap('C:/Users/themr/Downloads/avatar_referee_man_sport_game_icon_228558.ico')
root.geometry("400x400")

var = StringVar()
var.set("Monday")

drop = OptionMenu(root, var, "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
drop.pack()


def show():
    label = Label(root, text=var.get())
    label.pack()


button = Button(root, text="Show Selection", command=show)
button.pack()

root.mainloop()

What I actually want is that the new label should replace the first one and so there is only one line shown no matter how many times I press the button.

Please help out!

Upvotes: 1

Views: 514

Answers (1)

ela16
ela16

Reputation: 857

This is an easy fix. What you're currently doing is creating a new label each time show is called. And you don't need to remove and replace the label each time. All you have to do is instantiate the label with an empty text and then use .config to change its text.

root = Tk()
root
root.title("First Window")
root.iconbitmap('C:/Users/themr/Downloads/avatar_referee_man_sport_game_icon_228558.ico')
root.geometry("400x400")

var = StringVar()
var.set("Monday")

drop = OptionMenu(
    root,
    var,
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday",
)
drop.pack()


def show():
    # when show is called, change the label's text
    label.config(text=var.get())


my_button = Button(root, text="Show selection", command=show)

# label starts with an empty text
label = Label(root, text="")

my_button.pack()
label.pack()

root.mainloop()

Upvotes: 1

Related Questions