Home > Software engineering >  Cannot modify global Label in Tkinter python
Cannot modify global Label in Tkinter python

Time:11-01

I am simply trying to make a Radiobutton GUI using tkinter. In which I want to change/replace the "Select your toppings" Label (myLabel) every time the user selects any Radiobutton with that Radiobutton name. So, the error which I am facing is instead of replacing that label a new label is created just below even though I am using a global Label.

from tkinter import *

root = Tk()

Toppings = [
    ["Pepperoni", "Pepperoni"],
    ["Cheese", "Cheese"],
    ["Mushroom", "Mushroom"],
    ["Onion", "Onion"]
]

pizza = StringVar()
pizza.set("Select your toppings")

for topping, value in Toppings:
    Radiobutton(root, text = topping, variable = pizza, value = value). pack(anchor = W)

myLabel = Label(root, text = pizza.get())
myLabel.pack()

def clicked(value):
    global myLabel
    myLabel.grid_forget()
    myLabel = Label(root, text = value)
    myLabel.pack()


myButton = Button(root, text="CLick me!", command = lambda: clicked(pizza.get()))
myButton.pack()



root.mainloop()

Image of my code output goes here

CodePudding user response:

Use .config to configure a particular widget option (and no need to use global in this case anyways) (and the explanation of why overwriting it didn't work is because you need to remove it from the Tcl by calling .destroy if you want to do it that way but that is unnecessary):

def clicked(value):
    myLabel.config(text=value)

Also I would suggest following PEP 8 and not have space around = if it is used in keyword arguments, also variable names should be in snake_case. And don't use * when importing a module, import only what you need.

Further improvements:

from tkinter import Tk, Label, Radiobutton, StringVar

toppings = [
    "Pepperoni",
    "Cheese",
    "Mushroom",
    "Onion"
]

root = Tk()

topping_var = StringVar(value='Select your topping')

for topping in toppings:
    Radiobutton(root, text=topping, variable=topping_var, value=topping).pack(anchor='w')

myLabel = Label(root, textvariable=topping_var)
myLabel.pack()


root.mainloop()

You don't need to use a button, just set the variable as the textvariable for the Label and that is it

  • Related