如何一次更改 tkinter GUI 中所有内容的颜色 [英] How to change the colour of everything in a tkinter GUI at once

查看:20
本文介绍了如何一次更改 tkinter GUI 中所有内容的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码(如下所示)提示用户选择将 GUI 更改为哪种颜色.但我的问题是它只会改变背景.我想知道是否有办法一次更改每个标签和按钮的背景,或者我是否必须单独更改每个标签/按钮.

I have some code (as shown below) which prompts the user to select which colour to change the GUI to. But my problem is that it only changes the background. I'd like to know if there's a way to change the background of every label and button at once or do I have to change each label/button individually.

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()

推荐答案

您可以制作一个包含所有要更改的小部件的列表

You can make a list containing all your widgets you want to change

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

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

Here's an example code of changing the background colour of multiple labels at once.

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()

或者,如果您的 Frame 已经包含您想要更改的所有小部件,那么您可以改用它.

Or if you have a Frame already containing all the widgets you want to change, then you can use this instead.

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

parent_widget.winfo_children() will return a list containing all the widgets stored inside the parent widget

def change_colour():
    c = user.get()
    for wid in label_frame.winfo_children():
        wid.configure(bg = c)

这篇关于如何一次更改 tkinter GUI 中所有内容的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆