By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,101 Members | 1,340 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,101 IT Pros & Developers. It's quick & easy.

How to change value of label in Tkinter

P: 3
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
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
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.