469,641 Members | 1,134 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,641 developers. It's quick & easy.

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:
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. from random import *
  3.  
  4. def background():
  5.     x = randrange(255)
  6.     y = randrange(255)
  7.     z = randrange(255)
  8.     rgb_color = [x,y,z]
  9.     mycolor = '#%02x%02x%02x' % (x, y, z)
  10.     app.configure(bg=mycolor)
  11.     label1 = Label(app, text=rgb_color)
  12.     label1.pack()
  13.  
  14. app = Tk()
  15. app.geometry("500x400+5+5")
  16. app.resizable(0,0)
  17. app.title("Color Code")
  18. button1 = Button(app, text="Change", command=background)
  19. button1.pack()
  20. 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.
Sep 23 '14 #1
1 24046
bvdet
2,851 Expert Mod 2GB
Initialize the label outside of the callback function. Configure the label widget in the callback.
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. from random import *
  3.  
  4. def background():
  5.     x = randrange(255)
  6.     y = randrange(255)
  7.     z = randrange(255)
  8.     rgb_color = [x,y,z]
  9.     mycolor = '#%02x%02x%02x' % (x, y, z)
  10.     app.configure(bg=mycolor)
  11.     label1.configure(text=rgb_color)
  12.  
  13. app = Tk()
  14. app.geometry("500x400+5+5")
  15. app.resizable(0,0)
  16. app.title("Color Code")
  17. button1 = Button(app, text="Change", command=background)
  18. button1.pack()
  19. label1 = Label(app, text="")
  20. label1.pack()
  21. app.mainloop()
Sep 23 '14 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

3 posts views Thread by Matt | last post: by
3 posts views Thread by OutdoorGuy | last post: by
3 posts views Thread by John Smith | last post: by
2 posts views Thread by John Smith | last post: by
reply views Thread by marknoten | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.