Home > Net >  How do I efficiently change all the buttons in my program?
How do I efficiently change all the buttons in my program?

Time:07-12

I have coded multiple buttons in my Tkinter program, and I want to change the text colour of all of them to blue. I know I could type 'fg="blue"'every time I create a new button, but I'm looking for a way to select all the buttons in my program, and change the background colour of all of them at the same time. So far I've tried

for AllButtons in (Button1, Button, ect.)

But it still takes a long time and I'll have to add to the list every time I make a new button. What's the most efficient way of changing the text colour of all the buttons in my program?

CodePudding user response:

You can use ttk widgets and their style to change the appearance of all of the widgets of a specific class at once.

Consider the following example, clicking on the change style button will change the text color from red to blue.

import tkinter as tk
from tkinter import ttk


class App(tk.Tk):
    def __init__(self):
        super().__init__()

        self.geometry('300x110')
        self.resizable(0, 0)

        self.style = ttk.Style(self)
        self.style.configure('W.TButton', foreground = 'red')

        # login button
        login_button = ttk.Button(self, text="Login",style="W.TButton")
        login_button.grid(column=1, row=1, sticky=tk.E)

        change_button = ttk.Button(self, text="Change Style",style="W.TButton", command=self.changeStyle)
        change_button.grid(column=1,row=2,sticky=tk.E)



    def changeStyle(self):
        print("Change")
        self.style.configure('W.TButton', foreground='blue')


if __name__ == "__main__":
    app = App()
    app.mainloop()

All of the buttons are mapped to a "W.TButton" style so when we change that style, all of the widgets associated with that style will change their appearance.

  • Related