您可以创建一个包含所有要更改的小部件的列表myWidgets = [button1, label1, ... ] # List of widgets to change colour
for wid in myWidgets:
wid.configure(bg = newColour)
下面是一个同时改变多个标签背景颜色的示例代码。import tkinter as tk
# Change all label backgrounds
def change_colour():
c = user.get() #Get the entered text of the Entry widget
for wid in widget_list:
wid.configure(bg = c)
# Create GUI
root = tk.Tk()
tk.Label(root, text='Enter a colour').pack()
user = tk.Entry(root)
user.pack()
label_frame = tk.Frame(root)
label_frame.pack()
btn = tk.Button(root, text='Change Colour', command = change_colour)
btn.pack()
widget_list = [user, btn] # Add defined widgets to list
#Dynamicly create labels for example
for x in range(10):
lbl = tk.Label(label_frame, text='Label '+str(x))
lbl.pack(side = tk.LEFT)
widget_list.append(lbl) #Add widget object to list
root.mainloop()
或者如果您有一个框架已经包含了您想要更改的所有小部件,那么您可以使用它来代替。
parent_widget.winfo_children()将返回一个包含父小部件中存储的所有小部件的列表def change_colour():
c = user.get()
for wid in label_frame.winfo_children():
wid.configure(bg = c)