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

时间:2017-03-25 19:05:17

标签: 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(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()

2 个答案:

答案 0 :(得分:0)

您需要使用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() 将颜色值封装到函数中(称为“闭包”)。

public static void main(String[] args) throws IOException {
    char[] input = new char[1000];
    int input_size = 0;
    int readChars;

    //Reader in = new InputStreamReader(System.in);
    Reader in = new FileReader("572be-stud3.txt");
    do {
        readChars = in.read(input);
        for (int a = 0; a < readChars; a++) {
            if (input[a] >= 48 && input[a] <= 57) {
                input_size++;
            }
        }
    } while((readChars < 0) || (input[readChars-1] != '\n'));
    in.close();

    System.out.println(input_size);
}

答案 1 :(得分:0)

你应该创建一个这样的函数来改变背景颜色并使用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()