使列表中的每个按钮(颜色)将背景变为相应的颜色

Make each button(color) from list turn background to correspondent color

我想让每个按钮(在颜色列表下)在单击时将(整体 window)背景颜色更改为其名称中的颜色。我想这就是我在第 16 行中这部分代码的目标:

command=window.configure(background=c)

但是没用... 我真的很感激这里的一点帮助。 这是完整的代码:

import tkinter
window = tkinter.Tk()

window.title("Colors")
window.geometry('650x300')
window.configure(background="#ffffff")

#Create a list of colors
colors = ['red', 'green', 'blue', 'cyan', 'orange', 'purple', 'white', 'black']

#loops through each color to make button
for c in colors:
    #create a new button using the text & background color
    b = tkinter.Button(text=c, bg=c, font=(None, 15), command=(window.configure(background=c)))
    b.pack()

window.mainloop()

您需要使用functools.partial将颜色值封装到一个函数中(称为"closure")。

from functools import partial

for c in colors:
    #create a new button using the text & background color
    b = tkinter.Button(text=c, bg=c, font=(None, 15), command=partial(window.configure, background=c))
    b.pack()

你应该做一个像这样的函数来改变背景颜色并使用functools.partial。

from functools import partial 
import tkinter
window = tkinter.Tk()

window.title("Colors")
window.geometry('650x300')
window.configure(background="#ffffff")

#Create a list of colors
colors = ['red', 'green', 'blue', 'cyan', 'orange', 'purple', 'white', 'black']

def change_colour(button, colour):
    window.configure(background=colour)

#loops through each color to make button
for c in colors:
    #create a new button using the text & background color
    b = tkinter.Button(text=c, bg=c, font=(None, 15))
    b.configure(command=partial(change_colour, b, c))
    b.pack()

window.mainloop()