簡體   English   中英

如何更改所有按鈕顏色?

[英]How can i change all button color?

所以這是我的代碼

for i in range(22):
    burtas.append(
        Button(
            logs,
            text=burti[i],
            fg="black",
            bg="light grey",
            width=3,
            font="Arial 20 bold",
        )
    )
    burtas[i].place(x=1 + 60 * (i % 9), y=530 + 55 * (i // 9))
    burtas[i].bind("<Button-1>", burtsKlik)

如何同時更改所有按鈕顏色?

沒有辦法在一次調用中全部更改它們,但您可以遍歷所有它們並 配置元素

burtas = []

for i in range(22):
    burta = Button(
        logs,
        text=burti[i],
        fg="black",
        bg="light grey",
        width=3,
        font="Arial 20 bold",
    )
    burta.place(x=1 + 60 * (i % 9), y=530 + 55 * (i // 9))
    burta.bind("<Button-1>", burtsKlik)
    burtas.append(burta)

# ...

for burta in burtas:
    burta["fg"] = "red"
    burta["bg"] = "blue"

您可以將 tkinter 按鈕子類化,創建一個可以記住 class 實例的版本,並可以在以后修改它們

class MyButton(tk.Button):
    objects = []

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__class__.objects.append(self)

    @classmethod
    def set_config(cls, **kwargs):
        for obj in cls.objects:
            obj.config(**kwargs)

    def destroy(self):
        self.__class__.objects.remove(self)
        super().destroy()

然后在您的代碼中,您可以使用set_config class 方法來修改所有創建的MyButton實例,如下所示

for i in range(22):
    burtas.append(
        MyButton(
            logs,
            text=burti[i],
            fg="black",
            bg="light grey",
            width=3,
            font="Arial 20 bold",
        )
    )
    burtas[i].place(x=1 + 60 * (i % 9), y=530 + 55 * (i // 9))
    burtas[i].bind("<Button-1>", burtsKlik)

MyButton.set_config(fg='red', bg='green')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM