# L-32 MCS 260 Fri 1 Apr 2016 : rgbgui.py

"""
This GUI illustrates the use of sliders in Tkinter.
The users can manipulate the intensity of red, green, and blue
as the background of the canvas.  Every time the scale widget
is touched a variable holding the corresponding intensity is set
and the command "show_colors" is executed.
"""

from tkinter import Tk, Label, Canvas, Scale, DoubleVar

class ColorGUI(object):
    """
    Manipulate rgb color parameters with scale widgets.
    """
    def __init__(self, wdw):
        """
        Defines canvas and three scales.
        """
        wdw.title('color slider')
        self.dim = 400
        self.lab = Label(wdw, text='use scales to change colors')
        self.lab.grid(row=0, column=1)
        self.cnv = Canvas(wdw, width=self.dim, height=self.dim, bg='white')
        self.cnv.grid(row=1, column=1)
        self.labred = Label(wdw, text='red')
        self.labred.grid(row=0, column=0)
        self.red = DoubleVar()  # red intensity
        self.scared = Scale(wdw, orient='vertical', length=self.dim, \
            from_=0.0, to=1.0, resolution=1.0/256, \
            variable=self.red, command=self.show_colors)
        self.scared.set(0.5)    # initial value of red scale
        self.scared.grid(row=1, column=0)
        self.labblu = Label(wdw, text='blue')
        self.labblu.grid(row=0, column=2)
        self.blue = DoubleVar() # blue intensity
        self.scablu = Scale(wdw, orient='vertical', length=self.dim, \
           from_=0.0, to=1.0, resolution=1.0/256, \
           variable=self.blue, command=self.show_colors)
        self.scablu.set(0.5)    # initial value of blue scale
        self.scablu.grid(row=1, column=2)
        self.labgrn = Label(wdw, text='green')
        self.labgrn.grid(row=2, column=0)
        self.green = DoubleVar() # green intensity
        self.scagrn = Scale(wdw, orient='horizontal', length=self.dim, \
           from_=0.0, to=1.0, resolution=1.0/256, \
           variable=self.green, command=self.show_colors)
        self.scagrn.set(0.5) # initial green intensity
        self.scagrn.grid(row=2, column=1)

    def show_colors(self, val):
        """
        Displays a rectangle on canvas, filled with rgb colors
        """
        xmd = self.dim/2+1
        ymd = self.dim/2+1
        mid = self.dim/2-3
        red = self.scared.get()
        green = self.scagrn.get()
        blue = self.scablu.get()
        print('r = %f, g = %f, r = %f' % (red, green, blue))
        hxr = '%.2x' % int(255*red)
        hxg = '%.2x' % int(255*green)
        hxb = '%.2x' % int(255*blue)
        color = '#' + hxr + hxg + hxb
        self.cnv.delete('box')
        self.cnv.create_rectangle(xmd-mid, ymd-mid, xmd+mid, ymd+mid, \
            width=1, outline='black', fill=color, tags='box')

def main():
    """
    Makes the GUI and launches the main event loop.
    """
    top = Tk()
    ColorGUI(top)
    top.mainloop()

if __name__ == '__main__':
    main()
