如何立即在Tkinter GUI中更改所有内容的颜色

Ink*_*lot 2 python user-interface background tkinter button

我有一些代码(如下所示),提示用户选择将GUI更改为哪种颜色。但是我的问题是,它只会改变背景。我想知道是否可以同时更改每个标签和按钮的背景,还是必须分别更改每个标签/按钮。

import tkinter
window = tkinter.Tk()  
colour_frame = tkinter.Frame(window)
options_frame = tkinter.Frame(window)

def colours():
    options_frame.pack_forget()
    red.pack()
    orange.pack()
    back_button.pack()
    colour_frame.pack()

def back():
    options_frame.pack()
    colour_frame.pack_forget()

def make_red():
    window.configure(background="red")

def make_orange():
    window.configure(background="orange")

colour_button = tkinter.Button(options_frame, text="Appearance", command=colours)

red = tkinter.Button(colour_frame, text="RED", command=make_red)
red.configure(bg = "red")
orange = tkinter.Button(colour_frame, text="ORANGE", command=make_orange)
orange.configure(bg = "orange")
back_button = tkinter.Button(colour_frame, text="Back", command=back)

window.mainloop()
Run Code Online (Sandbox Code Playgroud)

Ste*_*ers 6

您可以创建一个列表,其中包含要更改的所有小部件

myWidgets = [button1, label1, ... ] # List of widgets to change colour
for wid in myWidgets:
    wid.configure(bg = newColour)
Run Code Online (Sandbox Code Playgroud)

这是一次更改多个标签的背景色的示例代码。

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()
Run Code Online (Sandbox Code Playgroud)

或者,如果您的框架已经包含要更改的所有小部件,则可以改用它。

parent_widget.winfo_children() 将返回一个列表,其中包含所有存储在父窗口小部件内的窗口小部件

def change_colour():
    c = user.get()
    for wid in label_frame.winfo_children():
        wid.configure(bg = c)
Run Code Online (Sandbox Code Playgroud)