Python 使列表中的每个按钮(颜色)将背景转换为相应的颜色
我想让每个按钮(在“颜色”列表下)在单击时将(整个窗口)背景颜色从其名称更改为一种。我想这就是我在第16行代码中的目标: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
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()