通过单个函数更改tkinter中所有按钮颜色

0 投票
1 回答
52 浏览
提问于 2025-04-13 20:09

我想定义一个函数,这个函数可以改变程序中所有按钮的颜色,而不需要一个一个去设置。这个函数大概是这样的:

def change_colors():
    #change button a, b and c colors

a = Button(text='1',command=change_color)
b = Button(text='2',command=change_color)
c = Button(text='3',command=change_color)

在这个例子中,我只需要这样做:

def change_colors():
    a.config(bg='red')
    b.config(bg='red')
    c.config(bg='red')

但是在我实际的代码中,有很多按钮,每个按钮需要设置不同的颜色。

1 个回答

1

这里有一种方法可以处理这个问题,利用了 lambda(也叫“匿名函数”)。

  • 像平常一样定义每个 tk.Button 按钮。
  • 在定义完按钮后,使用 config 来设置它们的 command 属性(因为你需要引用这些按钮,所以必须先创建它们!)
  • 使用 lambda 将按钮对象和颜色传递给一个处理颜色变化的函数(这里的 lambda 用来动态传递参数给函数)。
import tkinter as tk

root = tk.Tk()


def change_btn_color(btn: tk.Button, color: str) -> None:
    btn.config(bg=color)


a = tk.Button(text='1')
a.config(command=lambda: change_btn_color(a, 'red'))
a.pack()

b = tk.Button(text='2')
b.config(command=lambda: change_btn_color(b, 'green'))
b.pack()

c = tk.Button(text='3')
c.config(command=lambda: change_btn_color(c, 'blue'))
c.pack()


root.mainloop()

如果目标是将所有按钮的颜色更改为某个特定按钮的颜色,那么方法会稍微不同。

在这种情况下,change_btn_color 会获取 root 窗口中的所有控件,然后如果这个控件是 tk.Button,就会改变它的颜色。

使用这种方法,你可以在定义每个 Button 时直接设置 command - 不需要单独调用 config,因为在这种情况下你并不需要传递按钮本身。

同样,我们使用 lambda 来将一个参数(颜色名称)传递给 command 函数。

import tkinter as tk

root = tk.Tk()


def change_btn_color(color: str) -> None:
    for widget in root.winfo_children():  # get all the widgets
        if isinstance(widget, tk.Button):  # get only the buttons
            widget.config(bg=color)


a = tk.Button(text='1', command=lambda: change_btn_color('red'))
a.pack()

b = tk.Button(text='2', command=lambda: change_btn_color('green'))
b.pack()

c = tk.Button(text='3', command=lambda: change_btn_color('blue'))
c.pack()


root.mainloop()

撰写回答