Two naive Tkinter questions

Peter Otten __peter__ at web.de
Sun Nov 2 17:06:42 EST 2003


Andrew Koenig wrote:

> work with my application because I'm going to have lots of these buttons,
> and I want to be able to set their colors independently.

If you have many buttons with similar functionality, I'd suggest using a
subclass, e. g.:

import Tkinter as tk

class ColorButton(tk.Button):
    def __init__(self, master, text, color):
        tk.Button.__init__(self, master, text=text, command=self.execute)
        self.color = color
    def execute(self):
        self["background"] = self.color


root = tk.Tk()
for color in "red green blue yellow".split():
    ColorButton(root, text=color.capitalize(), color=color).pack()
root.mainloop()

Peter




More information about the Python-list mailing list