如何更改Tkinter中标签的值

我想在每次单击按钮并调用命令时更改标签中的文本。以下是我的代码:

选择 | 换行 | 行号
  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()

每次单击该按钮时,都会在该按钮下创建一个新标签。如何使其根据RGB_COLOR更改当前标签?谢谢。

# 回答1


在回调函数外部初始化标签。在回调中配置Label小部件。

选择 | 换行 | 行号
  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()

标签: python

添加新评论