Friday, August 17, 2012

Tkinter Horizontal Scale Demo

This code is based on the Tcl hscale.tcl demo.  A horizontal ttk.Scale is displayed along with an arrow (canvas polygon item). Drag the scale to stretch or shrink the arrow.





# File: hscale.py

from tkinter import *
from tkinter import ttk
from demopanels import MsgPanel, SeeDismissPanel

class HorizScaleDemo(ttk.Frame):
    def __init__(self, isapp=True, name='hscaledemo'):
        ttk.Frame.__init__(self, name=name)
        self.pack(expand=Y, fill=BOTH)
        self.master.title('Horizontal Scroll Demo')
        self.isapp = isapp
        self._create_widgets()
        
    def _create_widgets(self):
        if self.isapp:
            MsgPanel(self, 
                     ["An arrow and a horizontal scale are displayed below. ",
                      "If you click or drag mouse button 1 in the scale, you ",
                      "can change the length of the arrow."])
            
            SeeDismissPanel(self)
        
        self._create_demo_panel()
        
    def _create_demo_panel(self):
        demoPanel = Frame(self, borderwidth=10, name='demo')
        demoPanel.pack(side=TOP, expand=Y, fill=BOTH)
        
        canvas = Canvas(demoPanel, width=50, height=50, 
                        bd=0, highlightthickness=0, name='arrow')

        # draw an arrow
        canvas.create_polygon('0 0 1 1 2 2', fill='DeepSkyBlue3',
                              tags=('poly', ), outline='black')

        scale = ttk.Scale(orient=HORIZONTAL, length=284,
                          from_=0, to=250,
                          command=self._set_width)
        scale.set(75)
        
        # position and set resize behaviour
        canvas.pack(side=TOP, expand=Y, fill=X, padx=15, anchor=S)
        scale.pack(in_=demoPanel, side=BOTTOM, expand=Y, anchor=N)

    def _set_width(self, width):
        # stretch the arrow
        canvas = self.nametowidget('demo.arrow')
        width = float(width) + 31
        x2 = width - 30 
        if x2 < 31:  x2 = 31
        
        x2 = str(x2)
        width = str(width)
        
        shape = (30, 15, 30, 35, x2, 35, x2, 45,
                  width, 25, x2, 5, x2, 15, 30, 15)
        
        canvas.coords('poly', shape)
    

if __name__ == '__main__':
    HorizScaleDemo().mainloop()