Color string tester in Tkinter

jrcagle 0 Tallied Votes 217 Views Share

Inspired by Bumsfeld's color tester, and wanting to give my students some practice at interpreting color strings, I wrote a little Tkinter program that asks the user to chose one of six buttons whose color most closely matches the color string printed at top.

Comments welcome, and does anyone know of a named solid bitmap?

Jeff

Edit: rolled global into MyFrame class

from Tkinter import *
import random



class MyButton(Button):

    HEX = "0123456789ABCDEF"
    
    def __init__(self, master):
        self.color = self.rand_color()
        Button.__init__(self, master, \
                        fg=self.color,\
                        bitmap="gray75",\
                        width=50,\
                        command = self.report)
        self.master = master

    def rand_color(self):
        return '#' + ''.join([random.choice(self.HEX) for x in range(3)])
    
    def report(self):
        self.master.answer.set("That color is %s" % self.color)
        
        
        
class MyFrame(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.display = StringVar()
        self.answer = StringVar()
        self.create_display()

    def set_display(self, color):
        self.display.set("Choose the color closest to %s" % color)

    def create_display(self):
        self.l = Label(self, font=("Times","24"), textvariable=self.display)
        self.l.grid(row=0,column=0,columnspan=3)
        self.buttons = []
        for x in range(6):
            b = MyButton(self) 
            self.buttons.append(b)           
        for b in self.buttons:
            n = self.buttons.index(b)
            b.grid(row=n/3+1, column=n%3)
        color = random.choice(self.buttons).cget('fg')
        self.set_display(color)
        self.restart_button = Button(self, text="Restart", command=self.restart)
        self.restart_button.grid(row=3,column=0)
        self.answer_label = Label(self, textvariable=self.answer)
        self.answer_label.grid(row=3, column=1)

    def restart(self):
        for x in self.buttons:
            x.color = x.rand_color() 
            x['fg'] = x.color
        s = random.choice(self.buttons).color
        self.answer.set("")
        self.update()
        self.set_display(s)
        
mainw = Tk()
mainw.f = MyFrame(mainw)
mainw.f.grid(row=0,columnspan=3)
mainw.mainloop()