Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使列表中的每个按钮(颜色)将背景转换为相应的颜色_Python_Loops_Tkinter_Tk_For In Loop - Fatal编程技术网

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

Python 使列表中的每个按钮(颜色)将背景转换为相应的颜色,python,loops,tkinter,tk,for-in-loop,Python,Loops,Tkinter,Tk,For In Loop,我想让每个按钮(在“颜色”列表下)在单击时将(整个窗口)背景颜色从其名称更改为一种。我想这就是我在第16行代码中的目标: command=window.configure(background=c) 但它不起作用。。。 我真的很感激你能帮我一点忙。 以下是完整的代码: import tkinter window = tkinter.Tk() window.title("Colors") window.geometry('650x300') window.configure(backgroun

我想让每个按钮(在“颜色”列表下)在单击时将(整个窗口)背景颜色从其名称更改为一种。我想这就是我在第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
将颜色值封装到函数中(称为“闭包”)


您应该使用这样的函数来更改背景颜色并使用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()

你试过window[“bg”]=c吗?正是我需要的!
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()