Exemplo n.º 1
0
agent_host.addOptionalFloatArgument('epsilon',
    'Exploration rate of the Q-learning agent.', 0.01)
agent_host.addOptionalFloatArgument('gamma', 'Discount factor.', 1.0)
agent_host.addOptionalFlag('load_model', 'Load initial model from model_file.')
agent_host.addOptionalStringArgument('model_file', 'Path to the initial model file', '')
agent_host.addOptionalFlag('debug', 'Turn on debugging.')

malmoutils.parse_command_line(agent_host)

# -- set up the python-side drawing -- #
scale = 40
world_x = 6
world_y = 14
root = tk.Tk()
root.wm_title("Q-table")
canvas = tk.Canvas(root, width=world_x*scale, height=world_y*scale, borderwidth=0, highlightthickness=0, bg="black")
canvas.grid()
root.update()

if agent_host.receivedArgument("test"):
    num_maps = 1
else:
    num_maps = 30000

for imap in range(num_maps):

    # -- set up the agent -- #
    actionSet = ["movenorth 1", "movesouth 1", "movewest 1", "moveeast 1"]

    agent = TabQAgent(
        actions=actionSet,
 def __init__(self,
              master,
              width,
              height,
              background='white',
              font="-*-helvetica-medium-r-normal--10-*-*-*-*-*-*-*",
              **attr):
     """
     @param master: the parent widget
     @param width: the initial width of the canvas
     @type width: C{int}
     @param height: the initial height of the canvas
     @type height: C{int}
     @param background: the background color
     @type background: C{str}
     @param font: the font used for the axis labels
     @type font: C{str}
     @param attr: widget attributes
     
     @keyword zoom: a flag that indicates whether interactive
                    zooming (using the left mouse button) is enabled; the
                    default is C{False} (no zoom)
     @type zoom: C{bool}
     
     @keyword select: enables the user to select a range along the x axis
                      by dragging the mouse (with the left button pressed)
                      in the area B{under} the x axis. If select is 0,
                      no selection is possible. Otherwise the value of
                      select must be a callable object that is called
                      whenever the selection changes, with a single
                      argument that can be C{None} (no selection) or
                      a tuple containing two x values.
     """
     self.zoom = 0
     if attr.has_key('zoom'):
         self.zoom = attr['zoom']
         del attr['zoom']
     self.selectfn = None
     if attr.has_key('select'):
         self.selectfn = attr['select']
         del attr['select']
     apply(Tkinter.Frame.__init__, (self, master), attr)
     self.canvas = Tkinter.Canvas(self,
                                  width=width,
                                  height=height,
                                  background=background)
     self.canvas.pack(fill=Tkinter.BOTH, expand=Tkinter.YES)
     border_w = self.canvas.winfo_reqwidth() - \
                int(self.canvas.cget('width'))
     border_h = self.canvas.winfo_reqheight() - \
                int(self.canvas.cget('height'))
     self.border = (border_w, border_h)
     self.canvas.bind('<Configure>', self.reconfigure)
     if self.zoom or self.selectfn is not None:
         self.mouse_state = 0
         self.canvas.bind('<Button-1>', self._mousePressed)
         self.canvas.bind('<B1-Motion>', self._mouseMotion)
         self.canvas.bind('<ButtonRelease-1>', self._mouseRelease)
     self.popup_menu = Tkinter.Menu(self.canvas, tearoff=0)
     self.label = None
     self.canvas.bind('<Button-2>', self._showValue)
     self.canvas.bind('<ButtonRelease-2>', self._hideValue)
     self.popup_menu.add_command(label='Auto Scale',
                                 command=self._autoScale)
     self.popup_menu.add_command(label='Run Xmgrace', command=self._xmgr)
     self.canvas.bind('<Button-3>', self._popupMenu)
     self._setsize()
     self.last_draw = None
     self.font = self._testFont(font)
     self.rubberband = None
     self.rectangle = None
     self.selected_range = None
Exemplo n.º 3
0
        t, dt = tnew, tnew - t
        for point in explode_points:
            for item in point:
                item.update(dt)
        cv.update()
        total_time += dt
    # 通过递归持续不断的在背景中添加新烟花
    root.after(wait_time, simulate, cv)


def close(*ignore):
    """停止模拟循环,关闭窗口"""
    global root
    root.quit()


if __name__ == '__main__':
    root = tk.Tk()
    cv = tk.Canvas(root, height=600, width=600)
    # 自己选择一个好的图像背景填充画布
    image = Image.open("tknv.jpg")
    photo = ImageTk.PhotoImage(image)
    cv.create_image(0, 0, image=photo, anchor='nw')

    cv.pack()
    root.protocol("WM_DELETE_WINDOW", close)

    root.after(100, simulate, cv)

    root.mainloop()
Exemplo n.º 4
0
    def __init__(self, root, options):
        """ web2pyDialog constructor  """

        root.title('web2py server')
        self.root = Tkinter.Toplevel(root)
        self.options = options
        self.scheduler_processes = {}
        self.menu = Tkinter.Menu(self.root)
        servermenu = Tkinter.Menu(self.menu, tearoff=0)
        httplog = os.path.join(self.options.folder, 'httpserver.log')
        iconphoto = 'web2py.gif'
        if os.path.exists(iconphoto):
            img = Tkinter.PhotoImage(file=iconphoto)
            self.root.tk.call('wm', 'iconphoto', self.root._w, img)
        # Building the Menu
        item = lambda: start_browser(httplog)
        servermenu.add_command(label='View httpserver.log',
                               command=item)

        servermenu.add_command(label='Quit (pid:%i)' % os.getpid(),
                               command=self.quit)

        self.menu.add_cascade(label='Server', menu=servermenu)

        self.pagesmenu = Tkinter.Menu(self.menu, tearoff=0)
        self.menu.add_cascade(label='Pages', menu=self.pagesmenu)

        #scheduler menu
        self.schedmenu = Tkinter.Menu(self.menu, tearoff=0)
        self.menu.add_cascade(label='Scheduler', menu=self.schedmenu)
        #start and register schedulers from options
        self.update_schedulers(start=True)

        helpmenu = Tkinter.Menu(self.menu, tearoff=0)

        # Home Page
        item = lambda: start_browser('http://www.web2py.com/')
        helpmenu.add_command(label='Home Page',
                             command=item)

        # About
        item = lambda: tkMessageBox.showinfo('About web2py', ProgramInfo)
        helpmenu.add_command(label='About',
                             command=item)

        self.menu.add_cascade(label='Info', menu=helpmenu)

        self.root.config(menu=self.menu)

        if options.taskbar:
            self.root.protocol('WM_DELETE_WINDOW',
                               lambda: self.quit(True))
        else:
            self.root.protocol('WM_DELETE_WINDOW', self.quit)

        sticky = Tkinter.NW

        # IP
        Tkinter.Label(self.root,
                      text='Server IP:',
                      justify=Tkinter.LEFT).grid(row=0,
                                                 column=0,
                                                 sticky=sticky)
        self.ips = {}
        self.selected_ip = Tkinter.StringVar()
        row = 0
        ips = [('127.0.0.1', 'Local (IPv4)')] + \
            ([('::1', 'Local (IPv6)')] if socket.has_ipv6 else []) + \
            [(ip, 'Public') for ip in options.ips] + \
            [('0.0.0.0', 'Public')]
        for ip, legend in ips:
            self.ips[ip] = Tkinter.Radiobutton(
                self.root, text='%s (%s)' % (legend, ip),
                variable=self.selected_ip, value=ip)
            self.ips[ip].grid(row=row, column=1, sticky=sticky)
            if row == 0:
                self.ips[ip].select()
            row += 1
        shift = row
        # Port
        Tkinter.Label(self.root,
                      text='Server Port:',
                      justify=Tkinter.LEFT).grid(row=shift,
                                                 column=0,
                                                 sticky=sticky)

        self.port_number = Tkinter.Entry(self.root)
        self.port_number.insert(Tkinter.END, self.options.port)
        self.port_number.grid(row=shift, column=1, sticky=sticky)

        # Password
        Tkinter.Label(self.root,
                      text='Choose Password:'******'*')
        self.password.bind('<Return>', lambda e: self.start())
        self.password.focus_force()
        self.password.grid(row=shift + 1, column=1, sticky=sticky)

        # Prepare the canvas
        self.canvas = Tkinter.Canvas(self.root,
                                     width=300,
                                     height=100,
                                     bg='black')
        self.canvas.grid(row=shift + 2, column=0, columnspan=2)
        self.canvas.after(1000, self.update_canvas)

        # Prepare the frame
        frame = Tkinter.Frame(self.root)
        frame.grid(row=shift + 3, column=0, columnspan=2)

        # Start button
        self.button_start = Tkinter.Button(frame,
                                           text='start server',
                                           command=self.start)

        self.button_start.grid(row=0, column=0)

        # Stop button
        self.button_stop = Tkinter.Button(frame,
                                          text='stop server',
                                          command=self.stop)

        self.button_stop.grid(row=0, column=1)
        self.button_stop.configure(state='disabled')

        if options.taskbar:
            self.tb = contrib.taskbar_widget.TaskBarIcon()
            self.checkTaskBar()

            if options.password != '<ask>':
                self.password.insert(0, options.password)
                self.start()
                self.root.withdraw()
        else:
            self.tb = None
Exemplo n.º 5
0
    def __init__(self, logger):

        self.logger = logger
        self.drawcolors = ['white', 'black', 'red', 'yellow', 'blue', 'green']

        root = Tkinter.Tk()
        root.title("ImageViewTk Example")
        #root.set_border_width(2)
        #root.connect("delete_event", lambda w, e: self.quit(w))
        self.root = root
        
        #self.select = FileSelection.FileSelection()
        
        vbox = Tkinter.Frame(root, relief=Tkinter.RAISED, borderwidth=1)
        vbox.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)

        canvas = Tkinter.Canvas(vbox, bg="grey", height=512, width=512)
        canvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)

        fi = ImageViewCanvas(logger)
        fi.set_widget(canvas)
        #fi.set_redraw_lag(0.0)
        fi.enable_autocuts('on')
        fi.set_autocut_params('zscale')
        fi.enable_autozoom('on')
        fi.enable_draw(False)
        fi.set_callback('none-move', self.motion)
        fi.set_bg(0.2, 0.2, 0.2)
        fi.ui_setActive(True)
        fi.show_pan_mark(True)
        self.fitsimage = fi

        bd = fi.get_bindings()
        bd.enable_all(True)

        # canvas that we will draw on
        canvas = DrawingCanvas()
        canvas.enable_draw(True)
        canvas.set_drawtype('rectangle', color='lightblue')
        canvas.setSurface(fi)
        self.canvas = canvas
        # add canvas to view
        fi.add(canvas)
        canvas.ui_setActive(True)

        fi.configure(512, 512)

        hbox = Tkinter.Frame(root)
        hbox.pack(side=Tkinter.BOTTOM, fill=Tkinter.X, expand=0)

        self.readout = Tkinter.Label(root, text='')
        self.readout.pack(side=Tkinter.BOTTOM, fill=Tkinter.X, expand=0)
        
        self.drawtypes = fi.get_drawtypes()
        ## wdrawtype = ttk.Combobox(root, values=self.drawtypes,
        ##                          command=self.set_drawparams)
        ## index = self.drawtypes.index('ruler')
        ## wdrawtype.current(index)
        wdrawtype = Tkinter.Entry(hbox, width=12)
        wdrawtype.insert(0, 'rectangle')
        wdrawtype.bind("<Return>", self.set_drawparams)
        self.wdrawtype = wdrawtype

        # wdrawcolor = ttk.Combobox(root, values=self.drawcolors,
        #                           command=self.set_drawparams)
        # index = self.drawcolors.index('blue')
        # wdrawcolor.current(index)
        wdrawcolor = Tkinter.Entry(hbox, width=12)
        wdrawcolor.insert(0, 'blue')
        wdrawcolor.bind("<Return>", self.set_drawparams)
        self.wdrawcolor = wdrawcolor

        self.vfill = Tkinter.IntVar()
        wfill = Tkinter.Checkbutton(hbox, text="Fill", variable=self.vfill)
        self.wfill = wfill

        walpha = Tkinter.Entry(hbox, width=12)
        walpha.insert(0, '1.0')
        walpha.bind("<Return>", self.set_drawparams)
        self.walpha = walpha

        wclear = Tkinter.Button(hbox, text="Clear Canvas",
                            command=self.clear_canvas)
        wopen = Tkinter.Button(hbox, text="Open File",
                               command=self.open_file)
        wquit = Tkinter.Button(hbox, text="Quit",
                               command=lambda: self.quit(root))
        for w in (wquit, wclear, walpha, Tkinter.Label(hbox, text='Alpha:'),
                  wfill, wdrawcolor, wdrawtype, wopen):
            w.pack(side=Tkinter.RIGHT)
Exemplo n.º 6
0
    def _build_maze(self):
        self.canvas = tk.Canvas(
            self,
            bg='white',  #設定畫布大小(?
            height=MAZE_H * UNIT,
            width=MAZE_W * UNIT)

        # create grids
        for c in range(0, MAZE_W * UNIT, UNIT):
            x0, y0, x1, y1 = c, 0, c, MAZE_H * UNIT
            self.canvas.create_line(x0, y0, x1, y1)
        for r in range(0, MAZE_H * UNIT, UNIT):
            x0, y0, x1, y1 = 0, r, MAZE_W * UNIT, r
            self.canvas.create_line(x0, y0, x1, y1)

    # create origin
        origin = np.array([20, 20]) + np.array([0, UNIT * 3])

        # hell
        hell1_center = origin + np.array([UNIT, 0])
        self.hell1 = self.canvas.create_rectangle(hell1_center[0] - 15,
                                                  hell1_center[1] - 15,
                                                  hell1_center[0] + 15,
                                                  hell1_center[1] + 15,
                                                  fill='black')
        # hell
        hell2_center = origin + np.array([UNIT * 2, 0])
        self.hell2 = self.canvas.create_rectangle(hell2_center[0] - 15,
                                                  hell2_center[1] - 15,
                                                  hell2_center[0] + 15,
                                                  hell2_center[1] + 15,
                                                  fill='black')
        # hell
        hell3_center = origin + np.array([UNIT * 3, 0])
        self.hell3 = self.canvas.create_rectangle(hell3_center[0] - 15,
                                                  hell3_center[1] - 15,
                                                  hell3_center[0] + 15,
                                                  hell3_center[1] + 15,
                                                  fill='black')
        # hell
        hell4_center = origin + np.array([UNIT * 4, 0])
        self.hell4 = self.canvas.create_rectangle(hell4_center[0] - 15,
                                                  hell4_center[1] - 15,
                                                  hell4_center[0] + 15,
                                                  hell4_center[1] + 15,
                                                  fill='black')
        # hell
        hell5_center = origin + np.array([UNIT * 5, 0])
        self.hell5 = self.canvas.create_rectangle(hell5_center[0] - 15,
                                                  hell5_center[1] - 15,
                                                  hell5_center[0] + 15,
                                                  hell5_center[1] + 15,
                                                  fill='black')
        # hell
        hell6_center = origin + np.array([UNIT * 6, 0])
        self.hell6 = self.canvas.create_rectangle(hell6_center[0] - 15,
                                                  hell6_center[1] - 15,
                                                  hell6_center[0] + 15,
                                                  hell6_center[1] + 15,
                                                  fill='black')
        # hell
        hell7_center = origin + np.array([UNIT * 7, 0])
        self.hell7 = self.canvas.create_rectangle(hell7_center[0] - 15,
                                                  hell7_center[1] - 15,
                                                  hell7_center[0] + 15,
                                                  hell7_center[1] + 15,
                                                  fill='black')
        # hell
        hell8_center = origin + np.array([UNIT * 8, 0])
        self.hell8 = self.canvas.create_rectangle(hell8_center[0] - 15,
                                                  hell8_center[1] - 15,
                                                  hell8_center[0] + 15,
                                                  hell8_center[1] + 15,
                                                  fill='black')
        # hell
        hell9_center = origin + np.array([UNIT * 9, 0])
        self.hell9 = self.canvas.create_rectangle(hell9_center[0] - 15,
                                                  hell9_center[1] - 15,
                                                  hell9_center[0] + 15,
                                                  hell9_center[1] + 15,
                                                  fill='black')
        # hell
        hell10_center = origin + np.array([UNIT * 10, 0])
        self.hell10 = self.canvas.create_rectangle(hell10_center[0] - 15,
                                                   hell10_center[1] - 15,
                                                   hell10_center[0] + 15,
                                                   hell10_center[1] + 15,
                                                   fill='black')
        # hell
        hell11_center = origin + np.array([UNIT * 0, UNIT * 1])
        self.hell11 = self.canvas.create_rectangle(hell11_center[0] - 15,
                                                   hell11_center[1] - 15,
                                                   hell11_center[0] + 15,
                                                   hell11_center[1] + 15,
                                                   fill='black')
        # hell
        hell12_center = origin + np.array([UNIT * 11, UNIT * 1])
        self.hell12 = self.canvas.create_rectangle(hell12_center[0] - 15,
                                                   hell12_center[1] - 15,
                                                   hell12_center[0] + 15,
                                                   hell12_center[1] + 15,
                                                   fill='black')

        # create oval
        oval_center = origin + np.array([UNIT * 11, 0])
        self.oval = self.canvas.create_oval(oval_center[0] - 15,
                                            oval_center[1] - 15,
                                            oval_center[0] + 15,
                                            oval_center[1] + 15,
                                            fill='yellow')

        # create red rect
        self.rect = self.canvas.create_rectangle(origin[0] - 15,
                                                 origin[1] - 15,
                                                 origin[0] + 15,
                                                 origin[1] + 15,
                                                 fill='red')

        # pack all
        self.canvas.pack()
Exemplo n.º 7
0
import Tkinter
import time

window = Tkinter.Tk()
canvas = Tkinter.Canvas(window, height=800, width=1280)
canvas.pack()

dash = Tkinter.PhotoImage(file = "CenterCircle.gif")
image = canvas.create_image(640,400, image=dash)



for n in range(1,360):
    
    if n<181:
        arc = 240, 0, 1040, 800
        canvas.create_arc(arc, start = 181-n, extent = n-1, outline = 'blue', width = 8, tag='greenarc')
    else:
        arc = 640, 400, 1040, 800
        canvas.create_arc(arc, start = n-181, extent = 361-n, outline = 'blue', width = 8, tag='greenarc')
    
    
    canvas.update()
    #time.sleep(0.01)
    canvas.delete('greenarc')




window.mainloop() #this holds the window open
Exemplo n.º 8
0
def xGC_skew(seq, window=1000, zoom=100, r=300, px=100, py=100):
    """Calculate and plot normal and accumulated GC skew (GRAPHICS !!!)."""
    try:
        import Tkinter as tkinter  # Python 2
    except ImportError:
        import tkinter  # Python 3

    yscroll = tkinter.Scrollbar(orient=tkinter.VERTICAL)
    xscroll = tkinter.Scrollbar(orient=tkinter.HORIZONTAL)
    canvas = tkinter.Canvas(yscrollcommand=yscroll.set,
                            xscrollcommand=xscroll.set,
                            background="white")
    win = canvas.winfo_toplevel()
    win.geometry("700x700")

    yscroll.config(command=canvas.yview)
    xscroll.config(command=canvas.xview)
    yscroll.pack(side=tkinter.RIGHT, fill=tkinter.Y)
    xscroll.pack(side=tkinter.BOTTOM, fill=tkinter.X)
    canvas.pack(fill=tkinter.BOTH, side=tkinter.LEFT, expand=1)
    canvas.update()

    X0, Y0 = r + px, r + py
    x1, x2, y1, y2 = X0 - r, X0 + r, Y0 - r, Y0 + r

    ty = Y0
    canvas.create_text(X0,
                       ty,
                       text="%s...%s (%d nt)" % (seq[:7], seq[-7:], len(seq)))
    ty += 20
    canvas.create_text(X0, ty, text="GC %3.2f%%" % (GC(seq)))
    ty += 20
    canvas.create_text(X0, ty, text="GC Skew", fill="blue")
    ty += 20
    canvas.create_text(X0, ty, text="Accumulated GC Skew", fill="magenta")
    ty += 20
    canvas.create_oval(x1, y1, x2, y2)

    acc = 0
    start = 0
    for gc in GC_skew(seq, window):
        r1 = r
        acc += gc
        # GC skew
        alpha = pi - (2 * pi * start) / len(seq)
        r2 = r1 - gc * zoom
        x1 = X0 + r1 * sin(alpha)
        y1 = Y0 + r1 * cos(alpha)
        x2 = X0 + r2 * sin(alpha)
        y2 = Y0 + r2 * cos(alpha)
        canvas.create_line(x1, y1, x2, y2, fill="blue")
        # accumulated GC skew
        r1 = r - 50
        r2 = r1 - acc
        x1 = X0 + r1 * sin(alpha)
        y1 = Y0 + r1 * cos(alpha)
        x2 = X0 + r2 * sin(alpha)
        y2 = Y0 + r2 * cos(alpha)
        canvas.create_line(x1, y1, x2, y2, fill="magenta")

        canvas.update()
        start += window

    canvas.configure(scrollregion=canvas.bbox(tkinter.ALL))
Exemplo n.º 9
0
######
# Create Controller
#######
# Instantiate and place slider
speed_slider = Tkinter.Scale(root, from_=20, to=1, variable=speed_intvar,    
                              label='speed')
speed_slider.grid(row=1, column=0, sticky=Tkinter.W)
# Create and place directions for the user
text = Tkinter.Label(root, text='Drag slider \nto adjust\nspeed.')
text.grid(row=0, column =0)

######
# Create View
#######
# Create and place a canvas
canvas = Tkinter.Canvas(root, width=600, height=600, background='#FFFFFF')
canvas.grid(row=0, rowspan=2, column=1)

# Create a circle on the canvas to match the initial model

amount = 20

def rand8bit():
    return random.randint(0,255)

def randpos():
    return random.randint(r, 600-r)

circles = []

for i in range(amount):
Exemplo n.º 10
0
	        break

	if flag3==1:
		result.config(text="BREAKAGE DETECTED")
	ima=images.replace('.jpg','res.jpg')
	cv2.imwrite(ima,img)
	pro_image(ima)

def load_image(entry):
	pro_img.paste(Image.open("camo.jpg"))
	original_img.paste(Image.open(entry))
	start_detection(entry)

root.title("XXX  PEACE KEEPER  XXX")

canvas = tk.Canvas(root,height=HEIGHT,width=WIDTH)
canvas.pack()

bg = Image.open("camo.jpg")
background_image = ImageTk.PhotoImage(bg)
background_label = tk.Label(root, image=background_image)
background_label.place(relwidth=1, relheight=1)

top_frame = tk.Frame(root,bg="#071F2D",bd=5)
top_frame.place(relx=0.5,rely=0.03,relwidth=0.9,relheight=0.1,anchor='n')

entry = tk.Entry(top_frame,font=("Courier", 20))
entry.place(relwidth=0.65,relheight=1)

load = tk.Button(top_frame,font=("Courier", 20),text=" LOAD ",bg="#394344",command=lambda:load_image(entry.get()))
load.place(relx=0.68,relwidth=0.32,relheight=1)
Exemplo n.º 11
0
    def _create_step2_widgets(self):
        self.current_step = 2

        assert self.xcorr_ca is not None

        self.ROOT_FRAME_2 = tk.Frame(self)
        self.ROOT_FRAME_2.pack(fill=tk.BOTH, expand=1)

        upper_frame_2 = tk.LabelFrame(self.ROOT_FRAME_2, text="Station code: " + self.station_code)
        upper_frame_2.pack(anchor=tk.N, side=tk.TOP)

        coeff_widgets_frame_2 = tk.Frame(upper_frame_2)
        coeff_widgets_frame_2.pack(anchor=tk.NW, side=tk.TOP, padx=2, pady=2)

        coeff_widgets_label = tk.Label(coeff_widgets_frame_2, font=8,
                                       text="Tune coefficients to optimize clustering and filtering of outliers")
        coeff_widgets_label.pack(anchor=tk.W, side=tk.TOP, pady=2)

        coeff0_label = tk.LabelFrame(coeff_widgets_frame_2, text="Coefficient 0 (x-separation)")
        coeff0_label.pack(anchor=tk.W, side=tk.LEFT, padx=2)
        coeff0_spinbox = tk.Spinbox(coeff0_label, from_=0.0, to=100.0, increment=0.1,
                                    textvariable=self.cluster_coeff0)
        coeff0_spinbox.pack(padx=2, pady=2)

        coeff1_label = tk.LabelFrame(coeff_widgets_frame_2, text="Coefficient 1 (y-separation)")
        coeff1_label.pack(anchor=tk.W, side=tk.LEFT, padx=2)
        coeff1_spinbox = tk.Spinbox(coeff1_label, from_=0.0, to=100.0, increment=0.1,
                                         textvariable=self.cluster_coeff1)
        coeff1_spinbox.pack(padx=2, pady=2)

        coeff2_label = tk.LabelFrame(coeff_widgets_frame_2, text="Coefficient 2 (slope)")
        coeff2_label.pack(anchor=tk.W, side=tk.LEFT, padx=2)
        coeff2_spinbox = tk.Spinbox(coeff2_label, from_=0.0, to=100.0, increment=0.1,
                                    textvariable=self.cluster_coeff2)
        coeff2_spinbox.pack(padx=2, pady=2)

        control_buttons_frame_2 = tk.Frame(upper_frame_2)
        control_buttons_frame_2.pack(anchor=tk.NW, side=tk.TOP, padx=2, pady=2, fill=tk.X)

        self.next_button = tk.Button(control_buttons_frame_2)
        self.next_button['text'] = "Continue..."
        self.next_button['command'] = self._goto_step3
        self.next_button.pack(anchor=tk.NW, side=tk.LEFT)

        self.quit_button = tk.Button(control_buttons_frame_2)
        self.quit_button['text'] = "Quit"
        self.quit_button['command'] = self._quit_app
        self.quit_button.pack(anchor=tk.SE, side=tk.RIGHT)

        lower_frame_2 = tk.LabelFrame(self.ROOT_FRAME_2, text="Clustering Result")
        lower_frame_2.pack(anchor=tk.N, side=tk.TOP)

        self.cluster_figure_canvas_2 = tk.Canvas(lower_frame_2)
        self.cluster_figure_canvas_2.pack(anchor=tk.N, side=tk.TOP, fill=tk.BOTH, expand=True, padx=4, pady=4)

        self._refresh_clustering_canvas()

        self.update()

        coeff0_spinbox['command'] = self._refresh_clustering_canvas
        coeff1_spinbox['command'] = self._refresh_clustering_canvas
        coeff2_spinbox['command'] = self._refresh_clustering_canvas
        coeff0_spinbox.bind('<FocusOut>', self._refresh_clustering_canvas)
        coeff0_spinbox.bind('<Return>', self._refresh_clustering_canvas)
        coeff1_spinbox.bind('<FocusOut>', self._refresh_clustering_canvas)
        coeff1_spinbox.bind('<Return>', self._refresh_clustering_canvas)
        coeff2_spinbox.bind('<FocusOut>', self._refresh_clustering_canvas)
        coeff2_spinbox.bind('<Return>', self._refresh_clustering_canvas)
Exemplo n.º 12
0
    def build_grid(self):
        """
        construir los objetos necesarios
        """
        self.canvas = tk.Canvas(self.window,
                                bg='white',
                                height=MAZE_H * UNIT,
                                width=MAZE_W * UNIT)

        # grillar un tabla de UNIT * UNIT, iterar para ambos lados
        for c in range(0, MAZE_W * UNIT, UNIT):
            x0, y0, x1, y1 = c, 0, c, MAZE_W * UNIT
            self.canvas.create_line(x0, y0, x1, y1)
        for r in range(0, MAZE_H * UNIT, UNIT):
            x0, y0, x1, y1 = 0, r, MAZE_H * UNIT, r
            self.canvas.create_line(x0, y0, x1, y1)

        # punto de comienzo en el centro
        origin = np.array([int(UNIT / 2), int(UNIT / 2)])

        # definir centro de la celda
        hell1_center = origin + np.array([UNIT * 2, UNIT])

        # infierno 1
        self.hell1 = self.canvas.create_rectangle(hell1_center[0] - 15,
                                                  hell1_center[1] - 15,
                                                  hell1_center[0] + 15,
                                                  hell1_center[1] + 15,
                                                  fill='black')
        # infierno 2
        hell2_center = origin + np.array([UNIT, UNIT * 2])
        self.hell2 = self.canvas.create_rectangle(hell2_center[0] - 15,
                                                  hell2_center[1] - 15,
                                                  hell2_center[0] + 15,
                                                  hell2_center[1] + 15,
                                                  fill='black')
        # infierno 3
        hell3_center = origin + np.array([UNIT, UNIT * 5])
        self.hell3 = self.canvas.create_rectangle(hell3_center[0] - 15,
                                                  hell3_center[1] - 15,
                                                  hell3_center[0] + 15,
                                                  hell3_center[1] + 15,
                                                  fill='black')
        # infierno 4
        hell4_center = origin + np.array([UNIT * 8, UNIT * 5])
        self.hell4 = self.canvas.create_rectangle(hell4_center[0] - 15,
                                                  hell4_center[1] - 15,
                                                  hell4_center[0] + 15,
                                                  hell4_center[1] + 15,
                                                  fill='black')
        # infierno 5
        hell5_center = origin + np.array([UNIT * 9, UNIT * 2])
        self.hell5 = self.canvas.create_rectangle(hell5_center[0] - 15,
                                                  hell5_center[1] - 15,
                                                  hell5_center[0] + 15,
                                                  hell5_center[1] + 15,
                                                  fill='black')
        # infierno 6
        hell6_center = origin + np.array([UNIT * 10, UNIT * 10])
        self.hell6 = self.canvas.create_rectangle(hell6_center[0] - 15,
                                                  hell6_center[1] - 15,
                                                  hell6_center[0] + 15,
                                                  hell6_center[1] + 15,
                                                  fill='black')
        # infierno 7
        hell7_center = origin + np.array([UNIT * 6, UNIT * 8])
        self.hell7 = self.canvas.create_rectangle(hell7_center[0] - 15,
                                                  hell7_center[1] - 15,
                                                  hell7_center[0] + 15,
                                                  hell7_center[1] + 15,
                                                  fill='black')
        # infierno 8
        hell8_center = origin + np.array([UNIT * 5, UNIT * 8])
        self.hell8 = self.canvas.create_rectangle(hell8_center[0] - 15,
                                                  hell8_center[1] - 15,
                                                  hell8_center[0] + 15,
                                                  hell8_center[1] + 15,
                                                  fill='black')
        # infierno 9
        hell9_center = origin + np.array([UNIT * 3, UNIT * 3])
        self.hell9 = self.canvas.create_rectangle(hell9_center[0] - 15,
                                                  hell9_center[1] - 15,
                                                  hell9_center[0] + 15,
                                                  hell9_center[1] + 15,
                                                  fill='black')
        # infierno 10
        hell10_center = origin + np.array([UNIT * 3, UNIT * 3])
        self.hell10 = self.canvas.create_rectangle(hell10_center[0] - 15,
                                                   hell10_center[1] - 15,
                                                   hell10_center[0] + 15,
                                                   hell10_center[1] + 15,
                                                   fill='black')

        # crear donde esta el oro
        oval_center1 = origin + UNIT * 4
        self.oval1 = self.canvas.create_oval(oval_center1[0] - 15,
                                             oval_center1[1] - 15,
                                             oval_center1[0] + 15,
                                             oval_center1[1] + 15,
                                             fill='yellow')

        oval_center2 = origin + np.array([UNIT * 7, UNIT * 7])
        self.oval2 = self.canvas.create_oval(oval_center2[0] - 15,
                                             oval_center2[1] - 15,
                                             oval_center2[0] + 15,
                                             oval_center2[1] + 15,
                                             fill='yellow')

        oval_center3 = origin + np.array([UNIT * 9, UNIT * 1])
        self.oval3 = self.canvas.create_oval(oval_center3[0] - 15,
                                             oval_center3[1] - 15,
                                             oval_center3[0] + 15,
                                             oval_center3[1] + 15,
                                             fill='yellow')

        # crear el rectangulo del agente
        self.rect = self.canvas.create_rectangle(origin[0] - 15,
                                                 origin[1] - 15,
                                                 origin[0] + 15,
                                                 origin[1] + 15,
                                                 fill='green')

        # tomar todos con método pack de canvas
        self.canvas.pack()
Exemplo n.º 13
0
	def fillInUI(self, parent):
		parent.columnconfigure(0, pad=2)
		parent.columnconfigure(1, pad=2)
		import itertools
		row = itertools.count()

		self.showBackbone = BackboneOption(parent, row.next(),
					'Show backbone as', 'ribbon', None)
		self.showSide = SideOption(parent, row.next(),
				'Show side (sugar/base) as', 'fill/slab',
				self._showSideCB)
		self.showOrientation = BooleanOption(parent, row.next(),
				'Show base orientation', default.ORIENT, None)

		import Tix
		self.nb = Tix.NoteBook(parent)
		self.nb.grid(row=row.next(), column=0, columnspan=2, sticky=Tk.EW, padx=2)

		# ladder page
		self.nb.add("ladder", label="Ladder Options")
		f = self.nb.page("ladder")
		if Tk.TkVersion >= 8.5:
			parent.tk.call('grid', 'anchor', f._w, Tk.N)

		prow = itertools.count()
		self.skipNonBase = BooleanOption(f, prow.next(),
				'Ignore non-base H-bonds', default.IGNORE, None)
		self.showStubs = BooleanOption(f, prow.next(),
					'Show stubs', default.STUBS, None)
		self.rungRadius = FloatOption(f, prow.next(), 'Rung radius',
							default.RADIUS, None)
		self.rungRadius.min = 0.0
		self.useExisting = BooleanOption(f, prow.next(),
			'Using existing H-bonds', default.USE_EXISTING,
			self._useExistingCB)
		from FindHBond.gui import RelaxParams
		self.relaxParams = RelaxParams(f, None, colorOptions=False)
		#self.relaxParams.relaxConstraints = False
		self.relaxParams.grid(row=prow.next(), columnspan=2,
							sticky='nsew', padx=2)

		# slab page
		self.nb.add("slab", label="Slab Options")
		f = self.nb.page("slab")
		if Tk.TkVersion >= 8.5:
			parent.tk.call('grid', 'anchor', f._w, Tk.N)

		prow = itertools.count()
		self.thickness = FloatOption(f, prow.next(), 'Thickness',
						default.THICKNESS, None)
		self.thickness.min = 0.01
		self.shape = ShapeOption(f, prow.next(), 'Slab object',
							default.SHAPE, None)
		self.hideBases = BooleanOption(f, prow.next(),
					'Hide base atoms', default.HIDE, None)
		self.showGlycosidic = BooleanOption(f, prow.next(),
				'Separate glycosidic bond', default.GLYCOSIDIC,
				None)

		self.nb.add("style", label="Slab Style", raisecmd=self.map)
		# style page
		f = self.nb.page("style")
		if Tk.TkVersion >= 8.5:
			f.tk.call('grid', 'anchor', f._w, Tk.N)

		info = NA.findStyle(self.currentStyle)
		from chimera.preferences import saveui
		f2 = Tk.Frame(f)
		self.saveui = saveui.SaveUI(f2, self)
		f2.grid(row=prow.next(), column=0, columnspan=2, sticky=Tk.EW,
								padx=2, pady=2)

		self.anchor = AnchorOption(f, prow.next(), 'Anchor',
					info[NA.ANCHOR], self._drawStyle)

		f2 = Pmw.Group(f, tag_text=NA.PURINE.title())
		f2.grid(row=prow.next(), column=0, columnspan=2, sticky=Tk.EW,
									padx=2)
		f2 = f2.interior()
		f2.columnconfigure(0, weight=1, pad=2, uniform='a')
		f2.columnconfigure(1, weight=1, uniform='a')
		f2.columnconfigure(2, weight=1)

		self.purine_canvas = Tk.Canvas(f2, width=1, height=1) #,
						#borderwidth=2, relief=Tk.RIDGE)
		r = prow.next()
		self.purine_canvas.grid(row=r, column=0, rowspan=3,
						sticky=Tk.NSEW, padx=2, pady=2)
		corners = info[NA.PURINE]
		self.puLL = Float2Option(f2, prow.next(), 'Lower left',
					corners[0], self._drawStyle, startCol=1)
		self.puUR = Float2Option(f2, prow.next(), 'Upper right',
					corners[1], self._drawStyle, startCol=1)

		f3 = Pmw.Group(f, tag_text="%s, %s" % (NA.PYRIMIDINE.title(),
						NA.PSEUDO_PYRIMIDINE.title()))
		r = prow.next()
		f3.grid(row=r, column=0, columnspan=2, sticky=Tk.EW, padx=2)
		f3 = f3.interior()
		f3.columnconfigure(0, weight=1, pad=2, uniform='a')
		f3.columnconfigure(1, weight=1, uniform='a')
		f3.columnconfigure(2, weight=1)

		self.pyrimidine_canvas = Tk.Canvas(f3, width=1, height=1) #,
						#borderwidth=2, relief=Tk.RIDGE)
		r = prow.next()
		self.pyrimidine_canvas.grid(row=r, column=0, rowspan=3,
						sticky=Tk.NSEW, padx=2, pady=2)

		corners = info[NA.PYRIMIDINE]
		self.pyLL = Float2Option(f3, prow.next(), 'Lower left',
					corners[0], self._drawStyle, startCol=1)
		self.pyUR = Float2Option(f3, prow.next(), 'Upper right',
					corners[1], self._drawStyle, startCol=1)

		self.restrict = Tk.IntVar(parent)
		self.restrict.set(1)
		cb = Tk.Checkbutton(parent, variable=self.restrict,
		    text="Restrict OK/Apply to current selection, if any")
		cb.grid(row=row.next(), columnspan=2)

		parent.pack(ipady=2)

		self._showSideCB()
		chimera.triggers.addHandler(NA.TRIGGER_SLAB_STYLES,
						self._updateStyles, None)
Exemplo n.º 14
0
    def __init__(self):
        # Variable for showing the "ruler" to false
        self.ViewOffsets = False

        # Variable used to track the width and height of a character
        #  Narrow = 8 bits
        #  Wide = 16 bits
        self.charwidth = 8
        self.charheight = 19

        # Variable for tracking the margin size (both Vertical and Horizontal) of the canvas
        # attempting to draw outside of this margin will not be rendered on the canvas
        self.margins = 2

        # Variable for tracking this Tk Widget's root widget
        self.root = Tkinter.Tk()

        # Set the Title bar of the widget
        self.root.title("UEFI Glyph Creator")

        # Calculate the height/width of each square in a glyph
        #  if the resolution is low, then set a minimum of 20
        self.smallestsquare = self.root.winfo_screenheight() / 70
        if self.smallestsquare < 20:
            self.smallestsquare = 20

        # Set the current square size based on the smallest square
        self.square = self.smallestsquare

        # Create a Menu, and configure the root widget to use it
        menubar = Tkinter.Menu(self.root, tearoff=0)
        self.root.config(menu=menubar)

        # Add an Edit Menu to the menu bar
        EditMenu = Tkinter.Menu(menubar, tearoff=0)
        EditMenu.add_command(label="Increase Size", command=self.IncreaseSize)
        EditMenu.add_command(label="Decrease Size", command=self.DecreaseSize)
        EditMenu.add_checkbutton(label="Show Offsets",
                                 variable=self.ViewOffsets,
                                 command=self.SwitchShowOffsets)
        EditMenu.add_command(label="Clear", command=self.Clear)
        menubar.add_cascade(label="Edit", menu=EditMenu)

        # Add an Options menu to the menu bar
        OptionsMenu = Tkinter.Menu(menubar, tearoff=0)
        OptionsMenu.add_checkbutton(label="WideChar",
                                    variable=self.charwidth,
                                    command=self.SwitchToWideChar)
        OptionsMenu.add_command(label="Copy To Clipboard",
                                command=self.CopyBufferToClipBoard)
        OptionsMenu.add_command(label="Import from ClipBoard",
                                command=self.ImportClipBoardToBuffer)
        menubar.add_cascade(label="Options", menu=OptionsMenu)

        # Add a Help menu to the menu bar
        HelpMenu = Tkinter.Menu(menubar, tearoff=0)
        HelpMenu.add_command(label="About", command=self.About)
        menubar.add_cascade(label="Help", menu=HelpMenu)

        # Create a Canvas widget and add it to the root Widget
        self.canvas = Tkinter.Canvas(self.root, bg="white")
        self.canvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)

        # Bind the left mouse button click to function Clicked
        self.root.bind('<Button-1>', self.Clicked)

        # Bind keypad + and the plus keys to the IncreaseSize function
        self.root.bind('<KP_Add>', self.IncreaseSize)
        self.root.bind('<plus>', self.IncreaseSize)

        # Bind keypad - and the minus keys to the DecreaseSize function
        self.root.bind('<KP_Subtract>', self.DecreaseSize)
        self.root.bind('<minus>', self.DecreaseSize)

        # Initialize the Canvas area with the Glyph Information
        self.InitializeCanvas()

        # Create a status bar that show the current Width and Height
        self.StatusBar = Tkinter.Label(self.root,
                                       text="",
                                       bd=1,
                                       relief=Tkinter.GROOVE,
                                       anchor=Tkinter.W)
        self.StatusBar.config(text="Width = %d Height = %d  " %
                              (self.charwidth, self.charheight))
        self.StatusBar.pack(side=Tkinter.TOP, fill=Tkinter.X)

        # Start the Widget
        self.root.mainloop()
Exemplo n.º 15
0
    root.bind('<Alt-Key-x>', callback)
    root.bind('<Button2-Motion>', drag)
    box.bind('<<ListboxSelect>>', selected)
    box.bind('b', wrap(swap, box))
    prog = ttk.Progressbar(frame,
                           orient='horizontal',
                           length=500,
                           mode='determinate',
                           maximum=5,
                           value=0)
    prog.grid(column=0, row=6)
    # prog.bind('<Double-Button-1>', wrap(step, prog))
    prog.bind('<Button-1>', wrap(start, prog))
    prog.bind('<Double-Button-1>', wrap(stop, prog))

    canvas = tkinter.Canvas(frame, width=500, height=500)
    canvas.grid(row=5, column=0)
    canvas.create_line(10, 10, 490, 490)
    canpoint = [0, 0]

    canvas.bind('<Button-1>',
                (lambda *args: begin_lines(canvas, canpoint, *args)))
    canvas.bind('<Button1-Motion>',
                (lambda *args: draw_line(canvas, canpoint, *args)))

    try:
        label.configure(image=pim)
    except:
        traceback.print_exc()
        do = False
    if do:
Exemplo n.º 16
0
 class TkinterEvent(object):
     x_root = 0
     y_root = 0
     x = 0
     y = 0
     widget = tk.Canvas()
Exemplo n.º 17
0
        radialPixPerDeg = float(self.endRad - self.begRad) / (self.endAng -
                                                              self.begAng)
        radPix = self.begRad + (radialPixPerDeg * (ang - self.begAng))

        adjAng = (ang * self.angScale) + self.angOff
        xPos = self.xctr + (radPix * RO.MathUtil.cosd(adjAng))
        yPos = self.yctr - (radPix * RO.MathUtil.sind(adjAng))
        return (xPos, yPos)


if __name__ == '__main__':
    from RO.Wdg.PythonTk import PythonTk
    root = PythonTk()

    cnv = Tkinter.Canvas(root, width=201, height=201)
    cnv.pack()
    ctrPlus(cnv, 80, 80, 10, 5)
    ctrPlus(cnv, 100, 80, 10, 5, 5)
    ctrX(cnv, 80, 100, 10, 5)
    ctrX(cnv, 100, 100, 10, 5, 5)
    ctrCircle(cnv, 80, 120, 10, 1)
    ctrCircle(cnv, 100, 120, 10, 5)

    ctrCircle(cnv, 120, 80, 10)
    ctrPlus(cnv, 120, 80, 10, holeRad=5)
    ctrX(cnv, 120, 80, 10, holeRad=5)

    ctrCircle(cnv, 120, 100, 10, width=5)
    ctrPlus(cnv, 120, 100, 10, holeRad=5, width=5)
    ctrX(cnv, 120, 100, 10, holeRad=5, width=5)
Exemplo n.º 18
0
    def __init__(self, master, board):
        self.__margin = 20
        self.__tile_size = 40
        self.__canvas_width = None
        self.__canvas_height = None
        self.__robot_images = {}
        self.__target_images = {}
        self.__solution_images = []
        self.__direction_images = []
        self.__entered = set()
        self.__slots = {}
        self.__highlights = {}
        self.__targets = {}
        self.__moves = {}
        self.__moves_short = {}
        self.__robots = {}
        self.__barriers = {}
        self.__tiles = []

        self.__canvas_width = board.size * self.__tile_size + 2 * self.__margin
        self.__canvas_height = (
            1 + board.size) * self.__tile_size + 3 * self.__margin

        self.__canvas = Tkinter.Canvas(master,
                                       width=self.__canvas_width,
                                       height=self.__canvas_height)
        self.__canvas.pack()

        colors = ['green', 'red', 'blue', 'yellow']
        shapes = ['moon', 'sun', 'star', 'saturn']
        directions = [('north', 0, -1), ("east", 1, 0), ('south', 0, 1),
                      ('west', -1, 0)]
        for orientation in ['left', 'right']:
            path = 'img/tile_{orientation}.gif'.format(orientation=orientation)
            self.__tiles.append(Tkinter.PhotoImage(file=path))
        for direction in ['north', 'west']:
            path = 'img/wall_{direction}.gif'.format(direction=direction)
            self.__barriers[direction] = (Tkinter.PhotoImage(file=path), -6,
                                          -6)
        for color in colors:
            path = 'img/robot_{color}.gif'.format(color=color)
            self.__robots[color] = Tkinter.PhotoImage(file=path)
            for shape in shapes:
                path = "img/{shape}_{color}.gif".format(shape=shape,
                                                        color=color)
                self.__targets[(color, shape)] = Tkinter.PhotoImage(file=path)
            for (direction, dx, dy) in directions:
                path = "img/arrow_{color}_{direction}.gif".format(
                    color=color, direction=direction)
                self.__moves[(color, dx, dy)] = Tkinter.PhotoImage(file=path)
                path = "img/move_{color}_{direction}.gif".format(
                    color=color, direction=direction)
                self.__moves_short[(color, dx,
                                    dy)] = Tkinter.PhotoImage(file=path)
        for x in range(0, board.size):
            for y in range(0, board.size):
                self.__canvas.create_image(
                    self.__margin + self.__tile_size * x,
                    self.__margin + self.__tile_size * y,
                    anchor=Tkinter.NW,
                    image=self.__tiles[(x + y) % len(self.__tiles)])
        for (t, m, x, y) in board.targets:
            self.__target_images[(x, y)] = self.__canvas.create_image(
                self.__margin + self.__tile_size * x,
                self.__margin + self.__tile_size * y,
                anchor=Tkinter.NW,
                image=self.__targets[(t, m)])
            self.__canvas.itemconfig(self.__target_images[(x, y)],
                                     state=Tkinter.HIDDEN)
        for (r, (x, y)) in board.pos.items():
            self.__robot_images[r] = self.__canvas.create_image(
                self.__margin + self.__tile_size * x,
                self.__margin + self.__tile_size * y,
                anchor=Tkinter.NW,
                image=self.__robots[r])
        for (d, x, y) in board.barriers:
            (img, dx, dy) = self.__barriers[d]
            self.__canvas.create_image(
                self.__margin + self.__tile_size * x + dx,
                self.__margin + self.__tile_size * y + dy,
                anchor=Tkinter.NW,
                image=img)
        self.__solve_button = self.__canvas.create_text(
            board.size * self.__tile_size / 2 + self.__margin,
            (0.5 + board.size) * self.__tile_size + 2 * self.__margin,
            text="Solve!",
            activefill="blue",
            state=Tkinter.HIDDEN)
        self.__solving_text = self.__canvas.create_text(
            board.size * self.__tile_size / 2 + self.__margin,
            (0.5 + board.size) * self.__tile_size + 2 * self.__margin,
            text="Solving...",
            state=Tkinter.HIDDEN)
        self.__canvas.bind('<Motion>', self.__mouse_move_event)
        self.__canvas.bind('<Button-1>', self.__mouse_click_event)
Exemplo n.º 19
0
    # Uses vector math to compute the new velocities after the collision has commenced.
    '''https://en.wikipedia.org/wiki/Elastic_collision#Two-dimensional_collision_with_two_moving_objects'''
    v1f = scalar_product(COLLISION_LOSS,
                    subtract_vectors(v1,
                                scalar_product(float(dot_product(subtract_vectors(v1,v2),subtract_vectors(x1,x2)))/float(square_sum(subtract_vectors(x1,x2))),
                                            subtract_vectors(x1,x2))))
    v2f = subtract_vectors(add_vectors(v1,v2),v1f)  # Conservation of momentum
    return [v1f, v2f]

'''
    Tkinter Canvas
'''
root = TK.Tk()
root.wm_title('MiniPool')

canvas = TK.Canvas(root, width=DIMENSIONS[0], height=DIMENSIONS[1], background='#FFFFFF')
canvas.grid(row=0, column=0, columnspan=4)

speed_intvar = TK.IntVar()
speed_intvar.set(0)
direction_intvar = TK.IntVar()
direction_intvar.set(360)

# Buttons and sliders
start_button = TK.Button(root, text='New Game', command=new_game)
start_button.grid(row=1, column=0)
shoot_button = TK.Button(root, text='Shoot', command=shoot, state=TK.ACTIVE, disabledforeground='#000000')
shoot_button.grid(row=1, column=3)
direction_slider = TK.Scale(root, from_=0, to=720, orient=TK.HORIZONTAL, length = 760, variable=direction_intvar,
                                label='Direction', command=adjust_trajectory, showvalue=0)
direction_slider.grid(row=1, column=1)
Exemplo n.º 20
0
            x += d * (0.5 - random.random()) * 0.25
            y += d * (0.5 - random.random()) * 0.25
        x += x0
        y += y0
        dots.append(Point(x, y))
    dots.append(Point(x1, y1))
    return dots


if __name__ == "__main__":
    root = tk.Tk()
    root.title("Tree")
    gw, gh = 800, 600
    canvas = tk.Canvas(
        root,
        width=gw,
        height=gh,
    )
    canvas.pack()
    tree = Tree(root,
                canvas,
                Point(gw / 2, gh - 20),
                Point(gw / 2, gh * 0.2),
                branches=2,
                depth=8)
    root.bind("n", lambda evt: tree.new())
    root.bind("=", lambda evt: tree.chgDepth(0))
    root.bind("w", lambda evt: tree.chgDepth(1))
    root.bind("s", lambda evt: tree.chgDepth(-1))
    root.bind("a", lambda evt: tree.chgBranch(1))
    root.bind("d", lambda evt: tree.chgBranch(-1))
Exemplo n.º 21
0
    def __init__(self, root, options):
        """ web2pyDialog constructor  """

        import Tkinter
        import tkMessageBox

        bg_color = 'white'
        root.withdraw()

        self.root = Tkinter.Toplevel(root, bg=bg_color)
        self.root.resizable(0, 0)
        self.root.title(ProgramName)

        self.options = options
        self.scheduler_processes = {}
        self.menu = Tkinter.Menu(self.root)
        servermenu = Tkinter.Menu(self.menu, tearoff=0)
        httplog = os.path.join(self.options.folder, self.options.log_filename)
        iconphoto = os.path.join('extras', 'icons', 'web2py.gif')
        if os.path.exists(iconphoto):
            img = Tkinter.PhotoImage(file=iconphoto)
            self.root.tk.call('wm', 'iconphoto', self.root._w, img)
        # Building the Menu
        item = lambda: start_browser(httplog)
        servermenu.add_command(label='View httpserver.log',
                               command=item)

        servermenu.add_command(label='Quit (pid:%i)' % os.getpid(),
                               command=self.quit)

        self.menu.add_cascade(label='Server', menu=servermenu)

        self.pagesmenu = Tkinter.Menu(self.menu, tearoff=0)
        self.menu.add_cascade(label='Pages', menu=self.pagesmenu)

        #scheduler menu
        self.schedmenu = Tkinter.Menu(self.menu, tearoff=0)
        self.menu.add_cascade(label='Scheduler', menu=self.schedmenu)
        #start and register schedulers from options
        self.update_schedulers(start=True)

        helpmenu = Tkinter.Menu(self.menu, tearoff=0)

        # Home Page
        item = lambda: start_browser('http://www.web2py.com/')
        helpmenu.add_command(label='Home Page',
                             command=item)

        # About
        item = lambda: tkMessageBox.showinfo('About web2py', ProgramInfo)
        helpmenu.add_command(label='About',
                             command=item)

        self.menu.add_cascade(label='Info', menu=helpmenu)

        self.root.config(menu=self.menu)

        if options.taskbar:
            self.root.protocol('WM_DELETE_WINDOW',
                               lambda: self.quit(True))
        else:
            self.root.protocol('WM_DELETE_WINDOW', self.quit)

        sticky = Tkinter.NW

        # Prepare the logo area
        self.logoarea = Tkinter.Canvas(self.root,
                                background=bg_color,
                                width=300,
                                height=300)
        self.logoarea.grid(row=0, column=0, columnspan=4, sticky=sticky)
        self.logoarea.after(1000, self.update_canvas)

        logo = os.path.join('extras', 'icons', 'splashlogo.gif')
        if os.path.exists(logo):
            img = Tkinter.PhotoImage(file=logo)
            pnl = Tkinter.Label(self.logoarea, image=img, background=bg_color, bd=0)
            pnl.pack(side='top', fill='both', expand='yes')
            # Prevent garbage collection of img
            pnl.image = img

        # Prepare the banner area
        self.bannerarea = Tkinter.Canvas(self.root,
                                bg=bg_color,
                                width=300,
                                height=300)
        self.bannerarea.grid(row=1, column=1, columnspan=2, sticky=sticky)

        Tkinter.Label(self.bannerarea, anchor=Tkinter.N,
                      text=str(ProgramVersion + "\n" + ProgramAuthor),
                      font=('Helvetica', 11), justify=Tkinter.CENTER,
                      foreground='#195866', background=bg_color,
                      height=3).pack(side='top',
                                     fill='both',
                                     expand='yes')

        self.bannerarea.after(1000, self.update_canvas)

        # IP
        Tkinter.Label(self.root,
                      text='Server IP:', bg=bg_color,
                      justify=Tkinter.RIGHT).grid(row=4,
                                                  column=1,
                                                  sticky=sticky)
        self.ips = {}
        self.selected_ip = Tkinter.StringVar()
        row = 4
        ips = [('127.0.0.1', 'Local (IPv4)')] + \
            ([('::1', 'Local (IPv6)')] if socket.has_ipv6 else []) + \
            [(ip, 'Public') for ip in options.ips] + \
            [('0.0.0.0', 'Public')]
        for ip, legend in ips:
            self.ips[ip] = Tkinter.Radiobutton(
                self.root, bg=bg_color, highlightthickness=0,
                selectcolor='light grey', width=30,
                anchor=Tkinter.W, text='%s (%s)' % (legend, ip),
                justify=Tkinter.LEFT,
                variable=self.selected_ip, value=ip)
            self.ips[ip].grid(row=row, column=2, sticky=sticky)
            if row == 4:
                self.ips[ip].select()
            row += 1
        shift = row

        # Port
        Tkinter.Label(self.root,
                      text='Server Port:', bg=bg_color,
                      justify=Tkinter.RIGHT).grid(row=shift,
                                                  column=1, pady=10,
                                                  sticky=sticky)

        self.port_number = Tkinter.Entry(self.root)
        self.port_number.insert(Tkinter.END, self.options.port)
        self.port_number.grid(row=shift, column=2, sticky=sticky, pady=10)

        # Password
        Tkinter.Label(self.root,
                      text='Choose Password:'******'*')
        self.password.bind('<Return>', lambda e: self.start())
        self.password.focus_force()
        self.password.grid(row=shift + 1, column=2, sticky=sticky)

        # Prepare the canvas
        self.canvas = Tkinter.Canvas(self.root,
                                     width=400,
                                     height=100,
                                     bg='black')
        self.canvas.grid(row=shift + 2, column=1, columnspan=2, pady=5,
                         sticky=sticky)
        self.canvas.after(1000, self.update_canvas)

        # Prepare the frame
        frame = Tkinter.Frame(self.root)
        frame.grid(row=shift + 3, column=1, columnspan=2, pady=5,
                   sticky=sticky)

        # Start button
        self.button_start = Tkinter.Button(frame,
                                           text='start server',
                                           command=self.start)

        self.button_start.grid(row=0, column=0, sticky=sticky)

        # Stop button
        self.button_stop = Tkinter.Button(frame,
                                          text='stop server',
                                          command=self.stop)

        self.button_stop.grid(row=0, column=1,  sticky=sticky)
        self.button_stop.configure(state='disabled')

        if options.taskbar:
            import gluon.contrib.taskbar_widget
            self.tb = gluon.contrib.taskbar_widget.TaskBarIcon()
            self.checkTaskBar()

            if options.password != '<ask>':
                self.password.insert(0, options.password)
                self.start()
                self.root.withdraw()
        else:
            self.tb = None
Exemplo n.º 22
0
    def __init__(self, master=None, label=None, minval=0.0, maxval=100.0,
		 incr=None, init=None, width=150, height=20, withValue=1,
		 immediate=1, left=10, right=10 , labelformat = '%4.2f',
                 cursortype='float', lookup=None):

	CallbackFunctions.__init__(self)
	self.frame = Tkinter.Frame(master)
	self.lastx=0
	self.immediate = immediate
        self.labelformat = labelformat
        self.cursortype = cursortype
        
	if not label: label = '' #'slider'
	fnt='-*-helvetica-medium-r-narrow-*-*-120-*-*-*-*-*-*'
	self.label = Tkinter.Label(self.frame, text=label, font=fnt)
	self.label.pack(side=Tkinter.LEFT)
	if withValue: height = max(30, height)
	self.withValue = withValue

	self.draw = Tkinter.Canvas(self.frame, width=width, height=height,
			   relief=Tkinter.SUNKEN)
	self.width = width
	self.height = height
	self.left = left
	self.right = width-right

        # MS May 1st add support for discrete set of values
        self.lookup = lookup # can be set to a list of values indexed by
                             # int(value)
        if lookup is not None:
            # force min and max to provide proper indices
            minval = 0.0
            maxval = len(lookup)-1
            incr = 1
            
	self.max=maxval
	self.min=minval
	self._ComputeCst()
	self.incr = incr
	self.incrCanvas = None

	if incr:
	    self.incrCanvas = round(incr*self.cst)

	if withValue: m = self.height / 2
	else: m = int(self.height * 0.75)
	self.middle = m

	self.draw.create_line( self.left, m, self.right, m,
			       width=2, fill='black')

	y = m-10 # 10 is the cursor's height
	l = self.left
	self.cursor = self.draw.create_polygon( l, m, l+5, y, l-5, y, l, m,
						fill='blue', tag='cursor')

	if withValue:
	    y = self.middle+10
	    self.valueLabel = self.draw.create_text( l, y, text= str(minval),
						     font=fnt, tag='cursor')

	self.draw.pack(side = Tkinter.RIGHT)

	if init is None:
            init = self.min
        if self.lookup:
            init = self.lookup.index(init)
	self.Set(init)
	Tkinter.Widget.bind(self.draw, "<1>", self.MoveCursor)
	Tkinter.Widget.bind(self.draw, "<B1-Motion>", self.MoveCursor)
	if not immediate:
	    Tkinter.Widget.bind(self.draw, "<ButtonRelease-1>", self.MouseUp)
Exemplo n.º 23
0
g.SetRandomNodePosition()

# create the window object for painting the graph on
root = tk.Tk()

# make it cover the entire screen
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))

c_width = w - border * 2
c_height = h - border * 2

root.title("Force directed layout of graphs (by Mathias Bader) - version 0.1")
c = tk.Canvas(root,
              width=c_width + 2 * border,
              height=c_height + 2 * border,
              bg='white')
# left-click
c.bind("<Button-1>", event_button1_pressed)
c.bind("<B1-Motion>", event_button1_motion)
c.bind("<ButtonRelease-1>", event_button1_released)
# right-click
c.bind("<Button-3>", event_button3_pressed)
c.bind("<B3-Motion>", event_button3_motion)
c.bind("<ButtonRelease-3>", event_button3_released)
# keyboard key
c.bind("<Key>", key_pressed)
c.pack()
c.focus_set()

g.paintGraph()
Exemplo n.º 24
0
    def initUI(self):
        ###################################################################
        # Create a Hamster joystick window which contains
        # 1. a canvas widget where "sensor readings" are displayed
        # 2. a square representing Hamster
        # 3. 4 canvas items to display floor sensors and prox sensors
        # 4. a button for exit, i.e., a call to stopProg(), given in this class
        # 5. listen to key press and key release when focus is on this window
        ###################################################################

        # canvas calculation
        canvas_width = 1280 / 2
        canvas_height = 720 / 2
        # robot calculation
        robot_side = 100
        robot_center_x = canvas_width / 2
        robot_center_y = canvas_height / 2
        robot_x1 = robot_center_x - robot_side / 2
        robot_y1 = robot_center_y - robot_side / 2
        robot_x2 = robot_center_x + robot_side / 2
        robot_y2 = robot_center_y + robot_side / 2
        # floor left calculation
        floor_side = 10
        floorl_x1 = robot_x1
        floorl_y1 = robot_y1
        floorl_x2 = robot_x1 + floor_side
        floorl_y2 = robot_y1 + floor_side
        # floor right calculation
        floorr_x1 = robot_x1 + robot_side - floor_side
        floorr_y1 = robot_y1
        floorr_x2 = floorr_x1 + floor_side
        floorr_y2 = floorr_y1 + floor_side
        # prox calculation
        prox_l_x = floorl_x1
        prox_l_y = floorl_y1
        prox_r_x = floorr_x2
        prox_r_y = floorr_y2 - floor_side

        self.exit = tk.Button(self.root, text='Exit', commands=self.stopProg())
        self.exit.pack(side='left')

        # init everything
        self.root.title("Hamster")
        self.root.geometry("1280x720+0+0")
        self.floor_l_id = tk.Label(self.root, text="FloorLeft: N/A")
        self.floor_l_id.pack()
        self.floor_r_id = tk.Label(self.root, text="FloorRight: N/A")
        self.floor_r_id.pack()
        self.prox_l_id = tk.Label(self.root, text="ProxLeft: N/A")
        self.prox_l_id.pack()
        self.prox_r_id = tk.Label(self.root, text="ProxRight: N/A")
        self.prox_r_id.pack()
        self.canvas = tk.Canvas(self.root,
                                width=canvas_width,
                                height=canvas_height,
                                bg="white")
        self.canvas_robot_id = self.canvas.create_rectangle(robot_x1,
                                                            robot_y1,
                                                            robot_x2,
                                                            robot_y2,
                                                            fill="gold")
        self.canvas_floorl_id = self.canvas.create_rectangle(floorl_x1,
                                                             floorl_y1,
                                                             floorl_x2,
                                                             floorl_y2,
                                                             fill="black")
        self.canvas_floorr_id = self.canvas.create_rectangle(floorr_x1,
                                                             floorr_y1,
                                                             floorr_x2,
                                                             floorr_y2,
                                                             fill="black")
        self.canvas_proxl_id = self.canvas.create_line(prox_l_x,
                                                       prox_l_y,
                                                       prox_l_x,
                                                       prox_l_y,
                                                       fill="black",
                                                       width=4)
        self.canvas_proxr_id = self.canvas.create_line(prox_r_x,
                                                       prox_r_y,
                                                       prox_r_x,
                                                       prox_r_y,
                                                       fill="black",
                                                       width=4)
        self.canvas.pack()

        # add key listeners
        self.root.bind('<KeyPress>', self.keydown)
        self.root.bind('<KeyRelease>', self.keyup)
Exemplo n.º 25
0
    def __init__(self):
        # Retrieve params:
        self._frequency = rospy.get_param('~frequency', 0.0)
        self._scale = rospy.get_param('~scale', 1.0)
        self._holonomic = rospy.get_param('~holonomic', False)

        # Create twist publisher:
        self._pub_cmd = rospy.Publisher('mouse_vel', Twist, queue_size=100)

        # Initialize twist components to zero:
        self._v_x = 0.0
        self._v_y = 0.0
        self._w = 0.0

        # Initialize mouse position (x, y) to None (unknown); it's initialized
        # when the mouse button is pressed on the _start callback that handles
        # that event:
        self._x = None
        self._y = None

        # Create window:
        self._root = Tkinter.Tk()
        self._root.title('Mouse Teleop')

        # Make window non-resizable:
        self._root.resizable(0, 0)

        # Create canvas:
        self._canvas = Tkinter.Canvas(self._root, bg='white')

        # Create canvas objects:
        self._canvas.create_arc(0,
                                0,
                                0,
                                0,
                                fill='red',
                                outline='red',
                                width=1,
                                style=Tkinter.PIESLICE,
                                start=90.0,
                                tag='w')
        self._canvas.create_line(0, 0, 0, 0, fill='red', width=4, tag='v_x')

        if self._holonomic:
            self._canvas.create_line(0,
                                     0,
                                     0,
                                     0,
                                     fill='blue',
                                     width=4,
                                     tag='v_y')

        # Create canvas text objects:
        self._text_v_x = Tkinter.StringVar()
        if self._holonomic:
            self._text_v_y = Tkinter.StringVar()
        self._text_w = Tkinter.StringVar()

        self._label_v_x = Tkinter.Label(self._root,
                                        anchor=Tkinter.W,
                                        textvariable=self._text_v_x)
        if self._holonomic:
            self._label_v_y = Tkinter.Label(self._root,
                                            anchor=Tkinter.W,
                                            textvariable=self._text_v_y)
        self._label_w = Tkinter.Label(self._root,
                                      anchor=Tkinter.W,
                                      textvariable=self._text_w)

        if self._holonomic:
            self._text_v_x.set('v_x = %0.2f m/s' % self._v_x)
            self._text_v_y.set('v_y = %0.2f m/s' % self._v_y)
            self._text_w.set('w   = %0.2f deg/s' % self._w)
        else:
            self._text_v_x.set('v = %0.2f m/s' % self._v_x)
            self._text_w.set('w = %0.2f deg/s' % self._w)

        self._label_v_x.pack()
        if self._holonomic:
            self._label_v_y.pack()
        self._label_w.pack()

        # Bind event handlers:
        self._canvas.bind('<Button-1>', self._start)
        self._canvas.bind('<ButtonRelease-1>', self._release)

        self._canvas.bind('<Configure>', self._configure)

        if self._holonomic:
            self._canvas.bind('<B1-Motion>', self._mouse_motion_linear)
            self._canvas.bind('<Shift-B1-Motion>', self._mouse_motion_angular)

            self._root.bind('<Shift_L>', self._change_to_motion_angular)
            self._root.bind('<KeyRelease-Shift_L>',
                            self._change_to_motion_linear)
        else:
            self._canvas.bind('<B1-Motion>', self._mouse_motion_angular)

        self._canvas.pack()

        # If frequency is positive, use synchronous publishing mode:
        if self._frequency > 0.0:
            # Create timer for the given frequency to publish the twist:
            period = rospy.Duration(1.0 / self._frequency)

            self._timer = rospy.Timer(period, self._publish_twist)

        # Start window event manager main loop:
        self._root.mainloop()
Exemplo n.º 26
0
Tkinter GUI Application Development Hotshot
"""

import Tkinter

root = Tkinter.Tk()


#pie chart
def prop(n):
    return 360.0 * n / 1000


Tkinter.Label(root, text='Pie Chart').pack()

c = Tkinter.Canvas(width=154, height=154)
c.pack()

c.create_arc((2, 2, 152, 152),
             fill="#FAF402",
             outline="#FAF402",
             start=prop(0),
             extent=prop(200))
c.create_arc((2, 2, 152, 152),
             fill="#00AC36",
             outline="#00AC36",
             start=prop(200),
             extent=prop(400))
c.create_arc((2, 2, 152, 152),
             fill="#7A0871",
             outline="#7A0871",
Exemplo n.º 27
0
    def __init__(self, parent, width=8,height=8, position=[0,0], options={}, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)

        # set root of frame
        self.root = parent
        self.root.title("Environment")
        self.root.resizable(0,0)

        # assign svg-reader, allows reading in svg-figures
        self.reader = SVGReader()

        # set constants
        # conversion of meter to pixels, required for plotting
        self.meter_to_pixel = options['meter_to_pixel'] if 'meter_to_pixel' in options else 50
        self.n_cells = options['n_cells'] if 'n_cells' in options else [20, 20]  # [horizontal, vertical]

        # make environment frame and size it
        self.frame_width_px = int(width*self.meter_to_pixel)
        self.frame_height_px = int(height*self.meter_to_pixel)
        self.frame_width_m = width
        self.frame_height_m = height
        # top left corner point of the frame [px]
        self.position = [pos * self.meter_to_pixel for pos in position]
        self.canvas = tk.Canvas(self.root, width=self.frame_width_px, height=self.frame_height_px,
                                borderwidth=0, highlightthickness=0)
        self.canvas.configure(cursor="tcross")
        self.canvas.grid(row=0,columnspan=3)
        # round up sizes, such that frame width is guaranteed to be reached
        self.cell_width_px = int(np.ceil(self.frame_width_px*1./self.n_cells[0]))
        self.cell_height_px = int(np.ceil(self.frame_height_px*1./self.n_cells[1]))
        self.rows = self.n_cells[0]
        self.columns = self.n_cells[1]

        self.draw_grid()  # draw grid in canvas

        self.obstacles = []  # list to hold all obstacles
        self.clicked_positions = []  # list to hold all clicked positions

        self.canvas.bind("<Button-1>", self.make_obstacle)  # left mouse button makes obstacle
        self.canvas.bind("<Button-3>", self.get_position)  # right mouse button gives start and goal position

        # Add buttons
        ready_button = tk.Button(self.root, text="Ready", fg="green", command=self.build_environment)
        ready_button.grid(row=2, column=0)

        quit_button = tk.Button(self.root, text="Quit", fg="red", command=self.canvas.quit)
        quit_button.grid(row=3, column=0)

        remove_button = tk.Button(self.root, text="Remove", fg="black", command=self.remove_last_obstacle)
        remove_button.grid(row=4, column=0)

        load_button = tk.Button(self.root, text="Load", fg="black", command=self.load_environment)
        load_button.grid(row=5, column=0)

        load_svg_button = tk.Button(self.root, text="Load SVG", fg="black", command=self.load_svg)
        load_svg_button.grid(row=6, column=0)

        self.save_env = tk.BooleanVar(value=False)
        label_save = tk.Checkbutton(self.root, text="Save [yes/no]", variable=self.save_env)
        label_save.grid(row=7,column=0)

        # indicate cell size
        self.cell_size_label = tk.Label(self.root, text='Cell size: ' + str(np.round(self.frame_width_m*1./self.n_cells[0],3)) + 'x' + str(np.round(self.frame_height_m*1./self.n_cells[0],3)) + ' [m]')
        self.cell_size_label.grid(row=1, column=1)

        # indicate clicked position
        # self.clickedPos = tk.StringVar()
        # labelClickedPos = tk.Label(self, text="Clicked position [x,y]")
        # labelClickedPosEntry = tk.Entry(self, bd =0, textvariable=self.clickedPos)
        # labelClickedPos.pack()
        # labelClickedPosEntry.pack()

        # select obstacle shape (rectangle or circle)
        self.shape = tk.StringVar()
        self.circle_button = tk.Radiobutton(self.root, text="Circle", variable=self.shape, value='circle')
        self.circle_button.grid(row=2, column=2)
        self.rectangle_button = tk.Radiobutton(self.root, text="Rectangle", variable=self.shape, value='rectangle')
        self.rectangle_button.grid(row=3,column=2)

        # select obstacle size
        self.width = tk.DoubleVar()
        label_width = tk.Label(self.root, text="Width [m]")
        label_width_entry = tk.Entry(self.root, bd =0, textvariable=self.width)
        label_width.grid(row=2,column=1)
        label_width_entry.grid(row=3,column=1)

        self.height = tk.DoubleVar()
        label_height = tk.Label(self.root, text="Height [m]")
        label_height_entry = tk.Entry(self.root, bd =0, textvariable=self.height)
        label_height.grid(row=4,column=1)
        label_height_entry.grid(row=5,column=1)

        self.radius = tk.DoubleVar()
        label_radius = tk.Label(self.root, text="Radius [m]")
        label_radius_entry = tk.Entry(self.root, bd =0, textvariable=self.radius)
        label_radius.grid(row=6,column=1)
        label_radius_entry.grid(row=7,column=1)

        # select obstacle velocity
        self.vel_x = tk.DoubleVar(value=0.0)
        label_velx = tk.Label(self.root, text="x-velocity [m/s]")
        label_velx_entry = tk.Entry(self.root, bd =0, textvariable=self.vel_x)
        label_velx.grid(row=4,column=2)
        label_velx_entry.grid(row=5,column=2)

        self.vel_y = tk.DoubleVar(value=0.0)
        label_vely = tk.Label(self.root, text="y-velocity [m/s]")
        label_vely_entry = tk.Entry(self.root, bd =0, textvariable=self.vel_y)
        label_vely.grid(row=6,column=2)
        label_vely_entry.grid(row=7,column=2)

        # select if moving obstacle should bounce off other obstacles or off the walls
        self.bounce = tk.BooleanVar(value=False)
        label_bounce = tk.Checkbutton(self.root, text="Bounce [yes/no]", variable=self.bounce)
        label_bounce.grid(row=8,column=2)

        # add scrollbars
        self.hbar=tk.Scrollbar(self.root,orient=tk.HORIZONTAL)
        self.hbar.grid(row=9, column = 0)
        self.hbar.config(command=self.canvas.xview)
        self.vbar=tk.Scrollbar(self.root,orient=tk.VERTICAL)
        self.vbar.grid(row=0, column = 3)
        self.vbar.config(command=self.canvas.yview)
        self.canvas.config(width=1000, height=600)  # limit canvas size such that it fits on screen
        self.canvas.config(xscrollcommand=self.hbar.set, yscrollcommand=self.vbar.set)
Exemplo n.º 28
0
    def initUI(self):

        self.parent.title("Cryo Shield")
        self.grid(row=0, column=0)

        self.tCernox = Tk.StringVar()
        self.tCernox.set("153.52 K")

        self.pollLongAB = Tk.IntVar()
        self.pollLongCERNOX = Tk.IntVar()

        self.whichDataSet = 0

        #ITEMS - First specify all the items!
        title = Tk.Label(self.parent,
                         text="DNP Insert CryoShield",
                         font="TkHeadingFont 16",
                         foreground="#000000")

        ### ALLEN BRADLEY
        abDataFrame = Tk.LabelFrame(self.parent,
                                    bd=1,
                                    text="Allen-Bradley",
                                    width=15)

        self.fig = Figure(figsize=(8, 3.5))
        self.ax1 = self.fig.add_axes([0.1, 0.1, 0.8, 0.8])
        self.ax1.set_ylabel("AB1")
        self.ax1.set_xlabel("Time (s)")
        self.ax1.grid(False)

        self.ax1.set_xlim([self.pOAB.xlimL, self.pOAB.xlimU])
        self.ax1.set_ylim([self.pOAB.ylimL, self.pOAB.ylimU])

        self.canvas = FigureCanvasTkAgg(self.fig, master=abDataFrame)

        plotOptionButtonAB = Tk.Button(
            abDataFrame,
            text="Plot Options",
            command=lambda: self.changePlotOptionsAB(self.pOAB, only="AB"))

        longTermSignalAB = Tk.Checkbutton(abDataFrame,
                                          text=" Long term",
                                          variable=self.pollLongAB,
                                          command=self.readCryoShield)

        #use the frame colour to match the plot colour for a given resistor!
        levelCanvas = Tk.Canvas(abDataFrame, width=400, height=50)
        levelCanvas.create_rectangle(30,
                                     10,
                                     120,
                                     40,
                                     outline="#f00",
                                     fill="#acf")
        levelCanvas.create_rectangle(150,
                                     10,
                                     240,
                                     40,
                                     outline="#f0f",
                                     fill="#acf")
        levelCanvas.create_rectangle(270,
                                     10,
                                     370,
                                     40,
                                     outline="#00f",
                                     fill="#acf")

        #Cernox Frame
        cernoxFrame = Tk.LabelFrame(self.parent, bd=1, text="Cernox", width=15)

        #this contains the temperature plot and goes into a second canvas
        self.fig2 = Figure(figsize=(8, 3.5))
        self.ax2 = self.fig2.add_axes([0.1, 0.1, 0.8, 0.8])
        self.ax2.set_ylabel("T (K)")
        self.ax2.set_xlabel("Time (h)")
        self.ax2.grid(False)
        self.canvas2 = FigureCanvasTkAgg(self.fig2, master=cernoxFrame)

        self.ax2.set_xlim([self.pOCERNOX.xlimL, self.pOCERNOX.xlimU])
        self.ax2.set_ylim([self.pOCERNOX.ylimL, self.pOCERNOX.ylimU])

        plotOptionButtonCERNOX = Tk.Button(
            cernoxFrame,
            text="Plot Options",
            command=lambda: self.changePlotOptionsCERNOX(self.pOCERNOX,
                                                         only="CERNOX"))

        temperatureFrame = Tk.Frame(cernoxFrame,
                                    width=400,
                                    height=50,
                                    background="#dddddd")
        tCernoxLabel = Tk.Label(temperatureFrame,
                                width=12,
                                text="Temperature:",
                                anchor=Tk.W,
                                foreground="#0000CC",
                                font="TkIconFont 15")
        tCernoxValue = Tk.Label(temperatureFrame,
                                textvariable=self.tCernox,
                                anchor=Tk.W,
                                foreground="#0000CC",
                                font="TkIconFont 15")

        longTermSignalCERNOX = Tk.Checkbutton(cernoxFrame,
                                              text=" Long term",
                                              variable=self.pollLongCERNOX,
                                              command=self.readCryoShield)

        tReadButton = Tk.Button(self.parent,
                                text="Read",
                                command=lambda: self.readCryoShield(only=""))

        self.var = Tk.IntVar()
        autoUpdateButton = Tk.Checkbutton(
            self.parent,
            text="Auto Poll",
            variable=self.var,
            command=lambda: self.autoPoll(self.var.get()))
        #autoPollButton.var = self.doAutoPoll

        cernoxFrame.columnconfigure(2, minsize=400)
        cernoxFrame.rowconfigure(1, minsize=40)

        #LAYOUT - Now arrange the layout
        title.grid(row=0, column=0, padx=2, pady=2, sticky=Tk.W + Tk.E)

        abDataFrame.grid(row=1, column=0, padx=2, pady=2, sticky=Tk.W + Tk.E)
        self.canvas.get_tk_widget().grid(row=0,
                                         column=0,
                                         columnspan=3,
                                         sticky=Tk.W + Tk.E + Tk.N + Tk.S)
        plotOptionButtonAB.grid(row=1, column=0, padx=2, pady=2, sticky=Tk.E)
        longTermSignalAB.grid(row=1, column=1, padx=2, pady=2, sticky=Tk.E)
        levelCanvas.grid(row=1, column=2, sticky=Tk.E)

        cernoxFrame.grid(row=2, column=0, padx=2, pady=2, sticky=Tk.E)
        self.canvas2.get_tk_widget().grid(row=0,
                                          column=0,
                                          columnspan=3,
                                          sticky=Tk.W + Tk.E + Tk.N + Tk.S)
        plotOptionButtonCERNOX.grid(row=1,
                                    column=0,
                                    padx=2,
                                    pady=2,
                                    sticky=Tk.E)

        longTermSignalCERNOX.grid(row=1, column=1, padx=2, pady=2, sticky=Tk.E)
        temperatureFrame.grid(row=1, column=2, padx=2, pady=2)

        tCernoxValue.pack(side=Tk.RIGHT)
        tCernoxLabel.pack(side=Tk.RIGHT)

        tReadButton.grid(row=3, column=0, padx=2, pady=2, sticky=Tk.E)
        autoUpdateButton.grid(row=5, column=0, padx=2, pady=2, sticky=Tk.E)

        #self.canvas2.get_tk_widget().grid(row = 1, column = 0, columnspan = 4, sticky = Tk.W + Tk.E + Tk.N + Tk.S)

        tReadButton.focus_set()

        print "Tk widget obtained and gridded"
Exemplo n.º 29
0
if __name__ == "__main__":

    win = gui.Tk()
    print(gui.TclVersion)
    win.geometry("+0+0")
    SEQ_FONT = gui_font.Font(size=32, weight='bold')
    TRANSPORT_FONT = gui_font.Font(size=20, weight='bold')
    CONFIG_FONT = gui_font.Font(size=14, weight='bold')
    LEGEND_FONT = gui_font.Font(size=12, slant='italic')
    YASS_SMALL_FONT = gui_font.Font(size=22, slant='italic')
    win.title("Y A S S !   Yet Another Step Sequencer")
    win.bind("<Escape>", quitProperly)

    canvas = gui.Canvas(win,
                        width=WIDTH * PPI * DRAW_SCALE,
                        height=HEIGHT * PPI * DRAW_SCALE,
                        bg=DRAW_BACKCOLOR)
    canvas.grid()

    drawRectangle(canvas, WIDTH / 2.0, HEIGHT / 2.0, WIDTH, HEIGHT)
    drawStepLeds(canvas)
    drawTransportKeys(canvas)
    drawSequenceKeys(canvas)
    drawGlobalKeys(canvas)
    drawRightKeys(canvas)
    drawDisplay(canvas)
    drawEncoder(canvas)
    drawLine2(canvas)
    drawLine3(canvas)
    drawBigYass(canvas)
    drawSmallYass(canvas)
Exemplo n.º 30
0
    def createWidgets(self):
        
       utils_cl = Common_Utils()
       sql_path = '../sql_scripts/'

       cnx = mysql.connector.connect(user=credential_list[0], password=credential_list[1],
                                  host=credential_list[2],
                                  database=credential_list[3],
                                  get_warnings=True,
                                  buffered=True)
        
       cursor = cnx.cursor()
       cursor_high = cnx.cursor()
       
       # returns list [ [0] readable list of 'stop_mysqlid : trunc stop_name', [1] integer stop_mysqlid ]
       # this list is the stops that can serve as a map center
       
       sql_phrase = utils_cl.read_sql_script(sql_path + 'select_current_map_starts.sql')
       
       cursor_high.execute(sql_phrase)
        
       ln = cursor_high.fetchone()
       temp_log_path = u'../data/temp_log_drawmaps.log'
       
       write = sys.stdout.write

       # loops through all of the 'starts' in the 'best_times' table
       while ln:
        
        
        starting_loc = ln[1]
        try:
            starting_loc = int(starting_loc)
            
            # want start to be persistent, separate persistent variable
            starting_saved = starting_loc
        except:
            print ln[0]
            sys.exit('Starting location wasn''t an integer - exiting')

        # x_dim and y_dim are size of map in pixels, or are supposed to be
        
        x_dim = 1024
        y_dim = 1024
        
        # x_ctr and y_ctr are center points on map, or are supposed to be
        
        x_ctr = int(round(( x_dim / 2 ) + (x_dim * .175)))
        y_ctr = int(round(( y_dim / 2 ) + (y_dim * .175)))
        
        # quit button, if you need it
        
        self.quitButton = tk.Button(self, text='Quit', command=self.quit)
        self.quitButton.grid()
        can = tk.Canvas(self, height=str(y_dim) + 'p', width=str(x_dim) + 'p', bg='#fff')

        # returns [0] maximim travel time for all trips from the starting_loc
        # for purposes of getting the scale right
        
        sql_phrase = "SELECT MAX(total_time) FROM mbta_data.mbta_map_best_times WHERE start_mysqlid = %(starting_loc)s GROUP BY start_mysqlid"
        
        cursor.execute(sql_phrase, {u'starting_loc' : starting_saved})
        max_time = cursor.fetchone()[0]
        
        # defensive programming - make sure the cursor is reset
        cursor.fetchall()

        # this is the central query
        # returns the list of best times with their attributes
        # the query itself determines the total travel time and compass direction
        # that work all is done in sql
        
        sql_phrase = utils_cl.read_sql_script(sql_path + 'populate_map_points_from_start.sql')
        
        # returns list with the following index locations:
        # [0] dest_mysqlid, [1] total_time (seconds), [2] trip_count, [3] transp_mode, [4] route_mysqlid,
        # [5] route_name, [6] dest_name, [7] route_color, [8]compass, [9]trip_leg, 
        # [10] start_loc, [11] prev_stop_mysqlid,  [12]immed_prev_stop
        
        cursor.execute(sql_phrase, {u'starting_loc' : starting_loc})  
                                    
        line = cursor.fetchone()
        
        # overall structure of script:
        # makes calculatons in section below and stores them in a dictionary
        # does this for two reasons (1) want entirely to draw the lines first, then the station points on top
        # (2) line drawing requires reference to a dictionary of the locations of the previous stops
        # so need both complete dictionaries before drawing lines
        
        # initial values
        point_dict = {}
        prev_stops = {}
        max_time_route = {}
        rail_dest_list = []
        
        route_mysqlid = -1

        dest_name = ''
        
        # reads through query of stops, total times
        while line:
            
            # belt-and-suspenders: stop if no more lines of query
            if line == [] or line == None or not line:
                break
            
            # use named local variables in place of index locations
            # to make code manipularions easier to read
            
            dest_mysqlid = line[0]    
            leng = line[1]
            total_min = (line[1]) /60  # converts output time in seconds to minutes
            trip_count = line[2]
            transp_mode = line[3]
            route_mysqlid = line[4]
            route_name = line[5]
            dest_name = line[6]
            color = line[7]
            comp = line[8]
            trip_leg = line[9]
            prev_stop_mysqlid = line[11]
            immed_prev_stop = line[12]
            
            # converts count into ratio, with 2512 being the most trips for any one origin/dest pair
            # probably would be more correct to run query with MAX(count)
            
            if trip_count != None:
                trip_ratio = line[2] / 2512
                
                # gave multipliers for heavy rail service
                # otherwise bus dots are overwhelming/dominant
                
                if transp_mode == 1:  trip_ratio = trip_ratio * 1.7
                if transp_mode == 2:  trip_ratio = trip_ratio * 40
            
            else:  # avoids potential errors nonetype and div by 0 errors
                trip_ratio = .01
            
            # convert total time in seconds into distance from origin on map
            
            if leng != 0:
                leng = (x_ctr) * scale_coef( ( leng / max_time ) )

            # convert compass direction into radians
            if comp == None:
                comp = 0
            
            comp = (comp * math.pi) / 180  #convert to radians
            
            # caluclate points on map for stop
            x_point = ( math.sin(comp) * leng ) + x_ctr
            y_point = -1 * ( math.cos(comp) * leng ) + y_ctr
            
            # use white color for stops reached by walking
            if color != None:
                color = '#' + str(color)
            else:
                color = '#fff'
                
            if color.upper() == '#FFFF7C':
                color = '#E7D450'
                        
            # update dictionary of *previous* stops
            # coordinates and colors of previous stops may be used in some situations
            # where it is desired to draw the route that *departs* from the station
            # rather than the one that arrives
            if prev_stop_mysqlid not in prev_stops:
                    
                prev_stops.update({prev_stop_mysqlid : dest_mysqlid})
                  
            # if stop already in list, only update if the new route is bigger/better than old route
            # or is not walking or bus
            else:
                if ( (point_dict[prev_stops[prev_stop_mysqlid]]['trip_ratio'] < trip_ratio and
                        (point_dict[prev_stops[prev_stop_mysqlid]]['transp_mode'] in [None, 3] or 
                        transp_mode not in [None, 3])) or
                        (point_dict[prev_stops[prev_stop_mysqlid]]['transp_mode'] in [None, 3] and
                             transp_mode not in [None, 3])
                        ):
                    prev_stops.update({prev_stop_mysqlid : dest_mysqlid})

            if transp_mode != None:
                        
                if route_mysqlid not in max_time_route:
                    max_time_route.update({route_mysqlid : {'min' : leng, 'max' : leng}})
                else:
                    if leng > max_time_route[route_mysqlid]['max']:
                        max_time_route[route_mysqlid].update({'max' : leng})
                    if leng < max_time_route[route_mysqlid]['min']:
                        max_time_route[route_mysqlid].update({'min' : leng})
                
                if transp_mode != 3:
                    rail_dest_list.append(dest_mysqlid)
            
            # dictionary of all destinations and point/other info
            
            point_dict.update( { dest_mysqlid : {
                    'x_point' : x_point,
                    'y_point' : y_point,
                    'total_min' : total_min,
                    'trip_count' : trip_count,
                    'route_mysqlid' : route_mysqlid,
                    'route_name' : route_name,
                    'immed_prev_stop' : immed_prev_stop,
                    'trip_ratio' : trip_ratio,
                    'color' : color,
                    'transp_mode' : transp_mode,
                    'prev_stop_mysqlid' : prev_stop_mysqlid,
                    'comp' : comp,
                    'leng' : leng,
                    'dest_name' : dest_name
                    } })
            
            
            line = cursor.fetchone()
        
        # draw background square; covers entire canvas
        
        can.create_rectangle(0,0,x_ctr * 2.5, y_ctr * 2.5, fill='#fff', outline='#fff')
        

        # get name of origin stop
                
        sql_phrase = "SELECT stop_name FROM mbta_data.sched_stops WHERE mysql_id = %(starting_loc)s"
        cursor.execute(sql_phrase, {u'starting_loc' : starting_saved})
        
        start_name = cursor.fetchone()[0]
        cursor.fetchall()
        
        txt = start_name
        
        trunc_loc = txt.find(u' - ')
        if trunc_loc != -1:
            txt = txt[:trunc_loc]
               
        trunc_loc = txt.find(u'Station')
        if trunc_loc != -1 and u'south station' not in txt.lower() and u'north station' not in txt.lower():
            txt = txt[:trunc_loc]
        
        can.create_text(x_ctr, y_ctr - 16, text = txt, font = ('UnBom', -48), fill = '#A3A3A3', anchor = 's' )
                
        
        # add legends
        
        fl = tk.PhotoImage(file='../legend.ppm')
        
        can.create_image((x_ctr * 2) - 18, (y_ctr * 2) - 20, anchor=tk.SE, image=fl, state=tk.NORMAL)

        fl_2 = tk.PhotoImage(file='../legend_2.ppm')        

        can.create_image( 36, (y_ctr * 2) - 56, anchor=tk.SW, image=fl_2, state=tk.NORMAL)
        
        # draw the reference circles
        circle_time_mins = [15, 30, 60]
        for i in range(0, len(circle_time_mins), 1):
            
            leng = (x_ctr) * scale_coef( ( ( circle_time_mins[i] * 60 ) / max_time ) )
          
            can.create_oval(x_ctr - leng , y_ctr - leng, x_ctr + leng, y_ctr + leng, fill = '', outline = '#A3A3A3', width = 5)
            
            can.create_text(x_ctr, y_ctr - leng, text = str(circle_time_mins[i]) + 'min.', anchor = 's', font = ('UnBom', -24), fill = '#A3A3A3')
            can.create_text(x_ctr, y_ctr + leng + 2, text = str(circle_time_mins[i]) + 'min.', anchor = 'n', font = ('UnBom', -24), fill = '#A3A3A3')
        
        # this loop is run after dictionaries are completely full
        # draws the maps using data stored earlier        
        
        # draw all of the lines first
        # first so that they do not interfere with dots
        
        for i in range(1, len(point_dict.keys()), 1):
            
            immed_prev_stop = None
            
            if (point_dict[point_dict.keys()[i]]['route_mysqlid'] not in [0, None] and                
                    point_dict[point_dict.keys()[i]]['immed_prev_stop'] != None and
                    point_dict[point_dict.keys()[i]]['immed_prev_stop'] in point_dict and
                    (point_dict[point_dict.keys()[i]]['transp_mode'] == 
                    point_dict[point_dict[point_dict.keys()[i]]['immed_prev_stop']]['transp_mode'])):
              
                immed_prev_stop = point_dict[point_dict.keys()[i]]['immed_prev_stop']
                
            
            elif (point_dict[point_dict.keys()[i]]['route_mysqlid'] not in [0, None]
                  and point_dict[point_dict.keys()[i]]['immed_prev_stop'] != None):
                
                sql_phrase = utils_cl.read_sql_script(sql_path + 'select_traceback_route.sql')
                
                immed_prev_stop = point_dict[point_dict.keys()[i]]['immed_prev_stop']
                
                transp_mode = point_dict[point_dict.keys()[i]]['transp_mode']
                transp_mode_2 = None
                
                sql_data = ({
                    'origin_mysqlid' : point_dict[point_dict.keys()[i]]['prev_stop_mysqlid'],
                    'immed_prev_mysqlid' : immed_prev_stop,
                    'start_mysqlid' : starting_saved
                    })
                
                count = 0
                
                if (not (immed_prev_stop in rail_dest_list and transp_mode == transp_mode_2 ) and
                      not (immed_prev_stop == point_dict[point_dict.keys()[i]]['prev_stop_mysqlid']) and not (count >= 100)):
                    
                    trip_mode = [-1, -2, -3]
                    
                    count_2 = 0
                    while (trip_mode[0] != trip_mode[1] and
                            point_dict[point_dict.keys()[i]]['prev_stop_mysqlid'] != trip_mode[2] and 
                             point_dict[point_dict.keys()[i]]['prev_stop_mysqlid'] != immed_prev_stop
                            and count_2 <= 30):
                        
                        cursor.execute(sql_phrase, sql_data)
                        sql_catchbasin = cursor.fetchone() #one step earlier immed_prev_stop
                                                           #[0]a.immed_prev_stop, [1]a.dest_route_type, 
                                                           #[2]b.immed_prev_route_type, [3]b.dest_mysqlid, [4]b.total_time, 
                                                           #[5]a.origin_mysqlid
                        
                        cursor.fetchall() # defensive programming
                    
                        if sql_catchbasin != None:
                            if sql_catchbasin[0] != None:
                                immed_prev_stop = sql_catchbasin[0]
                            else:
                                immed_prev_stop = point_dict[point_dict.keys()[i]]['prev_stop_mysqlid']
                            trip_mode = [sql_catchbasin[1], sql_catchbasin[2], sql_catchbasin[3]]
                        else:
                            immed_prev_stop = None
                            
                        sql_data.update({'immed_prev_mysqlid' : immed_prev_stop})
                        count_2 += 1
                    if sql_catchbasin != None:
                        if immed_prev_stop in point_dict:
                            if sql_catchbasin[0] != None:
                                transp_mode_2 = point_dict[immed_prev_stop]['transp_mode']
                            else:
                                transp_mode_2 = transp_mode
                        else:
                            immed_prev_stop = None
                        
                    count += 1
                
                # only trace to first stop on route
                # if the traced-to stop is same type of stop, update dictionary
                
                if immed_prev_stop != None and immed_prev_stop in point_dict:
                        
                    if immed_prev_stop not in prev_stops:
                        
                        prev_stops.update({immed_prev_stop : point_dict.keys()[i]})
                    elif (point_dict[prev_stops[immed_prev_stop]]['transp_mode'] in [None, 3] and 
                            point_dict[point_dict.keys()[i]]['transp_mode'] not in [None, 3]):
                        prev_stops.update({immed_prev_stop : point_dict.keys()[i]})
                            
                    point_dict[point_dict.keys()[i]]['immed_prev_stop'] = immed_prev_stop
                        
            elif point_dict[point_dict.keys()[i]]['route_mysqlid'] not in [0, None]:
                
                immed_prev_stop = point_dict[point_dict.keys()[i]]['prev_stop_mysqlid']
                
            else:  immed_prev_stop = None
            
            if immed_prev_stop != None and immed_prev_stop in point_dict:
                
                higher_comp = max(point_dict[point_dict.keys()[i]]['comp'], point_dict[immed_prev_stop]['comp'])
                
                x_point = round(point_dict[immed_prev_stop]['x_point'],0) 
                y_point = round(point_dict[immed_prev_stop]['y_point'],0)
                
                if math.pow(abs(x_point - x_ctr),3) + math.pow(abs(y_point - y_ctr),3) >= 3:
                    
                    prev_comp = point_dict[immed_prev_stop]['comp']
                    cur_comp = point_dict[point_dict.keys()[i]]['comp']
                
                    if prev_comp < cur_comp:
                        compass_delta = ( cur_comp - prev_comp )
                    elif prev_comp > cur_comp:
                        compass_delta = ( (2 * math.pi) - prev_comp + cur_comp )
                    else:
                        compass_delta = 0
                
                    if compass_delta > math.pi:
                        compass_delta = ( (-2 * math.pi) + compass_delta )
                
                    leng_delta = point_dict[point_dict.keys()[i]]['leng'] - point_dict[immed_prev_stop]['leng']
                
                    comp = point_dict[immed_prev_stop]['comp']
                    leng = point_dict[immed_prev_stop]['leng']
                
                
                    num_segments = int(abs(math.ceil(compass_delta / .0628)))
                
                    line_width = str(5 * (point_dict[point_dict.keys()[i]]['trip_ratio']) + 1) + 'p'
                
                    if num_segments != 0:
                        leng_seg = leng_delta / num_segments
                        comp_seg = compass_delta / num_segments
                
                    
                        for k in range(1, num_segments, 1): 
                
                            x_last = x_point
                            y_last = y_point
                    
                            leng = leng + leng_seg
                            comp = comp + comp_seg
                    
                            x_point = ( math.sin(comp) * leng ) + x_ctr
                            y_point = -1 * ( math.cos(comp) * leng ) + y_ctr
                
                            can.create_line(x_last, y_last, x_point, y_point, 
                                    fill = point_dict[point_dict.keys()[i]]['color'], width = line_width)
                    
                can.create_line(x_point, y_point, point_dict[point_dict.keys()[i]]['x_point'], 
                        point_dict[point_dict.keys()[i]]['y_point'], 
                        fill = point_dict[point_dict.keys()[i]]['color'], width = line_width)
        
        # draw all of the stop points
        # draws on top of the lines
        
        for i in range(0, len(point_dict.keys()), 1):
          for z in range(0, 2, 1):
            color = '#fff'
              
            if z == 0 and point_dict[point_dict.keys()[i]]['transp_mode'] not in [None]:
                color = point_dict[point_dict.keys()[i]]['color']
                trip_ratio = point_dict[point_dict.keys()[i]]['trip_ratio']
                transp_mode = point_dict[point_dict.keys()[i]]['transp_mode']
                route_name = point_dict[point_dict.keys()[i]]['route_name']
                route_mysqlid = point_dict[point_dict.keys()[i]]['route_mysqlid']
                leng = point_dict[point_dict.keys()[i]]['leng']
                
            if z == 1 and point_dict.keys()[i] in prev_stops:
                if (point_dict[point_dict.keys()[i]]['transp_mode'] in [None, 3] and
                        point_dict[prev_stops[point_dict.keys()[i]]]['transp_mode'] not in [None, 3]):
                    color = point_dict[prev_stops[point_dict.keys()[i]]]['color']
                    trip_ratio = point_dict[prev_stops[point_dict.keys()[i]]]['trip_ratio']
                    transp_mode = point_dict[prev_stops[point_dict.keys()[i]]]['transp_mode']
                    route_name = point_dict[prev_stops[point_dict.keys()[i]]]['route_name']
                    route_mysqlid = point_dict[prev_stops[point_dict.keys()[i]]]['route_mysqlid']
                    leng = point_dict[prev_stops[point_dict.keys()[i]]]['leng']
            
            if color != '#fff':
                    
                x1 = point_dict[point_dict.keys()[i]]['x_point'] - 18 * trip_ratio
                x2 = point_dict[point_dict.keys()[i]]['x_point'] + 18 * trip_ratio
                y1 = point_dict[point_dict.keys()[i]]['y_point'] - 18 * trip_ratio
                y2 = point_dict[point_dict.keys()[i]]['y_point'] + 18 * trip_ratio
            
                # draw stop labels, changing the anchor location based on the map sector
            
                if 1==1:
                
                    if point_dict[point_dict.keys()[i]]['y_point'] >= y_ctr:
                        anchor_loc = 'n'
                        y_anchor = y2
                        ln_loc = [7,0]
                        
                    else:
                        anchor_loc = 's'
                        y_anchor = y1
                        ln_loc = [0,-7]
                        
                    if point_dict[point_dict.keys()[i]]['x_point'] >= x_ctr :
                        anchor_loc += 'w'
                    else:
                        anchor_loc += 'e'
                    
                    txt = point_dict[point_dict.keys()[i]]['dest_name']
                
                    # truncates annoying little extras on stop names
                    
                    trunc_loc = txt.find(u' - ')
                    if trunc_loc != -1:
                        txt = txt[:trunc_loc]
                
                    trunc_loc = txt.find(u'Station')
                    if trunc_loc != -1:
                        txt = txt[:trunc_loc]
                
                    # station name and trip time
                    txt = txt + ' (' + str(int(round(point_dict[point_dict.keys()[i]]['total_min'],0))) + '\')'
                    
                    if color.upper() == '#FFFF7C':
                        color_out = '#FCF344'
                    else:
                        color_out = color
                
                    if transp_mode != 3:
                        
                        can.create_text( point_dict[point_dict.keys()[i]]['x_point'], y_anchor, 
                                    text = txt, 
                                    font = ('UnBom', int(round((trip_ratio)) * -10) - 9 ), 
                                    fill = color, anchor = anchor_loc )
                
                    elif route_mysqlid in max_time_route:
                        
                        if leng >= max_time_route[route_mysqlid]['max'] or leng <= max_time_route[route_mysqlid]['min']:
                            font_obj = tkFont.Font(family='UnBom', size=-10)
                            
                            slice_loc = route_name.find(u' ')
                            can.create_text( point_dict[point_dict.keys()[i]]['x_point'], y_anchor + ln_loc[0], 
                                        text = route_name[:slice_loc], 
                                        font = font_obj, 
                                        fill = color_out, anchor = anchor_loc )
                
                            can.create_text( point_dict[point_dict.keys()[i]]['x_point'], y_anchor + ln_loc[1], 
                                        text = route_name[(slice_loc + 1):], 
                                        font = font_obj, 
                                        fill = color_out, anchor = anchor_loc )
                
                if color.upper() == '#FFFF7C':
                    color_out = '#FCF344'
                    color = '#FCF344'
                else:
                    color_out = color
            
                can.create_oval( x1 , y1, x2, y2, fill = color, 
                                outline = color_out )
        
        # center/start circle
        
        can.create_oval(x_ctr -12 , y_ctr - 12, x_ctr + 12, y_ctr + 12, fill='#808080')
        
        can.create_text(24, 48, text = 'Travel times from:', anchor = 'nw', font = ('Segui UI Bold', -24, 'bold'), fill = '#A3A3A3')
        can.create_text(32, 74, text = str(start_name), anchor = 'nw', font = ('Segui UI Bold', int(round(-0.07 * x_dim)), 'bold'), fill = '#A3A3A3')
        can.create_text(24, 130, text = 'Time from origin in minutes.', anchor = 'nw', font = ('Segui UI Bold', -24, 'bold'), fill = '#A3A3A3')
        
        
        can.grid()    
        can.update()
        file_name = str(start_name).lower()
        
        spc_chars = ' \\/()\'\":;&|'
        for qq in range(0, len(spc_chars), 1):
            file_name = file_name.replace(spc_chars[qq], '_')
            
        file_name += "_travel_times"
        ps_path = "../data/ps/"
        png_path = "../data/png/"
        
        can.postscript(file=ps_path + str(file_name) + ".ps", height= str(y_dim) + 'p', width = str(x_dim) + 'p')
        
        cmd = 'convert -density 220 ' + ps_path + file_name + '.ps ' + png_path + file_name + '.png'
        os.system(cmd)
        
        with open(temp_log_path,'a') as __f__:
            __f__.write(u'\n' + unicode(file_name) + u'.png')
        
        can = None
        ln = cursor_high.fetchone()
        
       cursor.close()
       cursor_high.close()
       cnx.close()