How to change value of label in Tkinter

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • katyalrikin
    New Member
    • Sep 2014
    • 3

    How to change value of label in Tkinter

    I want to change the text in a label everytime the button is clicked and the command is called. Here is my code:
    Code:
    from Tkinter import *
    from random import *
    
    def background():
        x = randrange(255)
        y = randrange(255)
        z = randrange(255)
        rgb_color = [x,y,z]
        mycolor = '#%02x%02x%02x' % (x, y, z)
        app.configure(bg=mycolor)
        label1 = Label(app, text=rgb_color)
        label1.pack()
    
    app = Tk()
    app.geometry("500x400+5+5")
    app.resizable(0,0)
    app.title("Color Code")
    button1 = Button(app, text="Change", command=background)
    button1.pack()
    app.mainloop()
    Every time the button is clicked, a new label is created under it. How can I make it change the current label based on the rgb_color? Thanks.
    Last edited by bvdet; Sep 23 '14, 11:52 PM. Reason: Please use code tags when posting code [code].......[/code]
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Initialize the label outside of the callback function. Configure the label widget in the callback.
    Code:
    from Tkinter import *
    from random import *
     
    def background():
        x = randrange(255)
        y = randrange(255)
        z = randrange(255)
        rgb_color = [x,y,z]
        mycolor = '#%02x%02x%02x' % (x, y, z)
        app.configure(bg=mycolor)
        label1.configure(text=rgb_color)
     
    app = Tk()
    app.geometry("500x400+5+5")
    app.resizable(0,0)
    app.title("Color Code")
    button1 = Button(app, text="Change", command=background)
    button1.pack()
    label1 = Label(app, text="")
    label1.pack()
    app.mainloop()

    Comment

    Working...