Example #1
0
    def draw_planet(self, planet):

        # global main_nav, main_canvas, label, planet_images, main_window

        new_x = self.convert_coordinates_x(planet.loc.x)
        new_y = self.convert_coordinates_y(planet.loc.y)
        name_y = self.convert_coordinates_name(planet.loc.y, planet.loc.size)
        color = self.get_terrain_color(planet.terrain)

        size = planet.loc.size, planet.loc.size
        planet_image = Image.open(self.get_terrain_image(planet.terrain))
        planet_image.thumbnail(size, Image.ANTIALIAS)
        planet_image_res = ImageTk.PhotoImage(planet_image)
        new_planet_image = planet_image_res
        self.planet_images.append(new_planet_image)
        label = Label(self.main_canvas)
        label.config(image=planet_image_res)
        label.config(background='black')
        label.grid()
        label.planet_image_res = planet_image_res  # keep a reference!
        label.place(anchor=CENTER, x=new_x, y=new_y)
        label.bind("<Button-1>", lambda event, arg=planet: self.controller.select_planet(event, arg))

        label_name = Label(self.main_canvas, text=planet.name, fg=self.app.conf.main_text_color, bg='black'
                           , borderwidth=1
                           , highlightthickness=0)
        label_name.place(anchor=CENTER, x=new_x, y=name_y)

        if self.app.conf.debug == 1:
            print "Drawing planet: [", planet.name, ",", new_x, ",", new_y, ",", planet.loc.size, ",", color, "]"
Example #2
0
    def initUI(self):
        self.title("About LimeMicro PLLSim")

        self.rowconfigure(0, pad=10)
        self.rowconfigure(1, pad=1)
        self.rowconfigure(2, pad=1)

        script_dir = os.path.dirname(__file__)

        logo = Image.open(os.path.join(script_dir,
                                       "Figures/LimeMicroLogo.png"))
        logoImg = ImageTk.PhotoImage(logo)

        label1 = Label(self, image=logoImg)

        label1.image = logoImg

        label1.grid(row=0, sticky=W + E)

        string_about = 'Lime Microsystems PLLSim for LMS8001 IC\nVersion 1.0\nThis program comes with absolutely NO warranty'

        label2 = Label(self, text=string_about, justify='center')
        label2.grid(row=1)

        label3 = Label(self,
                       text=r"http://www.limemicro.com",
                       justify='center',
                       foreground='blue',
                       cursor="hand2")
        label3.bind('<Button-1>', self.gotoweb)
        label3.grid(row=2)
Example #3
0
 def initUI(self):
     #top frame using all the remaining space
     innerTopFrame = Frame(self, background="black")
     innerTopFrame.pack(fill=BOTH, expand=1)
     #CLOSE Label
     innerBottomLeftFrame = Frame(self, background="black")
     innerBottomLeftFrame.place(x=0, width=self.wRoot/2, 
         y=self.hRoot-200, height=200)
     closeLabel = Label(innerBottomLeftFrame, bg="black", fg="black",
         text="CLOSE", font=("Comic Sans MS", 48, "bold"))
     innerBottomLeftFrame.bind("<Enter>", lambda f: closeLabel.config(fg="white"))
     innerBottomLeftFrame.bind("<Leave>", lambda f: closeLabel.config(fg="black"))
     innerBottomLeftFrame.bind("<Button-1>", lambda f: self.root.quit())
     closeLabel.bind("<Button-1>", lambda f: self.root.quit())
     closeLabel.pack(fill=BOTH)
     #SHUT DOWN Label
     innerBottomRightFrame = Frame(self, background="black")
     innerBottomRightFrame.place(x=self.wRoot/2, width=self.wRoot/2, 
         y=self.hRoot-200, height=200)
     shutdownLabel = Label(innerBottomRightFrame, bg="black", fg="black",
         text="SHUT DOWN", font=("Comic Sans MS", 48, "bold"))
     innerBottomRightFrame.bind("<Enter>", lambda f: shutdownLabel.config(fg="white"))
     innerBottomRightFrame.bind("<Leave>", lambda f: shutdownLabel.config(fg="black"))
     innerBottomRightFrame.bind("<Button-1>", self.shutdown)
     shutdownLabel.bind("<Button-1>", self.shutdown)
     shutdownLabel.pack(fill=BOTH)
     #design the FullScreenApp
     self.pack(fill=BOTH, expand=1)
Example #4
0
 def makeDice(self, container):
   for row in range (0, WORDS):
     for column in range (0, DICE):
       label = Label(container, text = ' ', borderwidth = 1, relief = 'solid')
       label.grid(row = row, column = column)
       label.bind("<Button-1>", self.makeClick(row, column))
       self.switch.add(row, column, Connect(label))
Example #5
0
class MyFirstGUI:
    LABEL_TEXT = [
        "This is our first GUI!",
        "Actually, this is our second GUI.",
        "We made it more interesting...",
        "...by making this label interactive.",
        "Go on, click on it again.",
    ]

    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label_index = 0
        self.label_text = StringVar()
        self.label_text.set(self.LABEL_TEXT[self.label_index])
        self.label = Label(master, textvariable=self.label_text)
        self.label.bind("<Button-1>", self.cycle_label_text)
        self.label.pack()

        self.greet_button = Button(master, text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()

    def greet(self):
        print("Greetings!")

    def cycle_label_text(self, event):
        self.label_index += 1
        self.label_index %= len(self.LABEL_TEXT)  # wrap around
        self.label_text.set(self.LABEL_TEXT[self.label_index])
Example #6
0
    def setup(self):
        self.isOver = False
        self.player1.resetPlayer()
        self.player2.resetPlayer()
		#setup ocean and link left mouse button (button-1) to callback function
        for i in range(10):
            for j in range(10):
                x = Label(self, relief=RAISED, width=4, height=2)
                x.bind("<Button-1>", lambda event, arg=(i,j): self.callback(event, arg))
                x.grid(row=i, column=j)
				#initialize cell with isShip=isHit=false and label	
                cell = Cell(False, False, x)
                self.player2.addCellToOcean(cell, i)

        Label(self, text="Attack here!").grid(column=4, row=11, columnspan=3)
		#init section between oceans
        for i in range(10):
            x = Label(self, width=2, height=2, background="black")
            x.grid(column=10, row=i)
		#init computers attack ocean
        for i in range(10):
            for j in range(11,21):
                x = Label(self, relief=RAISED, width=4, height=2)
                x.grid(row=i, column=j)
                cell = Cell(False, False, x)
                self.player1.addCellToOcean(cell, i)

        self.player1.setUpShips()
        self.player2.setUpShips()
Example #7
0
      def insert_img(self, filename, frame, pic_path, label):
        clear_frame(frame)
        sizeY = frame.winfo_height()
        sizeX = frame.winfo_width()
        img = Image.open(filename)
        img = img.resize((sizeY, sizeX), Image.ANTIALIAS)
        # Subtract 8 for various borders in the frame.
        img = img.resize((sizeX-8, sizeY-8), Image.ANTIALIAS)
        img = ImageTk.PhotoImage(img)
        # The image is wrapped with a label to make it easier to place.
        lbl1 = Label(frame, image=img)

        #  Closure function for callback. This function will save the captured
        #   image of this specific panel, adding it to the model of the 
        #   person associated with the face being clicked on
        def save_image(event):
          global comparison_directory
          folder = "../face_comparison/%s/%s" %(comparison_directory,label)
          os.system("ls " + folder + " | wc -l > output.txt")
          f = open("output.txt", 'r')
          file_number = str(int(f.readline().rstrip().lstrip()) + 1)
          command = "cp " + pic_path + " " + folder + "/" +  file_number + ".jpg"
          add_face(pic_path, label)
          info_box['text'] = "Saved %s to %s" % (pic_path, folder)
          print command
          os.system(command)

        lbl1.image = img
        lbl1.bind('<Button-1>', save_image)
        lbl1.place(x=frame.winfo_x(), y=frame.winfo_y())
class MyFirstGUI:
    LABEL_TEXT = [
         "Esta es la segunda interfaz gráfica de usuario.",
         "Hemos hecho que sea más interesante ...",
         "... Al hacer esta etiqueta interactiva.",
         "Adelante, haz clic en él de nuevo.",
    ]
    def __init__(self, master):
        self.master = master
        master.title("Una simple GUI")

        self.label_index = 0
        self.label_text = StringVar()
        self.label_text.set(self.LABEL_TEXT[self.label_index])
        self.label = Label(master, textvariable=self.label_text)
        self.label.bind("<Button-1>", self.cycle_label_text)
        self.label.pack()

        self.greet_button = Button(master, text="Saluda", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, text="Cierra", command=master.quit)
        self.close_button.pack()

    def greet(self):
        print("¡Saludos pythoneros!")

    def cycle_label_text(self, event):
        self.label_index += 1
        self.label_index %= len(self.LABEL_TEXT) # encierra alrededor
        self.label_text.set(self.LABEL_TEXT[self.label_index])
Example #9
0
class MyFirstGUI:
    LABEL_TEXT = [
        "This is our first GUI!",
        "Actually, this is our second GUI.",
        "We made it more interesting...",
        "...by making this label interactive.",
        "Go on, click on it again.",
    ]

    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")
        # from here you can select te Label text
        self.label_index = 4
        self.label_text = StringVar()
        self.label_text.set(self.LABEL_TEXT[self.label_index])
        self.label = Label(master, textvariable=self.label_text)
        self.label.bind("<Button-1>", self.cycle_label_text)
        self.label.pack()

        self.greet_button = Button(master, text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()

    def greet(self):
        print("Greetings!")

    def cycle_label_text(self, event):
        self.label_index += 1
        self.label_index %= len(self.LABEL_TEXT)  # wrap around
        self.label_text.set(self.LABEL_TEXT[self.label_index])
Example #10
0
 def create_key(self, img, key):
     key_image = PhotoImage(file=img)
     label = Label(self, image=key_image, bd=0)
     label.image = key_image
     label.place(x=key[0], y=0)
     label.name = key[1]
     label.bind('<Button-1>', self.button_pressed)
     return label
Example #11
0
 def create_key(self, img, key):
     key_image = PhotoImage(file=img)
     label = Label(self, image=key_image, bd=0)
     label.image = key_image
     label.place(x=key[0], y=0)
     label.name = key[1]
     label.bind('<Button-1>', button_pressed)
     label.bind('<ButtonRelease-1>', label_released)
     return label
    def __init__(self, root):

        self.canvas = Canvas(root, width = 400, height = 350)
        self.canvas.configure(cursor="crosshair")
        self.canvas.pack(expand=YES, fill=BOTH, side='right')

        self.canvas.bind("<Key>", self.handle_key)
        self.canvas.bind("<Double-Button-1>", self.set_focus)
        self.canvas.bind("<Button-1>", self.set_cursor)
        self.canvas.bind("<Return>", self.remove_highlight)

        self.image, self.ponto1, self.ponto2 = (None, None, None)

        self.menubar = Menu(root)

        filemenu = Menu(self.menubar, tearoff=0)
        filemenu.add_command(label="Open Image", command=self.openImage)
        filemenu.add_command(label="Save", command=self.hello)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=root.quit)
        self.menubar.add_cascade(label="File", menu=filemenu)

        editmenu = Menu(self.menubar, tearoff=0)
        for e in ("Cut","Copy","Paste"):
            editmenu.add_command(label=e, command=self.hello)

        self.menubar.add_cascade(label="Edit", menu=editmenu)

        filtermenu = Menu(self.menubar, tearoff=0)
        filtermenu.add_command(label="Threshold", command=self.thresholdFilter)
        self.menubar.add_cascade(label="Filter", menu=filtermenu)

        reportmenu = Menu(self.menubar, tearoff=0)
        reportmenu.add_command(label="Relatorio.txt",
        command=self.generateReport)
        reportmenu.add_command(label="Relatorio.pdf")
        reportmenu.add_command(label="Email")
        self.menubar.add_cascade(label="Report", menu=reportmenu)

        helpmenu = Menu(self.menubar, tearoff=0)
        helpmenu.add_command(label="About", command=self.hello)
        self.menubar.add_cascade(label="Help", menu=helpmenu)

        root.config(menu=self.menubar)

        self.toolbar = Frame(root)
        self.toolbar.pack(side='left', fill='both')
        clean = Label(self.toolbar, text='Clean')
        clean.bind("<Button-1>", self.clean)
        b = Label(self.toolbar, text='B')
        c = Label(self.toolbar, text='C')
        d = Label(self.toolbar, text='D')

        for w in (clean,b,c,d):
            w.configure(relief="groove", font="Times 12 bold")
            w.pack(fill='both')
    def __init__(self, platform, gradient, *args, **kwargs):
        self.gradient = gradient
        self.step_size = 3
        self.gradient_type = ['linear', 'radial', 'square']
        self.current_fill = 0
        self.grads = []
        self.platform = platform
        if self.platform == 'Pythonista':
            ui.View.__init__(self, *args, **kwargs)
            self.next_button = ui.Button(frame= \
            (330, 360, 30, 60), title = 'Next')
            self.next_button.background_color = (0.4, 0.4, 0.4)
            self.next_button.action = self.next_fill
            self.next_button.height = 30
            self.next_button.width = 60
            self.next_button.tint_color = 'white'
            self.next_button.font = ('<system>', 12)
            self.add_subview(self.next_button)

        elif self.platform == 'Kivy':
            from kivy.uix.floatlayout import FloatLayout
            from kivy.uix.button import Button
            self.root = FloatLayout()
            self.frame = kwargs['frame']
            self.next_button = Button(text='NEXT',
                                      size_hint_y=None,
                                      size_hint_x=None,
                                      height=30,
                                      width=60,
                                      font_size=12,
                                      pos=(330, 10),
                                      on_press=self.next_fill)
            self.root.add_widget(self.next_button)

        elif self.platform == 'Tk':
            from Tkinter import Tk
            from Tkinter import Canvas
            from Tkinter import Frame
            from Tkinter import Label
            from Tkinter import NW
            self.master = Tk()
            self.root = Canvas(self.master, width=kwargs['frame'][2], \
            height=kwargs['frame'][3])
            self.root.pack()
            self.frame = kwargs['frame']
            contour = Frame(self.master, height=30, width=60)
            contour.pack_propagate(0)  # don't shrink
            label = Label(contour, text='NEXT', fg='white', bg='#585858', \
            height=30, width=60)
            label.bind("<Button-1>", self.tk_button_down)
            label.bind("<ButtonRelease-1>", self.tk_button_up)

            label.pack()
            label.config(font=('TkDefaultFont', 12), padx=0, pady=0)
            contour.place(x=330, y=360, anchor=NW)
Example #14
0
    def capture(self, map):
	self.map = map
        box_size = 15
	print map
        # create a new frame
        wrap = Frame(self, bg="black")

        self.hide_top()
        # label showing the image
        self.image = Image.open(self.path + "/" + map + ".gif")
        draw = ImageDraw.Draw(self.image) 
        
        for x in range(1, 240//box_size):
	        draw.line((box_size*x, 0, box_size*x, 240), fill=128, width=1)
        for y in range(1, 240//box_size):
	        draw.line((0, box_size*y, 240, box_size*y), fill=128, width=1)
        
        
        self.image = ImageTk.PhotoImage(self.image)
        imagelabel = Label(wrap, image=self.image)
        imagelabel.grid(row=0, column=0, columnspan=2, sticky=C.W + C.E + C.N + C.S)


        imagelabel.bind('<Button-1>', self.printcoords)

   
        # when there were previous frames, hide the top one and add a back button for the new one
        if len(self.framestack):
            self.hide_top()

            back = FlatButton(
                wrap,
                text='Back…',
                image=self.get_icon("arrow.left"),
                command= self.go_back,
            )

            exitbtn = FlatButton(
                wrap,
                text='Exit…',
                image=self.get_icon("exit"),
                command=self.app_exit,
            )

            back.set_color("#00a300")  # green
            exitbtn.set_color("#00a300")  # green

            back.grid(row=1, column=0, padx=1, pady=1, sticky=C.W + C.E + C.N + C.S)
            exitbtn.grid(row=1, column=1, padx=1, pady=1, sticky=C.W + C.E + C.N + C.S)
            #num += 1

        # add the new frame to the stack and display it
            self.framestack.append(wrap)
        self.show_top()
        self.parent.update()
Example #15
0
    def about_window(self):
        """
        Window showing information about the software and
        version number, including auto-update. If the application
        is run from a container, then auto-update is disabled
        """

        def callback(event):
            """
            open webbrowser when clicking links
            """
            webbrowser.open_new(event.widget.cget("text"))

        # main window
        t = Toplevel(self.master, width=500, height=500)
        t.wm_title("About")

        # NIC logo + name
        title = Label(t,
                      text="nicMSlesions v" + self.version + "\n"
                      "Multiple Sclerosis White Matter Lesion Segmentation")
        title.grid(row=2, column=1, padx=20, pady=10)
        img = ImageTk.PhotoImage(Image.open('./logonic.png'))
        imglabel = Label(t, image=img)
        imglabel.image = img
        imglabel.grid(row=1, column=1, padx=10, pady=10)
        group_name = Label(t,
                           text="Copyright Sergi Valverde (2018-) \n " +
                           "NeuroImage Computing Group")
        group_name.grid(row=3, column=1)
        group_link = Label(t, text=r"http://atc.udg.edu/nic",
                           fg="blue",
                           cursor="hand2")
        group_link.grid(row=4, column=1)
        group_link.bind("<Button-1>", callback)

        license_content = "Licensed under the BSD 2-Clause license. \n" + \
                          "A copy of the license is present in the root directory."

        license_label = Label(t, text=license_content)
        license_label.grid(row=5, column=1, padx=20, pady=20)

        if self.container is False:
            # check version and updates
            version_number = Label(t, text="commit: " + self.commit_version)
            version_number.grid(row=6, column=1, padx=20, pady=(1, 1))

            self.check_link = Button(t,
                                text="Check for updates",
                                command=self.check_update)
            self.check_link.grid(row=7, column=1)
Example #16
0
class PlaceItem(Frame):
    def __init__(self, master, item=PLACE_HOME, **kw):
        apply(Frame.__init__, (self, master), kw)
        self.item = item
        self['borderwidth'] = 3
        self['relief'] = 'flat'
        self.bg_color = self['background']
        self.bind('<Button-1>', self.callback)
        self.bind('<Enter>', self.mouse_enter)
        self.bind('<Leave>', self.mouse_leave)

        self.icon = Label(self, image=PLACES_DICT[item][0])
        self.icon.pack(side=LEFT)
        self.icon.bind('<Button-1>', self.callback)
        self.icon.bind('<Enter>', self.mouse_enter)
        self.icon.bind('<Leave>', self.mouse_leave)

        self.text = Label(self, text=PLACES_DICT[item][1])
        self.text.pack(side=LEFT, padx=5)
        self.text.bind('<Button-1>', self.callback)
        self.text.bind('<Enter>', self.mouse_enter)
        self.text.bind('<Leave>', self.mouse_leave)

    def callback(self, *args):
        print PLACES_DICT[self.item][2]

    def mouse_enter(self, *args):
        self['background'] = 'gray'
        self.text['background'] = 'gray'
        self.icon['background'] = 'gray'

    def mouse_leave(self, *args):
        self['background'] = self.bg_color
        self.text['background'] = self.bg_color
        self.icon['background'] = self.bg_color
Example #17
0
 def createNodeBindings( self ):
     "Create a set of bindings for nodes."
     bindings = {
         '<ButtonPress-1>': self.clickNode,
         '<B1-Motion>': self.dragNode,
         '<ButtonRelease-1>': self.releaseNode,
         '<Enter>': self.enterNode,
         '<Leave>': self.leaveNode,
         '<Double-ButtonPress-1>': self.xterm
     }
     l = Label()  # lightweight-ish owner for bindings
     for event, binding in bindings.items():
         l.bind( event, binding )
     return l
Example #18
0
 def createNodeBindings( self ):
     "Create a set of bindings for nodes."
     bindings = {
         '<ButtonPress-1>': self.clickNode,
         '<B1-Motion>': self.dragNode,
         '<ButtonRelease-1>': self.releaseNode,
         '<Enter>': self.enterNode,
         '<Leave>': self.leaveNode,
         '<Double-ButtonPress-1>': self.xterm
     }
     l = Label()  # lightweight-ish owner for bindings
     for event, binding in bindings.items():
         l.bind( event, binding )
     return l
Example #19
0
def main(interval):
    root = Tk()
    root.geometry('{0}x{1}+0+0'.format(root.winfo_screenwidth(),
                                       root.winfo_screenheight()))

    label_var = StringVar()
    label = Label(root, textvariable=label_var, font='-size 100 -weight bold')
    label.pack(fill=BOTH, expand=1)

    time_var = StringVar()
    time = Label(root, textvariable=time_var, font='-size 70 -weight bold')
    time.pack(fill=X)

    def next_instruction(event=None):
        color, text = instruction()
        label_var.set(text)
        label.config(fg=color)
        Popen(['say', '--voice', SAY_VOICE, text])

    def make_count_step(time_s):
        def step():
            time_var.set(time_s if time_s > 0 else '')

        return step

    def countdown(min, max):
        for n in range(min, max + 1):
            root.after(1000 * n, make_count_step(max - n))

    def step():
        next_instruction()
        countdown(1, interval)
        root.after(interval * 1000, step)

    def loop_instructions():
        countdown(0, 5)
        root.after(5000, step)

    def quit(event):
        root.quit()

    label.bind('<space>', next_instruction)
    label.bind('<Escape>', quit)
    label.focus_set()

    loop_instructions()
    root.mainloop()
Example #20
0
File: UI.py Project: Alovez/Pyste
 def render_rows(self, table='default'):
     rows = self.pm.get_value(table)
     for k, item in rows.iteritems():
         label = Label(self.canvas,
                       text=item,
                       height=10,
                       width=50,
                       wraplength=400,
                       justify='left')
         label.bind(
             "<Button-1>",
             lambda e, item=item, label=label: self.paste(item, label))
         label.bind("<Enter>", lambda e, label=label: self.on_enter(label))
         label.bind("<Leave>", lambda e, label=label: self.on_leave(label))
         label.pack()
     self.scrollbar.config(command=self.canvas.yview)
     self.canvas.pack()
Example #21
0
def ask_captcha(fname='./tmp.jpg'):
    def on_click(event):
        global val
        if event.num== 1:
            cx, cy = (event.x, event.y)
            for y in xrange(3):
                for x in xrange(4):
                    if ((x*65+30-cx)**2+(y*65+30-cy)**2)**0.5< 25:
                        val = x+4*y+1
                        root.destroy()
    root = Tk()
    image = PhotoImage(file=fname)
    lbl = Label(root, image=image)
    lbl.bind("<Button-1>", on_click)
    lbl.pack()
    root.title(u"点击头向下的鱼")
    root.mainloop()
    return val
Example #22
0
    def __init__(self, master, options, width=20, bordercolor="#cccccc", foreground="black", background="white", activebackground="#2780E3", activeforeground="white",padx=15, pady=7, command=None):
        Frame.__init__(self, master, background=background, highlightbackground=bordercolor, highlightcolor=bordercolor, highlightthickness=1, bd= 0)

        self._foreground = foreground
        self._background = background
        self._activebackground = activebackground
        self._activeforeground = activeforeground

        self._items = []
        
        index = 0
        for option in options:
            
            if option is None:
                Separator(self, orient=HORIZONTAL).pack(fill=X)
                continue
                
            if isinstance(option, basestring):
                test = option
                value = option
            else:
                text, value = option
            
            label_item = Label(self, width=width, text=text, background=background, foreground="black",  anchor=W, padx=padx, pady=pady)
            label_item.pack(fill=X)
            
            label_item.index = index
            label_item.value = value

            label_item.bind("<Enter>", self._on_enter_label_item)
            label_item.bind("<Leave>", self._on_leave_label_item)
            label_item.bind("<1>", lambda event, index=index:self._on_click_item(event.widget, index))
            self._items.append(label_item)
            
            index += 1
        
        self._actived_item = None
        self._command = command

        self.bind("<Up>", self._on_up)
        self.bind("<Down>", self._on_down)
        self.bind("<Return>", self._on_return)
Example #23
0
    def draw_planet_highlighted(self, planet):

        # global main_nav, main_canvas, label, planet_images, main_window

        new_x = self.convert_coordinates_x(planet.loc.x)
        new_y = self.convert_coordinates_y(planet.loc.y)
        name_y = self.convert_coordinates_name(planet.loc.y, planet.loc.size)
        color = self.get_terrain_color(planet.terrain)

        size = planet.loc.size, planet.loc.size
        planet_image = Image.open(self.get_terrain_image(planet.terrain))
        planet_image.thumbnail(size, Image.ANTIALIAS)
        planet_image_res = ImageTk.PhotoImage(planet_image)
        new_planet_image = planet_image_res
        self.planet_images.append(new_planet_image)
        label_planet = Label(self.main_canvas)
        label_planet.config(image=planet_image_res)
        label_planet.config(background='black')
        label_planet.planet_image_res = planet_image_res  # keep a reference!
        label_planet.place(anchor=CENTER, x=new_x, y=new_y)
        label_planet.bind("<Button-1>", lambda event, arg=planet: self.controller.select_planet(event, arg))
        label_name = Label(self.main_canvas, text=planet.name, fg='red', bg='black', borderwidth=1
                           , highlightthickness=0)
        label_name.place(anchor=CENTER, x=new_x, y=name_y)

        if self.app.conf.debug == 1:
            print "Drawing planet: [", planet.name, ",", new_x, ",", new_y, ",", planet.loc.size, ",", color, "]"

        # get nearest planet and draw a line
        if self.has_selected:
            nearest_planet = self.get_nearest_planet(planet)
            l = self.get_line_points((planet.loc.x, planet.loc.y)
                                     , (nearest_planet.loc.x, nearest_planet.loc.y)
                                     , planet.loc.size
                                     , nearest_planet.loc.size)
            self.main_canvas.create_line(l.x1, l.y1, l.x2, l.y2, fill='blue', dash=(4, 4))
            self.main_canvas.pack()
            self.app.debug(("Drawing line:", l.x1, ',', l.y1, ',', l.x2, ',', l.y2))
        else:
            self.app.debug("Line next time")
            self.has_selected = True
Example #24
0
    def append_chords(self, chords=[]):
        '''pass a [list] of Chords to the Accordion object'''

        self.update_idletasks()
        row = 0
        width = max([c.winfo_reqwidth() for c in chords])
        
        for c in chords:
            i = PhotoImage() # blank image to force Label to use pixel size
            label = Label(self, text=c.title,
                          image=i,
                          compound='center',
                          width=width,
                          bg=self.style['title_bg'],
                          fg=self.style['title_fg'],
                          bd=2, relief='groove')
            
            label.grid(row=row, column=0)
            c.grid(row=row+1, column=0, sticky='nsew')
            c.grid_remove()
            row += 2
            
            label.bind('<Button-1>', lambda e,
                       c=c: self._click_handler(c))
            label.bind('<Enter>', lambda e,
                       label=label, i=i: label.config(bg=self.style['highlight']))
            label.bind('<Leave>', lambda e,
                       label=label, i=i: label.config(bg=self.style['title_bg']))
Example #25
0
class MemoCaras(Frame):

    def __init__(self, root):
        Frame.__init__(self, root)
        self.grid(column=0, row=0)
        self.canvas = Canvas(self, width=604, height=480)
        self.canvas.grid(column=0, row=0, columnspan=2)
        self.bt_prox = Button(self, text='Próximo', command=self.proximo)
        self.bt_prox.grid(column=0, row=1, sticky=W)
        self.nome = Label(self, text='(passe aqui para ver o nome)')
        self.nome.bind('<Enter>', self.mostra_nome)
        self.nome.bind('<Leave>', self.esconde_nome)
        self.nome.grid(column=1, row=1, sticky=EW)
        self.foto = PhotoImage(file=NOME_ARQ_FOTO)
        self.canvas.create_image(0, 0, image=self.foto, anchor=NW)
        self.caras = {}
        for nome, bbox in pessoas:
            marca = self.canvas.create_oval(*bbox, outline='green', width=5,
                                    state=HIDDEN)
            self.caras[nome] = marca
        self.sequencia = []
        self.cara_ativa = None

    def proximo(self):
        if self.cara_ativa is not None:
            marca = self.caras[self.cara_ativa]
            self.canvas.itemconfigure(marca, state=HIDDEN)
        if len(self.sequencia) == 0:
            self.sequencia = self.caras.keys()
            shuffle(self.sequencia)
        self.cara_ativa = self.sequencia.pop()
        marca = self.caras[self.cara_ativa]
        self.canvas.itemconfigure(marca, state=NORMAL)

    def mostra_nome(self, evento):
        self.texto_nome = self.nome['text']
        self.nome['text'] = self.cara_ativa

    def esconde_nome(self, evento):
        self.nome['text'] = self.texto_nome
Example #26
0
    def new_label(self):
        # Creating a new row header
        
        self._number_of_labels += 1

        frame_button = Frame(self._frame_of_row_numbers, height=self._row_height)
        frame_button.pack()
        frame_button.pack_propagate(False)
        
        row_label = Label(frame_button, text =self._number_of_labels, **self._labelrow_kwargs)
        row_label.bind("<1>", lambda event, index=self._number_of_labels-1: self._on_click_label(index))
        
        if self._hover_background:
            row_label.bind("<Enter>", lambda event, row_label=row_label: row_label.configure(background=self._hover_background))
            row_label.bind("<Leave>", lambda event, row_label=row_label: row_label.configure(background=self.cget("background")))

        row_label.pack(expand=True, fill=BOTH)
        
        width_of_row_numbers= max(row_label.winfo_reqwidth(), self._row_minwidth)
        
        if width_of_row_numbers > self._width_of_row_numbers:
            self._width_of_row_numbers = width_of_row_numbers
            
            for slave in self._frame_of_row_numbers.pack_slaves():
                slave.configure(width=width_of_row_numbers)
        else:
            frame_button.configure(width=width_of_row_numbers)

        frame_button.update_idletasks()

        self.config(width=self._frame_of_row_numbers.winfo_reqwidth())
        self.config(scrollregion=(0, 0, self._frame_of_row_numbers.winfo_reqwidth(), self._number_of_labels*self._row_height))
Example #27
0
    def append_chords(self, chords=[]):
        '''pass a [list] of Chords to the Accordion object'''

        self.update_idletasks()
        row = 0
        width = max([c.winfo_reqwidth() for c in chords])

        for c in chords:
            i = PhotoImage()  # blank image to force Label to use pixel size
            label = Label(self,
                          text=c.title,
                          image=i,
                          compound='center',
                          width=width,
                          bg=self.style['title_bg'],
                          fg=self.style['title_fg'],
                          bd=2,
                          relief='groove')

            label.grid(row=row, column=0)
            c.grid(row=row + 1, column=0, sticky='nsew')
            c.grid_remove()
            row += 2

            label.bind('<Button-1>', lambda e, c=c: self._click_handler(c))
            label.bind('<Enter>',
                       lambda e, label=label, i=i: label.config(bg=self.style[
                           'highlight']))
            label.bind('<Leave>',
                       lambda e, label=label, i=i: label.config(bg=self.style[
                           'title_bg']))
Example #28
0
    def new_label(self):
        # Creating a new row header
        
        self._number_of_labels += 1

        frame_button = Frame(self._frame_of_row_numbers, height=self._row_height)
        frame_button.pack()
        frame_button.pack_propagate(False)
        
        row_label = Label(frame_button, text =self._number_of_labels, **self._labelrow_kwargs)
        row_label.bind("<1>", lambda event, index=self._number_of_labels-1: self._on_click_label(index))
        
        if self._hover_background:
            row_label.bind("<Enter>", lambda event, row_label=row_label: row_label.configure(background=self._hover_background))
            row_label.bind("<Leave>", lambda event, row_label=row_label: row_label.configure(background=self.cget("background")))

        row_label.pack(expand=True, fill=BOTH)
        
        width_of_row_numbers= max(row_label.winfo_reqwidth(), self._row_minwidth)
        
        if width_of_row_numbers > self._width_of_row_numbers:
            self._width_of_row_numbers = width_of_row_numbers
            
            for slave in self._frame_of_row_numbers.pack_slaves():
                slave.configure(width=width_of_row_numbers)
        else:
            frame_button.configure(width=width_of_row_numbers)

        frame_button.update_idletasks()

        self.config(width=self._frame_of_row_numbers.winfo_reqwidth())
        self.config(scrollregion=(0, 0, self._frame_of_row_numbers.winfo_reqwidth(), self._number_of_labels*self._row_height))
Example #29
0
 def __init__(self, parent, title, tcmd):
     self.remove = parent.rproject   #Remove function
     self.move = parent.move         #Move function
     self.nc = parent.nc
     self.title = title
     self.tcmd = tcmd #passed in from timehandler
     self.lock = 0
     self.going = parent.going
     self.stopped = parent.stopped
     self.pdate = None
     self.f = Frame(parent.f, relief=RAISED, borderwidth=2)
     f2 = Frame(self.f)
     f2.pack()
     l = Label(f2, text=title, width=42, font=("Helvetica", 16))
     l.pack(side=LEFT)
     l.bind("<Button-1>", self._click)
     self.b = Button(f2, image=self.stopped, command=self._timer)
     self.b.pack(side=LEFT)
     Button(f2, text='X', command=self.close).pack(side=LEFT)
     self.prev()
     self.entry = Text(self.f1, width=80, height=10, bg='white', wrap=WORD)
     self.entry.bind("<Shift-Key-Return>", self.commit_note)
     self.entry.bind("<Control-Key-Return>", self.p.gui_refresh)
     self.f.pack()
Example #30
0
 def __init__(self, parent, title, tcmd):
     self.remove = parent.rproject  #Remove function
     self.move = parent.move  #Move function
     self.nc = parent.nc
     self.title = title
     self.tcmd = tcmd  #passed in from timehandler
     self.lock = 0
     self.going = parent.going
     self.stopped = parent.stopped
     self.pdate = None
     self.f = Frame(parent.f, relief=RAISED, borderwidth=2)
     f2 = Frame(self.f)
     f2.pack()
     l = Label(f2, text=title, width=42, font=("Helvetica", 16))
     l.pack(side=LEFT)
     l.bind("<Button-1>", self._click)
     self.b = Button(f2, image=self.stopped, command=self._timer)
     self.b.pack(side=LEFT)
     Button(f2, text='X', command=self.close).pack(side=LEFT)
     self.prev()
     self.entry = Text(self.f1, width=80, height=10, bg='white', wrap=WORD)
     self.entry.bind("<Shift-Key-Return>", self.commit_note)
     self.entry.bind("<Control-Key-Return>", self.p.gui_refresh)
     self.f.pack()
Example #31
0
class PlaceItem(Frame):

	def __init__(self, master, item=PLACE_HOME, **kw):
		apply(Frame.__init__, (self, master), kw)
		self.item = item
		self['borderwidth'] = 3
		self['relief'] = 'flat'
		self.bg_color = self['background']
		self.bind('<Button-1>', self.callback)
		self.bind('<Enter>', self.mouse_enter)
		self.bind('<Leave>', self.mouse_leave)

		self.icon = Label(self, image=PLACES_DICT[item][0])
		self.icon.pack(side=LEFT)
		self.icon.bind('<Button-1>', self.callback)
		self.icon.bind('<Enter>', self.mouse_enter)
		self.icon.bind('<Leave>', self.mouse_leave)

		self.text = Label(self, text=PLACES_DICT[item][1])
		self.text.pack(side=LEFT, padx=5)
		self.text.bind('<Button-1>', self.callback)
		self.text.bind('<Enter>', self.mouse_enter)
		self.text.bind('<Leave>', self.mouse_leave)

	def callback(self, *args):
		print PLACES_DICT[self.item][2]

	def mouse_enter(self, *args):
		self['background'] = 'gray'
		self.text['background'] = 'gray'
		self.icon['background'] = 'gray'

	def mouse_leave(self, *args):
		self['background'] = self.bg_color
		self.text['background'] = self.bg_color
		self.icon['background'] = self.bg_color
Example #32
0
class CollapsibleFrame(Frame):
    def __init__(self,
                 master,
                 text=None,
                 borderwidth=2,
                 width=0,
                 height=16,
                 interior_padx=0,
                 interior_pady=8,
                 background=None,
                 caption_separation=4,
                 caption_font=None,
                 caption_builder=None,
                 icon_x=5):
        Frame.__init__(self, master)
        if background is None:
            background = self.cget("background")

        self.configure(background=background)

        self._is_opened = False

        self._interior_padx = interior_padx
        self._interior_pady = interior_pady

        self._iconOpen = PhotoImage(
            data=
            "R0lGODlhEAAQAKIAAP///9TQyICAgEBAQAAAAAAAAAAAAAAAACwAAAAAEAAQAAADNhi63BMgyinFAy0HC3Xj2EJoIEOM32WeaSeeqFK+say+2azUi+5ttx/QJeQIjshkcsBsOp/MBAA7"
        )
        self._iconClose = PhotoImage(
            data=
            "R0lGODlhEAAQAKIAAP///9TQyICAgEBAQAAAAAAAAAAAAAAAACwAAAAAEAAQAAADMxi63BMgyinFAy0HC3XjmLeA4ngpRKoSZoeuDLmo38mwtVvKu93rIo5gSCwWB8ikcolMAAA7"
        )

        height_of_icon = max(self._iconOpen.height(), self._iconClose.height())
        width_of_icon = max(self._iconOpen.width(), self._iconClose.width())

        containerFrame_pady = (height_of_icon // 2) + 1

        self._height = height
        self._width = width

        self._containerFrame = Frame(self,
                                     borderwidth=borderwidth,
                                     width=width,
                                     height=height,
                                     relief=RIDGE,
                                     background=background)
        self._containerFrame.pack(expand=True,
                                  fill=X,
                                  pady=(containerFrame_pady, 0))

        self.interior = Frame(self._containerFrame, background=background)

        self._collapseButton = Label(self,
                                     borderwidth=0,
                                     image=self._iconOpen,
                                     relief=RAISED)
        self._collapseButton.place(in_=self._containerFrame,
                                   x=icon_x,
                                   y=-(height_of_icon // 2),
                                   anchor=N + W,
                                   bordermode="ignore")
        self._collapseButton.bind("<Button-1>", lambda event: self.toggle())

        if caption_builder is None:
            self._captionLabel = Label(self,
                                       anchor=W,
                                       borderwidth=1,
                                       text=text)
            if caption_font is not None:
                self._captionLabel.configure(font=caption_font)
        else:
            self._captionLabel = caption_builder(self)

            if not isinstance(self._captionLabel, Widget):
                raise Exception(
                    "'caption_builder' doesn't return a tkinter widget")

        self.after(
            0, lambda: self._place_caption(caption_separation, icon_x,
                                           width_of_icon))

    def update_width(self, width=None):
        # Update could be devil
        # http://wiki.tcl.tk/1255
        self.after(0, lambda width=width: self._update_width(width))

    def _place_caption(self, caption_separation, icon_x, width_of_icon):
        self.update()
        x = caption_separation + icon_x + width_of_icon
        y = -(self._captionLabel.winfo_reqheight() // 2)

        self._captionLabel.place(in_=self._containerFrame,
                                 x=x,
                                 y=y,
                                 anchor=N + W,
                                 bordermode="ignore")

    def _update_width(self, width):
        self.update()
        if width is None:
            width = self.interior.winfo_reqwidth()

        if isinstance(self._interior_pady, (list, tuple)):
            width += self._interior_pady[0] + self._interior_pady[1]
        else:
            width += 2 * self._interior_pady

        width = max(self._width, width)

        self._containerFrame.configure(width=width)

    def open(self):
        self._collapseButton.configure(image=self._iconClose)

        self._containerFrame.configure(height=self.interior.winfo_reqheight())
        self.interior.pack(expand=True,
                           fill=X,
                           padx=self._interior_padx,
                           pady=self._interior_pady)

        self._is_opened = True

    def close(self):
        self.interior.pack_forget()
        self._containerFrame.configure(height=self._height)
        self._collapseButton.configure(image=self._iconOpen)

        self._is_opened = False

    def toggle(self):
        if self._is_opened:
            self.close()
        else:
            self.open()
Example #33
0
class ListEditor(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        border_width = 1
        border_style = SUNKEN
        background_colour = "#FFFFFF"
        default_height = 600

        nav_frame = Frame(
            self, height=default_height, width=200, bd=border_width, relief=border_style, bg=background_colour
        )

        content_frame = Frame(self, height=default_height, width=804, bd=border_width, relief=border_style)
        content_frame.parent = parent

        nav_frame.grid(column=0, row=0)
        content_frame.grid(column=1, row=0)
        nav_frame.grid_propagate(0)
        content_frame.pack_propagate(0)

        # Create fonts for navLabels
        fontMouseOver = tkFont.Font(family="Helvetica", size=14, underline=True)
        fontMouseOut = tkFont.Font(family="Helvetica", size=14, underline=False)

        # Creating Navigation Labels
        self.lNavStudentRecords = Label(
            nav_frame,
            text="Student Records",
            bg="white",
            font=fontMouseOut,
            bd=border_width,
            relief=border_style,
            width=20,
        )
        self.lNavViewLists = Label(
            nav_frame,
            text="View Word Lists",
            bg="white",
            font=fontMouseOut,
            bd=border_width,
            relief=border_style,
            width=20,
        )

        self.lNavCreateLists = Label(
            nav_frame,
            text="Create Word Lists",
            bg="white",
            font=fontMouseOut,
            bd=border_width,
            relief=border_style,
            width=20,
        )

        buttonBack = Button(nav_frame, text="Back", command=self.parent.new_list)

        # Binding Mouse events to the Labels
        # Mouse Clicks
        self.lNavViewLists.bind("<Button-1>", partial(self.switch_frame, 2))
        self.lNavCreateLists.bind("<Button-1>", partial(self.switch_frame, 1))
        self.lNavStudentRecords.bind("<Button-1>", partial(self.switch_frame, 3))
        # Mouse Movements
        self.lNavViewLists.bind("<Enter>", lambda (event): self.lNavViewLists.configure(font=fontMouseOver))
        self.lNavCreateLists.bind("<Enter>", lambda (event): self.lNavCreateLists.configure(font=fontMouseOver))
        self.lNavViewLists.bind("<Leave>", lambda (event): self.lNavViewLists.configure(font=fontMouseOut))
        self.lNavCreateLists.bind("<Leave>", lambda (event): self.lNavCreateLists.configure(font=fontMouseOut))
        self.lNavStudentRecords.bind("<Enter>", lambda (event): self.lNavStudentRecords.configure(font=fontMouseOver))
        self.lNavStudentRecords.bind("<Leave>", lambda (event): self.lNavStudentRecords.configure(font=fontMouseOut))
        # Gridding the labels
        # self.lNavStudentRecords.grid(column=0, row=0)
        self.lNavViewLists.grid(column=0, row=1)
        self.lNavCreateLists.grid(column=0, row=2)
        buttonBack.grid(column=0, row=3)

        # Creating the two views we have so far
        self.viewcreate = CreateView(content_frame, default_height, 800, border_style, border_width, background_colour)

        self.viewlists = ListView(content_frame, default_height, 800, border_style, border_width, background_colour)
        self.viewlists.pack()

    def switch_frame(self, frameNumber, event):
        if frameNumber == 1:
            self.viewlists.pack_forget()
            self.viewcreate.pack()
            self.lNavViewLists.configure(bg="white", fg="black")
            self.lNavCreateLists.configure(bg="#DDDDDD", fg="#8800AA")
            self.lNavStudentRecords.configure(bg="white", fg="black")
            self.viewcreate.update_category()
        elif frameNumber == 2:
            self.viewcreate.pack_forget()
            self.viewlists.pack()
            self.lNavCreateLists.configure(bg="white", fg="black")
            self.lNavViewLists.configure(bg="#DDDDDD", fg="#8800AA")
            self.lNavStudentRecords.configure(bg="white", fg="black")
            self.viewlists.update()
        else:
            self.viewcreate.pack_forget()
            self.viewlists.pack_forget()
            self.lNavCreateLists.configure(bg="white", fg="black")
            self.lNavViewLists.configure(bg="white", fg="black")
            self.lNavStudentRecords.configure(bg="#DDDDDD", fg="#8800AA")
class Arc:
    def __init__(self, from_pt=(100, 50), to_pt=(150, 100), text=None,
                 color=arc_color, from_node=None, to_node=None):
        self.from_pt = from_pt
        self.to_pt = to_pt
        # the actual nodes this arc connects
        self.from_node = from_node
        self.to_node = to_node
        # identify arc that is loop on single node
        self.is_loop = self.to_node.name == self.from_node.name
        
        # arc stuff
        mid = midpt(from_pt, to_pt)
        self.arc_points = [from_pt, mid, to_pt]
        self.color = color
        self.line_width = 4
        self.arrowshape = (20, 20, 10) # default (8, 10, 3)
        
        self.text = text
        self.font = ('arial', 12)
        self.arc_id = None
        self.text_id = None
        self.text_label = None
        self.text_label_pos = None
        self.text_label_size = None
        self.last_mouse = None
        self.is_selected = False
        self.canvas = None
        
    def length(self):
        """Returns distance between from_pt and to_pt.
        """
        return dist(self.from_pt, self.to_pt)
        
    def clear(self, canvas=None):
        """Clear graphics state and text, remove nodes.
        """
        if not canvas is None:
            if self.arc_id: canvas.delete(self.arc_id)
            if self.text_id: 
                canvas.delete(self.text_id)
                canvas.delete(self.text_label)
                
        self.text = None
        self.from_node = self.to_node = None
        
        
    def draw(self, canvas):
        """Draws arc and text on canvas, if previously drawn,
        deletes first.
        """
        if self.arc_id: canvas.delete(self.arc_id)
        if self.text_id: 
            canvas.delete(self.text_id)
            canvas.delete(self.text_label)
        
        # if its a loop, handle differently
        # use node size as a general metric
        loop_diam = GuiStateMachine.node_diameter
        if self.is_loop:
            # start with point on edge of node (midpt of whatever side of bounding box)
            # put midpoint in direction radiating from center of circle
            start_pt = self.arc_points[0]
            radial = Vec2.from_points(self.from_node.center(), start_pt).unit_vec()
            mid = Vec2(start_pt) + radial * loop_diam
            # now add 2 out to the sides to make a loop
            orthog = Vec2(-radial.y, radial.x) * (loop_diam * .5)
            halfpt = Vec2(start_pt) + radial * (loop_diam * .5)
            pt2 = halfpt + orthog
            pt1 = halfpt - orthog
            self.arc_points = [start_pt, pt1.tuple(), mid.tuple(), pt2.tuple(), start_pt]
            labelx, labely = mid.tuple()
            
#            print "orthog: %s, halfpt: %s" % (str(orthog), str(halfpt))
#            print "len(self.arc_points):", len(self.arc_points)
#            x,y = halfpt
#            canvas.create_oval(x, y, x+20, y+20, fill='purple')
#            for x,y in self.arc_points:
#                print "x, y: %d, %d" % (x, y)
#                canvas.create_oval(x, y, x+20, y+20, fill='red')
#            return

        else:            
            mid = midpt(self.from_pt, self.to_pt)
    #        print "from_pt: %s, to_pt: %s, midpt: %s" % (str(self.from_pt), str(self.to_pt), str(mid))
            labelx, labely = mid
            
        self.arc_id = canvas.create_line(self.arc_points, fill=self.color, smooth=1,
                               arrow='last', arrowshape=self.arrowshape, width=self.line_width)
        self.text_label = Label(canvas, text=self.text, font=self.font, 
                                fg=arc_label_fg, bg=arc_label_bg, #canvas['bg'],
                                padx=10, pady=10, borderwidth=1, relief='solid')
        self.text_label.pack()
        self.text_label.bind('<ButtonPress-1>', self.on_left_click)
        self.text_label.bind('<B1-Motion>', self.on_left_drag)
        
        self.text_id = canvas.create_window(labelx, labely, window=self.text_label)
        self.text_label_pos = (labelx, labely)
        self.canvas = canvas


    def on_left_click(self, event):
        """Handle left click on arc's text label.
        """
#        print 'left click: X=%s Y=%s' % (event.x, event.y)
        self.last_mouse = (event.x, event.y)
        self.is_selected = True
        
            
    def on_left_drag(self, event):
        """Handle left click and drag on canvas.
        """
#        print 'left drag: X=%s Y=%s' % (event.x, event.y)
        pt = (event.x, event.y)
        if self.is_selected:
            (offx, offy) = (pt[0]-self.last_mouse[0], pt[1]-self.last_mouse[1])
#            print "moving: (offx, offy) = %s" % str((offx, offy))
            self.move(self.canvas, offx, offy)
        
            
    def move(self, canvas=None, dx=0, dy=0):
        """Move this arc by dx and dy.  Moves on canvas if canvas is passed.
        Moving the arc consists of moving the text label, then reshaping the
        arc accordingly.
        """
        self.text_label_pos = (self.text_label_pos[0] + dx, self.text_label_pos[1] + dy)
        # for a 3 point line: move the center of the arc with the label
        if not self.is_loop:
            self.arc_points[1] = (self.arc_points[1][0] + dx,
                                  self.arc_points[1][1] + dy)
        # loop has 5 points
        else:
            for i in [1, 3]:
                # note that adjustment is the same, I'm keeping this here
                # though, in case it turns out to need tweaking again
                self.arc_points[i] = (self.arc_points[i][0] + dx,
                                      self.arc_points[i][1] + dy)
            self.arc_points[2] = (self.arc_points[2][0] + dx,
                                  self.arc_points[2][1] + dy)
        if canvas:
            canvas.move(self.text_id, dx, dy)
            if self.arc_id:
                canvas.delete(self.arc_id)
                self.arc_id = canvas.create_line(self.arc_points, fill=self.color, smooth=1,
                               arrow='last', arrowshape=self.arrowshape, width=self.line_width)
    
    def add_transition_string(self, s):
        """Adds transition string to label text as new line.
        """
        if self.text is None: self.text = ""
        numlines = len(self.text.splitlines())
        if numlines == 0:
            self.text += s
        else:
            self.text += "\n" + s
        
    def text_size(self):
        """Returns (w, h) of current text according to current font.
        """
        f = Font(family=self.font[0], size=self.font[1])
        # total height of line, I believe
        h = f.metrics('linespace')
#        print "all metrics:"
#        m = f.metrics()
#        for k in m:
#            print "%s: %s" % (k, str(m[k]))
        lines = self.text.splitlines()
        num_lines = len(lines)
        # max line width
        w = max( [f.measure(line) for line in lines] )
        h = num_lines * h
        
        return (w, h)        
        
    def __str__(self):
        """String rep without geometric stuff.
        """
        fn = "None" if self.from_node is None else self.from_node.name
        tn = "None" if self.to_node is None else self.to_node.name
        t = "" if self.text is None else "%s\n" % self.text
        s = "%s -> %s\n%s" % (fn, tn, t)
        return s
Example #35
0
class TreeNode:
    def __init__(self, canvas, parent, item, menuList=[]):
        self.canvas = canvas
        self.parent = parent
        self.item = item
        self.state = 'collapsed'
        self.selected = 0
        self.children = {}
        self.kidKeys = []
        self.x = self.y = None
        self.iconimages = {}  # cache of PhotoImage instances for icons
        self.menuList = menuList
        self.menuVar = IntVar()
        self.menuVar.set(0)
        self._popupMenu = None
        self.image_id = None
        if self.menuList:
            if self.menuList[-1] == 'Separator':
                self.menuList = self.menuList[:-1]
            self._popupMenu = Menu(self.canvas, tearoff=0)
            for i in range(len(self.menuList)):
                item = self.menuList[i]
                if item == 'Separator':
                    self._popupMenu.add_separator()
                else:
                    self._popupMenu.add_radiobutton(
                        label=item,
                        variable=self.menuVar,
                        value=i,
                        indicatoron=0,
                        command=self.popupMenuCommand)

    def destroy(self):
        for key in self.kidKeys:
            c = self.children[key]
            del self.children[key]
            c.destroy()
        self.parent = None

    def geticonimage(self, name):
        try:
            return self.iconimages[name]
        except KeyError:
            pass
        file, ext = os.path.splitext(name)
        ext = ext or ".gif"
        fullname = os.path.join(ICONDIR, file + ext)
        image = PhotoImage(master=self.canvas, file=fullname)
        self.iconimages[name] = image
        return image

    def select(self, event=None):
        if self.selected:
            return
        self.deselectall()
        self.selected = 1
        if self.parent != None:
            if self.parent.state == 'expanded':
                self.canvas.delete(self.image_id)
                self.drawicon()
                self.drawtext()
        self.item.OnSelect(event)

    def deselect(self, event=None):
        if not self.selected:
            return
        self.selected = 0
        if self.parent != None:
            if self.parent.state == 'expanded':
                self.canvas.delete(self.image_id)
                self.drawicon()
                self.drawtext()

    def deselectall(self):
        if self.parent:
            self.parent.deselectall()
        else:
            self.deselecttree()

    def deselecttree(self):
        if self.selected:
            self.deselect()
        for key in self.kidKeys:
            child = self.children[key]
            child.deselecttree()

    def flip(self, event=None):
        if self.state == 'expanded':
            self.collapse()
        else:
            self.expand()
        self.item.OnDoubleClick()
        return "break"

    def popupMenu(self, event=None):
        if self._popupMenu:
            self._popupMenu.post(event.widget.winfo_pointerx(),
                                 event.widget.winfo_pointery())
            return "break"

    def popupMenuCommand(self):
        command = self.menuList[self.menuVar.get()]
        self.item.MenuCommand(command)
        if self.parent and (command != 'Update Explorer'):
            # Update parent to try to keep explorer up to date
            self.parent.update()

    def expand(self, event=None):
        if not self.item.IsExpandable():
            return
        if self.state != 'expanded':
            self.state = 'expanded'
            self.update()
            self.view()

    def collapse(self, event=None):
        if self.state != 'collapsed':
            self.state = 'collapsed'
            self.update()

    def view(self):
        top = self.y - 2
        bottom = self.lastvisiblechild().y + 17
        height = bottom - top
        visible_top = self.canvas.canvasy(0)
        visible_height = self.canvas.winfo_height()
        visible_bottom = self.canvas.canvasy(visible_height)
        if visible_top <= top and bottom <= visible_bottom:
            return
        x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
        if top >= visible_top and height <= visible_height:
            fraction = top + height - visible_height
        else:
            fraction = top
        fraction = float(fraction) / y1
        self.canvas.yview_moveto(fraction)

    def reveal(self):
        # Make sure all parent nodes are marked as expanded
        parent = self.parent
        while parent:
            if parent.state == 'collapsed':
                parent.state = 'expanded'
                parent = parent.parent
            else:
                break
        # Redraw tree accordingly
        self.update()
        # Bring this item into view
        self.view()

    def lastvisiblechild(self):
        if self.kidKeys and self.state == 'expanded':
            return self.children[self.kidKeys[-1]].lastvisiblechild()
        else:
            return self

    def update(self):
        if self.parent:
            self.parent.update()
        else:
            oldcursor = self.canvas['cursor']
            self.canvas['cursor'] = "watch"
            self.canvas.update()
            self.canvas.delete(Tkinter.ALL)  # XXX could be more subtle
            self.draw(7, 2)
            x0, y0, x1, y1 = self.canvas.bbox(Tkinter.ALL)
            self.canvas.configure(scrollregion=(0, 0, x1, y1))
            self.canvas['cursor'] = oldcursor

    def draw(self, x, y):
        # XXX This hard-codes too many geometry constants!
        self.x, self.y = x, y
        self.drawicon()
        self.drawtext()
        if self.state != 'expanded':
            return y + 17
        # draw children
        sublist = self.item._GetSubList()
        if not sublist:
            # IsExpandable() was mistaken; that's allowed
            return y + 17
        self.kidKeys = []
        for item in sublist:
            key = item.GetKey()
            if self.children.has_key(key):
                child = self.children[key]
            else:
                child = TreeNode(self.canvas, self, item, self.menuList)
            self.children[key] = child
            self.kidKeys.append(key)
        # Remove unused children
        for key in self.children.keys():
            if key not in self.kidKeys:
                del (self.children[key])
        cx = x + 20
        cy = y + 17
        cylast = 0
        for key in self.kidKeys:
            child = self.children[key]
            cylast = cy
            self.canvas.create_line(x + 9, cy + 7, cx, cy + 7, fill="gray50")
            cy = child.draw(cx, cy)
            if child.item.IsExpandable():
                if child.state == 'expanded':
                    iconname = "minusnode"
                    callback = child.collapse
                else:
                    iconname = "plusnode"
                    callback = child.expand
                image = self.geticonimage(iconname)
                id = self.canvas.create_image(x + 9, cylast + 7, image=image)
                # XXX This leaks bindings until canvas is deleted:
                self.canvas.tag_bind(id, "<1>", callback)
                self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
        id = self.canvas.create_line(
            x + 9,
            y + 10,
            x + 9,
            cylast + 7,
            ##stipple="gray50",     # XXX Seems broken in Tk 8.0.x
            fill="gray50")
        self.canvas.tag_lower(id)  # XXX .lower(id) before Python 1.5.2
        return cy

    def drawicon(self):
        if self.selected:
            imagename = (self.item.GetSelectedIconName()
                         or self.item.GetIconName() or "openfolder")
        else:
            imagename = self.item.GetIconName() or "folder"
        image = self.geticonimage(imagename)
        id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)
        self.image_id = id
        self.canvas.tag_bind(id, "<1>", self.select)
        self.canvas.tag_bind(id, "<Double-1>", self.flip)
        self.canvas.tag_bind(id, "<3>", self.popupMenu)

    def drawtext(self, text=None):
        textx = self.x + 20 - 1
        texty = self.y - 1
        labeltext = self.item.GetLabelText()
        if labeltext:
            id = self.canvas.create_text(textx,
                                         texty,
                                         anchor="nw",
                                         text=labeltext)
            self.canvas.tag_bind(id, "<1>", self.select)
            self.canvas.tag_bind(id, "<Double-1>", self.flip)
            x0, y0, x1, y1 = self.canvas.bbox(id)
            textx = max(x1, 200) + 10
        if text == None:
            text = self.item.GetText() or "<no text>"
        try:
            self.entry
        except AttributeError:
            pass
        else:
            self.edit_finish()
        try:
            label = self.label
        except AttributeError:
            # padding carefully selected (on Windows) to match Entry widget:
            self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2)
        if self.selected:
            self.label.configure(fg="white", bg="darkblue")
        else:
            fg = self.item.GetTextFg()
            self.label.configure(fg=fg, bg="white")
        id = self.canvas.create_window(textx,
                                       texty,
                                       anchor="nw",
                                       window=self.label)
        self.label.bind("<1>", self.select_or_edit)
        self.label.bind("<Double-1>", self.flip)
        self.label.bind("<3>", self.popupMenu)
        # Update text if necessary
        if text != self.label['text']:
            self.label['text'] = text
        self.text_id = id

    def select_or_edit(self, event=None):
        if self.selected and self.item.IsEditable():
            text = self.item.GetTextForEdit()
            self.label['text'] = text
            self.drawtext(text)
            self.edit(event)
        else:
            self.select(event)

    def edit(self, event=None):
        self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
        self.entry.insert(0, self.label['text'])
        self.entry.selection_range(0, Tkinter.END)
        self.entry.pack(ipadx=5)
        self.entry.focus_set()
        self.entry.bind("<Return>", self.edit_finish)
        self.entry.bind("<Escape>", self.edit_cancel)

    def edit_finish(self, event=None):
        try:
            entry = self.entry
            del self.entry
        except AttributeError:
            return
        text = entry.get()
        entry.destroy()
        if text and text != self.item.GetText():
            self.item.SetText(text)
        text = self.item.GetText()
        self.label['text'] = text
        self.drawtext()
        self.canvas.focus_set()

    def edit_cancel(self, event=None):
        self.drawtext()
        self.canvas.focus_set()

    def find(self, searchKey):
        # Search for a node who's key matches the given key
        # Is it this node
        if searchKey == self.item.GetKey():
            return self
        # Nope, check the children
        sublist = self.item._GetSubList()
        for item in sublist:
            key = item.GetKey()
            # Use existing child or create new TreeNode if none exists
            if self.children.has_key(key):
                child = self.children[key]
            else:
                child = TreeNode(self.canvas, self, item, self.menuList)
                # Update local list of children and keys
                self.children[key] = child
                self.kidKeys.append(key)
            # See if node is child (or one of child's descendants)
            retVal = child.find(searchKey)
            if retVal:
                return retVal
        # Not here
        return None
Example #36
0
class DesktopNote(DraggableWindow):
    BG_NOTE = '#ffff7d'
    FILETYPES = [('Text/ASCII', '*.txt'), ('All files', '*')]

    def __init__(self,
                 master,
                 title='Without title',
                 min_width=110,
                 min_height=40):
        DraggableWindow.__init__(self, master)

        self.wm_attributes('-topmost', True)
        self.overrideredirect(True)

        self.filename = ''

        self.close_IMG = PhotoImage(
            data=
            "R0lGODlhEAAQAPAAAAQEBAAAACH5BAEAAAEALAAAAAAQABAAAAImDI6ZFu3/DpxO0mlvBLFX7oEfJo5QZlZNaZTupp2shsY13So6VwAAOw=="
        )
        self.minimize_IMG = PhotoImage(
            data=
            "R0lGODlhEAAQAPAAAAQEBAAAACH5BAEAAAEALAAAAAAQABAAAAIiDI6ZFu3/DpxO0mlvBBrmbnBg83Wldl6ZgoljSsFYqNRcAQA7"
        )
        self.restore_IMG = PhotoImage(
            data=
            "R0lGODlhEAAQAPcAAAAAAAQEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAAQABAAAAhFAP8FGEiwYEGB/xIqXLhwIMOHCh02NBgxAEODFhNKjNiwYsWDGQWGxIhQ48iJI09ynLhS48WUB1lCfLhxpkebHTHqtBgQADs="
        )
        self.minimizeAtRightSide_IMG = PhotoImage(
            data=
            "R0lGODlhEAAQAPcAAAAAAAQEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAAQABAAAAg+AP8FGEiwYEGB/xIqXLhwIMOHCh1CfChxosSKEC8GmJhQI0eBG0F+9MiRpMWQGCmiDPmxI8uWKUuCNEhzY0AAOw=="
        )

        frameNote = Frame(self,
                          bg=self.BG_NOTE,
                          bd=1,
                          highlightbackground='black',
                          highlightcolor='black',
                          highlightthickness=1)
        frameNote.pack()

        self.mimizedNote = Label(frameNote,
                                 text=title,
                                 bg=self.BG_NOTE,
                                 wraplength=1)
        self.mimizedNote.bind('<Button-1>',
                              lambda event: self.maximize_from_right_side())

        self.maximizedNote = Frame(frameNote)
        self.maximizedNote.pack()

        Header = Frame(self.maximizedNote, bg=self.BG_NOTE)
        Header.pack(fill=X)

        ttk.Separator(self.maximizedNote, orient=HORIZONTAL).pack(expand=True,
                                                                  fill=X)

        titleLabel = Label(Header, text=title, bg=self.BG_NOTE)
        titleLabel.pack(side=LEFT)

        Button(Header,
               compound=TOP,
               image=self.close_IMG,
               bg=self.BG_NOTE,
               activebackground=self.BG_NOTE,
               command=self.destroy).pack(side=RIGHT)

        self.iconifyButton = Button(Header,
                                    image=self.minimize_IMG,
                                    command=self.minimize,
                                    bg=self.BG_NOTE,
                                    activebackground=self.BG_NOTE)
        self.iconifyButton.pack(side=RIGHT)

        Button(Header,
               compound=TOP,
               image=self.minimizeAtRightSide_IMG,
               bg=self.BG_NOTE,
               activebackground=self.BG_NOTE,
               command=self.minimize_at_right_side).pack(side=RIGHT)

        self.text_box = AutoResizedText(self.maximizedNote,
                                        bd=0,
                                        bg=self.BG_NOTE,
                                        width=min_width,
                                        height=min_height)
        self.text_box.pack(expand=YES, fill=BOTH)

        self.text_box.bind('<Control-n>',
                           lambda event: self.ask_title_and_create_window())
        self.text_box.bind('<Control-N>',
                           lambda event: self.ask_title_and_create_window())
        self.text_box.bind('<Control-o>', lambda event: self.open_file())
        self.text_box.bind('<Control-O>', lambda event: self.open_file())
        self.text_box.bind('<Control-s>', lambda event: self.save_file())
        self.text_box.bind('<Control-S>', lambda event: self.save_file())
        self.text_box.bind('<Control-a>', lambda event: self.save_file_as())
        self.text_box.bind('<Control-A>', lambda event: self.save_file_as())
        self.text_box.bind('<Control-h>', lambda event: self.help())
        self.text_box.bind('<Control-H>', lambda event: self.help())

    def save_file(self, whatever=None):
        if not self.filename:
            self.save_file_as()
        else:
            with open(self.filename, 'w') as f:
                f.write(self.text_box.get('1.0', 'end'))

            # Comment out the following 2 lines if you don't want a
            # pop-up message every time you save a file:
            tkMessageBox.showinfo('FYI', 'File Saved.')
            self.after(1, self.text_box.focus)
        return "break"

    def save_file_as(self, change_title=False):
        self.filename = tkFileDialog.asksaveasfilename(
            filetypes=self.FILETYPES)

        if self.filename:
            with open(self.filename, 'w') as f:
                f.write(self.text_box.get('1.0', 'end'))

            if change_title:
                self.title(self.filename)
            # comment out the following line if you don't want a
            # pop-up message every time you save a file:
            tkMessageBox.showinfo('FYI', 'File Saved')

        self.after(1, self.text_box.focus)
        return "break"

    def open_file(self, filename=None, change_title=False):
        if not filename:
            self.filename = tkFileDialog.askopenfilename(
                filetypes=self.FILETYPES)
        else:
            self.filename = filename

        if not self.filename:
            with open(self.filename, 'r') as f:
                self.text_box.update(f.read())

            if change_title:
                self.title('File %s' % self.filename)

        self.after(1, self.text_box.focus)
        return "break"

    def ask_title_and_create_window(self):
        toplevel = Toplevel()

        label = Label(toplevel, text="Title:")
        label.pack(anchor=W)

        entry = Entry(toplevel, width=15)
        entry.pack(anchor=W, fill=X)

        entry.bind(
            "<Return>", lambda event:
            (self.new_window(entry.get()), toplevel.destroy()))

        entry.focus()

        return "break"

    @classmethod
    def new_window(class_, title):
        desktop_note = class_(root, title)
        desktop_note.text_box.focus()

    def help(self):
        tkMessageBox.showinfo('Tkinter Desktop Notes Help',
                              message=HELP_MESSAGE)
        self.after(1, self.text_box.focus)
        return "break"

    def minimize_at_right_side(self):
        self.disable_dragging()
        self.maximizedNote.pack_forget()
        self.mimizedNote.pack()

        self.x = self.winfo_x()
        self.y = self.winfo_y()

        self.wm_geometry('-0+%d' % self.y)

    def maximize_from_right_side(self):
        self.maximizedNote.pack()
        self.mimizedNote.pack_forget()
        self.wm_geometry('+%d+%d' % (self.x, self.y))
        self.enable_dragging()

    def minimize(self):
        self.text_box.pack_forget()
        self.iconifyButton['command'] = self.maximize
        self.iconifyButton['image'] = self.restore_IMG

    def maximize(self):
        self.text_box.pack(expand=YES, fill=BOTH)
        self.iconifyButton['command'] = self.minimize
        self.iconifyButton['image'] = self.minimize_IMG
Example #37
0
    def __init__(self, master, columns, column_weights=None, cnf={}, **kw):
        """
        Construct a new multi-column listbox widget.

        :param master: The widget that should contain the new
            multi-column listbox.
            
        :param columns: Specifies what columns should be included in
            the new multi-column listbox.  If ``columns`` is an integer,
            the it is the number of columns to include.  If it is
            a list, then its length indicates the number of columns
            to include; and each element of the list will be used as
            a label for the corresponding column.

        :param cnf, kw: Configuration parameters for this widget.
            Use ``label_*`` to configure all labels; and ``listbox_*``
            to configure all listboxes.  E.g.:

                >>> mlb = MultiListbox(master, 5, label_foreground='red')
        """
        # If columns was specified as an int, convert it to a list.
        if isinstance(columns, int):
            columns = range(columns)
            include_labels = False
        else:
            include_labels = True

        if len(columns) == 0:
            raise ValueError("Expected at least one column")

        # Instance variables
        self._column_names = tuple(columns)
        self._listboxes = []
        self._labels = []

        # Pick a default value for column_weights, if none was specified.
        if column_weights is None:
            column_weights = [1] * len(columns)
        elif len(column_weights) != len(columns):
            raise ValueError('Expected one column_weight for each column')
        self._column_weights = column_weights

        # Configure our widgets.
        Frame.__init__(self, master, **self.FRAME_CONFIG)
        self.grid_rowconfigure(1, weight=1)
        for i, label in enumerate(self._column_names):
            self.grid_columnconfigure(i, weight=column_weights[i])

            # Create a label for the column
            if include_labels:
                l = Label(self, text=label, **self.LABEL_CONFIG)
                self._labels.append(l)
                l.grid(column=i, row=0, sticky='news', padx=0, pady=0)
                l.column_index = i

            # Create a listbox for the column
            lb = Listbox(self, **self.LISTBOX_CONFIG)
            self._listboxes.append(lb)
            lb.grid(column=i, row=1, sticky='news', padx=0, pady=0)
            lb.column_index = i

            # Clicking or dragging selects:
            lb.bind('<Button-1>', self._select)
            lb.bind('<B1-Motion>', self._select)
            # Scroll whell scrolls:
            lb.bind('<Button-4>', lambda e: self._scroll(-1))
            lb.bind('<Button-5>', lambda e: self._scroll(+1))
            lb.bind('<MouseWheel>', lambda e: self._scroll(e.delta))
            # Button 2 can be used to scan:
            lb.bind('<Button-2>', lambda e: self.scan_mark(e.x, e.y))
            lb.bind('<B2-Motion>', lambda e: self.scan_dragto(e.x, e.y))
            # Dragging outside the window has no effect (diable
            # the default listbox behavior, which scrolls):
            lb.bind('<B1-Leave>', lambda e: 'break')
            # Columns can be resized by dragging them:
            l.bind('<Button-1>', self._resize_column)

        # Columns can be resized by dragging them.  (This binding is
        # used if they click on the grid between columns:)
        self.bind('<Button-1>', self._resize_column)

        # Set up key bindings for the widget:
        self.bind('<Up>', lambda e: self.select(delta=-1))
        self.bind('<Down>', lambda e: self.select(delta=1))
        self.bind('<Prior>', lambda e: self.select(delta=-self._pagesize()))
        self.bind('<Next>', lambda e: self.select(delta=self._pagesize()))

        # Configuration customizations
        self.configure(cnf, **kw)
Example #38
0
    def _set_up_gui(self):

        """Sets up the Tkinter user interface."""

        # Disable pylint warning for instance attributes defined outside
        # __init__(), since this method is called by __init__()
        #
        # pylint: disable=W0201

        self.root = Tk()
        self.root.title('Video Poker')

        # Set up menubar

        self.menubar = Menu(self.root)

        self.gamemenu = Menu(self.menubar, tearoff=0)
        self.gamemenu.add_command(label="Quit", command=sys.exit)
        self.menubar.add_cascade(label="Game", menu=self.gamemenu)

        self.helpmenu = Menu(self.menubar, tearoff=0)
        self.helpmenu.add_command(label="About", command=self.help_about)
        self.menubar.add_cascade(label="Help", menu=self.helpmenu)

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

        # Set up card images

        self.backimg = PhotoImage(file="{0}b.gif".format(self.gifdir))

        for num in range(5):
            lbl = Label(self.root, image=self.backimg)
            lbl.grid(row=0, column=num, padx=10, pady=10)
            lbl.bind("<Button-1>", self.flip)
            lbl.flipped = True
            lbl.pos = str(num + 1)
            self.cardimg.append(lbl)

        # Set up labels, fields and buttons

        self.pot_lbl = Label(self.root, text="Pot:")
        self.pot_lbl.grid(row=1, column=0,
                          padx=10, pady=2, sticky=W)

        self.pot_amt_lbl = Label(self.root, text="")
        self.pot_amt_lbl.grid(row=1, column=1, columnspan=2,
                              padx=10, pady=2, sticky=W)
        self._update_pot()

        self.bet_lbl = Label(self.root, text="Bet ($):")
        self.bet_lbl.grid(row=2, column=0,
                          padx=10, pady=2, sticky=W)

        self.bet_str = StringVar()
        self.bet_str.set(str(self.defaultbet))

        self.bet_amt_fld = Entry(self.root, textvariable=self.bet_str)
        self.bet_amt_fld.grid(row=2, column=1, columnspan=2,
                              padx=10, pady=2, sticky=W)

        self.button = Button(self.root, text="Deal",
                             command=self.button_clicked)
        self.button.grid(row=1, column=3, rowspan=2, columnspan=2,
                         sticky=W + E + S + N, padx=10)

        self.status_lbl = Label(self.root, bd=1, relief=SUNKEN,
                                text="Welcome to the casino! " +
                                     "Click 'Deal' to play!")
        self.status_lbl.grid(row=3, column=0, columnspan=5,
                             padx=10, pady=10, ipadx=10, ipady=10,
                             sticky=W + E + S + N)

        # Show winnings table

        lbl = Label(self.root, text="Winnings Table", relief=RAISED)
        lbl.grid(row=4, column=1, columnspan=3,
                 pady=15, ipadx=10, ipady=10, sticky=W + E)

        # Two different tables, one for easy mode, one for normal
        # mode, so be prepared to show either one.

        wte = {2500: "Royal Flush", 250: "Straight Flush",
               100: "Four of a Kind", 50: "Full House", 20: "Flush",
               15: "Straight", 4: "Three of a Kind", 3: "Two Pair",
               2: "Jacks or Higher"}
        wtn = {800: "Royal Flush", 50: "Straight Flush", 25: "Four of a Kind",
               9: "Full House", 6: "Flush", 4: "Straight",
               3: "Three of a Kind", 2: "Two Pair", 1: "Jacks or Higher"}
        wtxt = wte if self.game_easy else wtn

        row = 5
        for key in sorted(wtxt.keys(), reverse=True):
            lbl = Label(self.root, text=wtxt[key])
            lbl.grid(row=row, column=1, columnspan=2, sticky=W)
            lbl = Label(self.root, text="{0} : 1".format(key))
            lbl.grid(row=row, column=3, sticky=E)
            row += 1

        lbl = Label(self.root, text="")
        lbl.grid(row=row, column=0, columnspan=5, pady=15)
Example #39
0
    def __init__(self,
                 master,
                 options,
                 width=20,
                 bordercolor="#cccccc",
                 foreground="black",
                 background="white",
                 activebackground="#2780E3",
                 activeforeground="white",
                 padx=15,
                 pady=7,
                 command=None):
        Frame.__init__(self,
                       master,
                       background=background,
                       highlightbackground=bordercolor,
                       highlightcolor=bordercolor,
                       highlightthickness=1,
                       bd=0)

        self._foreground = foreground
        self._background = background
        self._activebackground = activebackground
        self._activeforeground = activeforeground

        self._items = []

        index = 0
        for option in options:

            if option is None:
                Separator(self, orient=HORIZONTAL).pack(fill=X)
                continue

            if isinstance(option, basestring):
                test = option
                value = option
            else:
                text, value = option

            label_item = Label(self,
                               width=width,
                               text=text,
                               background=background,
                               foreground="black",
                               anchor=W,
                               padx=padx,
                               pady=pady)
            label_item.pack(fill=X)

            label_item.index = index
            label_item.value = value

            label_item.bind("<Enter>", self._on_enter_label_item)
            label_item.bind("<Leave>", self._on_leave_label_item)
            label_item.bind("<1>",
                            lambda event, index=index: self._on_click_item(
                                event.widget, index))
            self._items.append(label_item)

            index += 1

        self._actived_item = None
        self._command = command

        self.bind("<Up>", self._on_up)
        self.bind("<Down>", self._on_down)
        self.bind("<Return>", self._on_return)
Example #40
0
enteredText = StringVar()
enteredText.set("")
enteredText.trace("w", match_entry)

# set up the entry box for the user to enter text (using the enteredText string variable)
matchThis = Entry(root, textvariable=enteredText, justify=RIGHT)
matchThis.grid(row=0, column=1)

# set up the result string variable and the label that holds it
result = []
for i in range(3):
    result.append(StringVar())
    result[i].set("")
    label = Label(root, textvariable=result[i])
    label.grid(row=1, column=i)
    label.bind("<Button-1>", lambda e, j=i: insert_text(j))

# the n-gram size options (choice of n-1) this allows you to choose how many words the dict is keyed on
sizeOptions = [1, 2, 3, 4, 5]

# set up the int variable that holds the size of n-1, and set its default value to the first option in sizeOptions
size = IntVar()
size.set(sizeOptions[0])
# set a trace on this variable that calls load_n_gram_dict on any change
size.trace("w", load_n_gram_dict)

# directory which contain texts
textDirectory = "text_sources"

# get files in directory for options
fileNameOptions = os.listdir(textDirectory)
Example #41
0
class App(object):
    def __init__(self):

        self.w_window = Tk()

        self.w_listbox_tracks = Listbox(self.w_window)
        self.w_label_base_path = Label(
            self.w_window,
            highlightbackground='red',
            highlightthickness=1,
        )
        self.w_btn_next = Button(
            self.w_window,
            text=u'Следующая',
            command=self.btn_next,
        )
        self.w_btn_pause = Button(
            self.w_window,
            text=u'Пауза/Играть',
            command=self.btn_pause,
        )
        self.w_btn_stop = Button(
            self.w_window,
            text=u'Стоп',
            command=self.btn_stop,
        )
        self.w_btn_plus = Button(
            self.w_window,
            text=u'+',
            command=self.btn_plus,
        )
        self.w_btn_minus = Button(
            self.w_window,
            text=u'-',
            command=self.btn_minus,
        )
        self.buttons = (
            self.w_btn_next,
            self.w_btn_pause,
            self.w_btn_stop,
            self.w_btn_plus,
            self.w_btn_minus,
        )

        self.music_path = ''
        self.musics = getattr(settings, 'musics', {})

        self.musics_map = {}

        self.media_instance = vlc.get_default_instance()
        self.player = self.media_instance.media_player_new()

        self.media = self.media_instance.media_new(u'')
        self.mediaManager = self.media.event_manager()

        self.mark5 = self.mark4 = self.mark3 = self.mark2 = 0
        self.current_play_path = u''

        # для исключения ошибки, get_position не всегда равен 1
        self._last_pos = 2

        self.worked = False

    def _nur_configure(self):
        self.w_window.protocol('WM_DELETE_WINDOW', self.end)
        self.w_label_base_path.bind('<Double-Button-1>', self.set_new_path)
        self.w_listbox_tracks.bind('<Double-Button-1>', self.select_music)

        self.w_window.minsize(width=settings.MAIN_WINDOW_MIN_WIDTH,
                              height=settings.MAIN_WINDOW_MIN_HEIGHT)
        self.w_window.geometry(u'{0}x{1}+{2}+{3}'.format(
            settings.MAIN_WINDOW_WIDTH, settings.MAIN_WINDOW_HEIGHT,
            settings.MAIN_WINDOW_X, settings.MAIN_WINDOW_Y))

    def _nur_layout(self):
        rel_label_height = 0.1
        rel_btns_height = 0.1
        rel_btns_width = 1.0 / len(self.buttons)
        rel_btns_y = 1 - rel_btns_height
        rel_listbox_heigth = 1 - rel_label_height - rel_btns_height

        self.w_label_base_path.place(
            relx=0,
            rely=0,
            relwidth=1,
            relheight=rel_label_height,
        )
        self.w_listbox_tracks.place(
            relx=0,
            rely=rel_label_height,
            relwidth=1,
            relheight=rel_listbox_heigth,
        )
        x = 0
        for btn in self.buttons:

            btn.place(
                relx=x,
                rely=rel_btns_y,
                relwidth=rel_btns_width,
                relheight=rel_btns_height,
            )
            x += rel_btns_width

    def start(self):
        self._nur_configure()
        self._nur_layout()
        self.set_new_path()
        self.w_window.mainloop()

    def end(self):
        self.write_settings()
        self.w_window.destroy()

    def write_settings(self):
        with open(settings.CONFIG_FILE_PATH, 'w') as f:
            json.dump(
                {
                    'MUSIC_PATH': self.music_path,
                    'musics': self.musics,
                    'VOLUME': self.player.audio_get_volume()
                },
                f,
                indent=4)

    def set_new_path(self, event=None):
        if event:
            self.music_path = askdirectory(
                title=u'Выберите папку с музыкой',
                initialdir=self.music_path) or self.music_path
        else:
            self.music_path = settings.MUSIC_PATH

        self.w_label_base_path['text'] = self.music_path
        self._load_musics()

    def _get_musics(self):
        _musics = {}
        for root, dirs, files in os.walk(self.music_path):
            for fil in files:
                if fil.endswith('.mp3'):
                    file_path = os.path.join(root, fil)
                    _musics[file_path] = {
                        'file_name':
                        fil,
                        'album': (file_path.replace(self.music_path,
                                                    '').replace(fil, '')),
                    }
        return _musics

    def _load_musics(self):
        for mus_path, meta in self._get_musics().iteritems():
            if mus_path not in self.musics:
                self.musics[mus_path] = meta
                meta['last_positions'] = [1.0]

        self.__load_musics()

    def __load_musics(self):
        self.musics_map = [(mus_path, u'{album}{file_name}'.format(**mus_meta))
                           for mus_path, mus_meta in self.musics.iteritems()]
        self.musics_map.sort(key=lambda x: x[1])

        self.musics_map = [(item[0], u'{0} - {2} - {1}'.format(
            index, item[1], (sum(self.musics[item[0]]['last_positions']) /
                             len(self.musics[item[0]]['last_positions']))))
                           for index, item in enumerate(self.musics_map)]
        self.w_listbox_tracks.delete(0, END)

        self.w_listbox_tracks.insert(
            END, *(title for mus_path, title in self.musics_map))

    def select_music(self, event=None):
        self.calculate_mark()
        try:
            index = self.w_listbox_tracks.curselection()[0]
            self.current_play_path, music_title = self.musics_map[index]
        except IndexError:
            return
        else:
            self.player.stop()

            self.media = self.media_instance.media_new(self.current_play_path)
            self.mediaManager = self.media.event_manager()

            self.player.set_media(self.media)
            self.player.play()
            self.player.audio_set_volume(settings.VOLUME)
            if not self.worked:
                self.worked = True
                self.w_window.after(3000, self.after)
            # self.player.set_position(0.9)

    def btn_pause(self):
        self.player.pause()
        self.worked = not self.worked
        print self.worked
        if self.worked:
            self.w_window.after(3000, self.after)

    def btn_stop(self):
        self.player.stop()
        self.worked = False

    def btn_plus(self):
        volume = self.player.audio_get_volume()
        if volume < 100:
            self.player.audio_set_volume(volume + 10)

    def btn_minus(self):
        volume = self.player.audio_get_volume()
        if volume > 0:
            self.player.audio_set_volume(volume - 10)

    def btn_next(self):
        if not self.musics:
            return

        self.calculate_mark()

        if self.mark5 < 10:
            mark = 0.8
            self.mark5 += 1
        elif self.mark4 < 8:
            mark = 0.6
            self.mark4 += 1
        elif self.mark3 < 6:
            mark = 0.4
            self.mark3 += 1
        elif self.mark2 < 4:
            mark = 0.2
            self.mark2 += 1
        else:
            mark = 0
            self.mark5 = self.mark4 = self.mark3 = self.mark2 = 0
            self.write_settings()
            self.__load_musics()

        music_path = random.choice([
            path for path, meta in self.musics.iteritems()
            if sum(meta['last_positions']) / len(meta['last_positions']) > mark
        ])
        for index, music in enumerate(self.musics_map):
            if music[0] == music_path:
                break
        self.w_listbox_tracks.selection_clear(0, END)
        self.w_listbox_tracks.activate(index)
        self.w_listbox_tracks.selection_set(index)
        self.w_listbox_tracks.see(index)
        self.select_music()

    def calculate_mark(self):
        try:
            self.musics[self.current_play_path]['last_positions'].append(
                self.player.get_position())
        except KeyError:
            pass
        else:
            self.musics[self.current_play_path]['last_positions'] = (
                self.musics[self.current_play_path]['last_positions'][-10:])

    def after(self):
        pos = self.player.get_position()
        if pos in (1.0, self._last_pos):
            self.btn_next()

        self._last_pos = pos
        if self.worked:
            self.w_window.after(3000, self.after)
Example #42
0
    def __init__( self, mw, current_options ):
        self.mw = mw
        Frame.__init__( self, mw.root )

        self.orig = current_options
        self.opt = deepcopy( self.orig )
        
        #self.wm_attributes( "-topmost", True )
        
        bg = BG_COLOR
        self.config( bg=bg )
        #self.new_find = new_find
        
        #**********************************
        # Logo Banner
        #**********************************
        self.pic_frame = Frame( self )
        self.image1 = PILopen( WELCOME_IM )
        self.im = PhotoImage( self.image1 )
        Label( self.pic_frame, image=self.im, bd=0 ).pack()
        
        #**********************************
        # Website Banner
        #**********************************
        self.web_frame = Frame( self )
        self.image2 = PILopen( WEBSITE_IM )
        self.im2 = PhotoImage( self.image2 )
        l = Label( self.web_frame, image=self.im2, bd=0 )
        l.pack()
        l.bind( "<ButtonPress-1>", self.WebPress )
        
        
        #**********************************
        # Tags
        #**********************************
        #self.tag_frame = TagCloud( self, self.TEST_TAGS )
        
        #self.tag = Canvas( self.tag_frame )
        #self.tag.config( height=self.winfo_vrootheight()/4 )
        #self.tag.config( width=self.winfo_vrootwidth() )
        #self.tag.config( bg="white" )
        #for thing in dir( self.tag.create_text ):
        #    print thing
        #self.tag.create_text( ( 30, 30 ), text="Hi There", font=Font( family="Times", size=20, weight=BOLD ) )
        #val = self.tag.create_text( ( 50, 50 ), text="Hi There2" )
        #print self.tag.bbox( val )
        
        #self.tag.pack()
        #need to pack still
        
        #**********************************
        # News
        #**********************************
        
        self.news = Frame( self )
                
        features = [ "-A quick start window has been added ( You're looking at it :) )\n",
                     "-The Snap Dragon Banner had been redesigned\n",   
                     "-The Find Pics Button has been redesigned\n", 
                     "-Adding Tags to pictures has been added ( t )\n", 
                     "-The Python Bouquet link now points to the Snap Dragon page\n", 
                     "-Added the ability to skip to a certain picture number ( ctrl-g )\n", 
                     "-fixed bug with finding date taken in find pics\n", 
                     "-fixed bug with finding pictures by date in find pics\n", 
                     "-fixed bug preventing saving pictures with effects\n", 
                     "-fixed bug preventing pictures from being removed\n", 
                     "-fixed bug when re-entering tag additions\n", 
                   ]

        fr1 = Frame( self.news )
        fr2 = Frame( self.news )
        fr3 = Frame( self.news )
        
        Label( fr1, text="News:\nHere are some new things added in this edition of Snap Dragon", bg=BG_COLOR ).pack( fill=X )
        fr1.pack( fill=X )
        
        s = Scrollbar( fr2 )
        t = Text( fr2, width=66 )
        t.focus_set()
        t.pack( side=LEFT, fill=Y )
        s.pack( side=LEFT, fill=Y )
        s.config( command=t.yview )
        t.config( yscrollcommand=s.set )
        for i in range( len( features ) ):
            t.insert( END, features[ i ] )
        t.config( state=DISABLED )
        fr2.pack()
        
        #cb1 = Checkbutton( fr3, text="Display on Startup?" )
        #cb1.bind( "<ButtonPress-1>", self.toggle_news )
        #if( self.opt[ "news_start" ] ):
        #    cb1.select()
        #cb1.pack( side=LEFT )
        
        #**********************************
        # Find Pics
        #**********************************
        self.find_pics = Frame( self )
        Button( self.find_pics, text="Find Pictures", width=15, height=3, command=self.mw.NewFindPics ).pack()
         
        #**********************************
        # Pack Everything grid
        #**********************************
        self.pic_frame.grid( row=0, column=0, columnspan=2 )
        self.find_pics.grid( row=3, column=0 )
        self.news.grid( row=1, column=0, rowspan=2, columnspan=2 )
        self.web_frame.grid( row=0, column=2 )
Example #43
0
class TilePicker(Frame):
    def __init__(self, parent, doc, **kw):
        apply(Frame.__init__, (self, parent), kw)
        self.doc = doc
        self.tilePicker = None
        self.attrPicker = None
        self.status = None
        self.curTile = 0
        self.setAttribute(0)
        self.tilePicker = Label(self, image=self.tilePickerPI,
                                width=128, borderwidth=0)
        self.tilePicker.grid(row=0,column=0)
        self.tilePicker.bind("<Button-1>", self.tilePickerCallback)
        self.attrPicker = Label(self, image=self.attrPickerPI,
                                borderwidth=0)
        self.attrPicker.grid(row=1,column=0)
        self.attrPicker.bind("<Button-1>", self.attrPickerCallback)
        self.status = Label(self)
        self.status.grid(row=2,column=0)
        self.setStatus()

    def setAttribute(self, value):
        self.curAttribute = value & 0x03
        self.updateWidgets()

    def updateWidgets(self):
        self.tilePickerImage = renderChrFile(self.doc.chrdata,
                                             self.doc.clut,
                                             self.curAttribute * 4)
        self.tilePickerPI = ImageTk.PhotoImage(self.tilePickerImage)
        if self.tilePicker is not None:
            self.tilePicker.configure(image=self.tilePickerPI)

        previewTile = self.doc.renderTile(self.curTile, self.curAttribute)
        self.attrPickerImage = renderAttrPicker(previewTile,
                                                self.doc.clut,
                                                self.curAttribute)
        self.attrPickerPI = ImageTk.PhotoImage(self.attrPickerImage)
        if self.attrPicker is not None:
            self.attrPicker.configure(image=self.attrPickerPI)
        
        self.setStatus()

    def setTile(self, tile):
        self.curTile = tile
        self.setAttribute(self.curAttribute)

    def setStatus(self):
        if self.status is None:
            return
        label = "tile $%02x attr %d" % (self.curTile, self.curAttribute)
        self.status.configure(text=label)

    def tilePickerCallback(self, event):
        if event.x >= 0 and event.x < 128 and event.y >= 0 and event.y < 128:
            tileX = event.x // 8
            tileY = event.y // 8
            newTileNo = tileY * 16 + tileX
            #print "mouse was clicked on tile", newTileNo
            self.setTile(newTileNo)
            return
        print "mouse was clicked at (%d, %d)" % (event.x, event.y)

    def attrPickerCallback(self, event):
        if event.x >= 0 and event.x < 128:
            attr = event.x // 32
            #print "mouse was clicked on attribute", attr
            self.setAttribute(attr)
            return
        print "mouse was clicked at (%d, %d)" % (event.x, event.y)
Example #44
0
    def __init__(self, master, columns, column_weights=None, cnf={}, **kw):
        """
        Construct a new multi-column listbox widget.

        :param master: The widget that should contain the new
            multi-column listbox.
            
        :param columns: Specifies what columns should be included in
            the new multi-column listbox.  If ``columns`` is an integer,
            the it is the number of columns to include.  If it is
            a list, then its length indicates the number of columns
            to include; and each element of the list will be used as
            a label for the corresponding column.

        :param cnf, kw: Configuration parameters for this widget.
            Use ``label_*`` to configure all labels; and ``listbox_*``
            to configure all listboxes.  E.g.:

                >>> mlb = MultiListbox(master, 5, label_foreground='red')
        """
        # If columns was specified as an int, convert it to a list.
        if isinstance(columns, int):
            columns = range(columns)
            include_labels = False
        else:
            include_labels = True
        
        if len(columns) == 0:
            raise ValueError("Expected at least one column")

        # Instance variables
        self._column_names = tuple(columns)
        self._listboxes = []
        self._labels = []

        # Pick a default value for column_weights, if none was specified.
        if column_weights is None:
            column_weights = [1] * len(columns)
        elif len(column_weights) != len(columns):
            raise ValueError('Expected one column_weight for each column')
        self._column_weights = column_weights

        # Configure our widgets.
        Frame.__init__(self, master, **self.FRAME_CONFIG)
        self.grid_rowconfigure(1, weight=1)
        for i, label in enumerate(self._column_names):
            self.grid_columnconfigure(i, weight=column_weights[i])

            # Create a label for the column
            if include_labels:
                l = Label(self, text=label, **self.LABEL_CONFIG)
                self._labels.append(l)
                l.grid(column=i, row=0, sticky='news', padx=0, pady=0)
                l.column_index = i
            
            # Create a listbox for the column
            lb = Listbox(self, **self.LISTBOX_CONFIG)
            self._listboxes.append(lb)
            lb.grid(column=i, row=1, sticky='news', padx=0, pady=0)
            lb.column_index = i

            # Clicking or dragging selects:
            lb.bind('<Button-1>', self._select)
            lb.bind('<B1-Motion>', self._select)
            # Scroll whell scrolls:
            lb.bind('<Button-4>', lambda e: self._scroll(-1))
            lb.bind('<Button-5>', lambda e: self._scroll(+1))
            lb.bind('<MouseWheel>', lambda e: self._scroll(e.delta))
            # Button 2 can be used to scan:
            lb.bind('<Button-2>', lambda e: self.scan_mark(e.x, e.y))
            lb.bind('<B2-Motion>', lambda e: self.scan_dragto(e.x, e.y))
            # Dragging outside the window has no effect (diable
            # the default listbox behavior, which scrolls):
            lb.bind('<B1-Leave>', lambda e: 'break')
            # Columns can be resized by dragging them:
            l.bind('<Button-1>', self._resize_column)

        # Columns can be resized by dragging them.  (This binding is
        # used if they click on the grid between columns:)
        self.bind('<Button-1>', self._resize_column)
            
        # Set up key bindings for the widget:
        self.bind('<Up>', lambda e: self.select(delta=-1))
        self.bind('<Down>', lambda e: self.select(delta=1))
        self.bind('<Prior>', lambda e: self.select(delta=-self._pagesize()))
        self.bind('<Next>', lambda e: self.select(delta=self._pagesize()))

        # Configuration customizations
        self.configure(cnf, **kw)
Example #45
0
    def create_content(self):

        self.pop = Toplevel(self.master, bg="white")
        self.pop.grab_set()  # when you show the popup

        self.pop.wm_title(' ' * 5 + self._title_)
        self.pop.geometry('{:d}x{:d}+{:d}+{:d}'.format(*self._vertex_))

        leftcolumn = Frame(self.pop, bg="white")
        Label(leftcolumn, bg="white").pack(side="top", fill="both", pady=30)
        Label(leftcolumn,
              bg="white", image=self.im_logo2).pack(side="top",
                                                    fill="both",
                                                    padx=10)  #side= LEFT,
        leftcolumn.pack(side="left", fill='both', padx=1)

        rightcolumn = Frame(self.pop, bg="white")
        firstrow = Frame(rightcolumn, bg="white")
        Frame(rightcolumn, bg="white").pack(side="top", pady=10, padx=0)

        Label(firstrow,
              text="GROTOLAM",
              fg="Gray13",
              bg="white",
              font="Verdana 13 bold").pack(side="left", pady=20)
        Label(firstrow, text='', bg="white").pack(side="left", padx=40)
        firstrow.pack(side="top", padx=0)

        secrow = Frame(rightcolumn, bg="white")
        Label(secrow,
              text="v " + __version__.split()[2],
              fg="Gray13",
              bg="white",
              font="Verdana 10").pack(side="left")
        Label(secrow, text='', bg="white").pack(side="left", padx=75)
        secrow.pack(side="top", padx=0)

        # lets create space to do some stuff ...
        Frame(rightcolumn, bg="white").pack(side="top", pady=20, padx=0)

        thirdrow = Frame(rightcolumn, bg="white")

        Label(thirdrow,
              text="2018 Python version by",
              fg="Gray13",
              bg="white",
              font="Verdana 10").pack(side="left")
        Label(thirdrow, text='', bg="white").pack(side="left", padx=16)
        thirdrow.pack(side="top", padx=0)

        fourthrow = Frame(rightcolumn, bg="white")
        Label(fourthrow,
              text="Hernan Chavez Thielemann",
              fg="Gray13",
              bg="white",
              font="Verdana 10").pack(side="left")
        Label(fourthrow, text='', bg="white").pack(side="left", padx=1)
        fourthrow.pack(side="top", padx=0)

        fifthrow = Frame(rightcolumn, bg="white")
        Label(fifthrow, bg="white", image=self.im_smlogo).pack(side="left",
                                                               fill="both",
                                                               padx=10)
        fifthrow.pack(side="top", padx=0)

        sixthrow = Frame(rightcolumn, bg="white")
        href = Label(sixthrow,
                     bg="white",
                     font="Verdana 10",
                     text="Small web page",
                     fg="blue",
                     cursor="hand2")
        f = Font(href, href.cget("font"))
        f.configure(underline=True)
        href.configure(font=f)
        href.pack(side="left")
        href.bind("<Button-1>", self.callback)

        Label(sixthrow, text='', bg="white").pack(side="left", padx=40)
        sixthrow.pack(side="top", padx=0)

        lastrow = Frame(rightcolumn, bg="white")
        self.bottom_button_row(lastrow)
        rightcolumn.pack(side="right", fill='both', padx=5)
Example #46
0
class Viewer():

    def __init__(self, image):
        self.original = image
        self.image = image.copy()
        self.window = Tk()

        self.genViews()
        self.currentView = StringVar(self.window)
        self.currentView.set('Original')
        options = self.filters.keys();options.sort()
        self.views = OptionMenu(self.window, self.currentView,
                *options, command=self.applyFilter)
        self.views.pack()

        self.tkImage = ImageTk.PhotoImage(image)
        self.lblImage = Label(image=self.tkImage)
        self.lblImage.bind('<Button-1>', self.displayInfos)
        self.lblImage.bind('<Button-3>', self.save)
        self.lblImage.image = self.tkImage
        self.lblImage.pack()

        self.status = StringVar()
        self.lblStatus = Label(textvariable=self.status, justify='right')
        self.lblStatus.pack()

        self.window.mainloop()

    def displayInfos(self, event):
        """
        Displays the coordinates in the status bar
        """
        x = int((event.x-0.1)/args.scalefactor)
        y = int((event.y-0.1)/args.scalefactor)
        pixel = orig.getpixel((x, y))
        self.setStatus("Coordinates : (%s:%s) - Pixel value : %s" %
                (x, y, str(pixel)))

    def setStatus(self, text):
        """
        Changes the text in the status bar
        """
        self.status.set(text)

    def save(self, event):
        """
        Saves the filtered image to a file
        """
        options = {'filetypes':[('PNG','.png'),('GIF','.gif')]}
        outfile = tkFileDialog.asksaveasfilename(**options)
        if outfile == '':
            return
        else:
            self.image.save(outfile)
            return

    def genViews(self):
        """
        Generates filters based on the source image
        """
        self.filters = {}
        for plug in viewPlugins:
            self.filters.update({plug.name:viewPlugins.index(plug)})

    def applyFilter(self, view):
        """
        Applies a filter to the image
        """
        view = self.filters[self.currentView.get()]
        plugin = viewPlugins[view]
        if plugin.parameters:
            for param in plugin.parameters.keys():
                a = tkSimpleDialog.askinteger(
                        'Question', plugin.parameters[param])
                if a is not None:
                    setattr(viewPlugins[view], param, a)
        self.image = viewPlugins[view].process(self.original)

        self.showImage(self.currentView.get(), self.image)
        self.setStatus("")
        return

    def showImage(self, title, image):
        """
        Updates the image in the window
        """
        self.tkImage = ImageTk.PhotoImage(image)
        self.lblImage.configure(image=self.tkImage)
        self.lblImage.image = self.tkImage
Example #47
0
    def _set_up_gui(self):

        """Sets up the Tkinter user interface."""

        # Disable pylint warning for instance attributes defined outside
        # __init__(), since this method is called by __init__()
        #
        # pylint: disable=W0201

        self.root = Tk()
        self.root.title('Video Poker')

        # Set up menubar

        self.menubar = Menu(self.root)

        self.gamemenu = Menu(self.menubar, tearoff=0)
        self.gamemenu.add_command(label="Quit", command=sys.exit)
        self.menubar.add_cascade(label="Game", menu=self.gamemenu)

        self.helpmenu = Menu(self.menubar, tearoff=0)
        self.helpmenu.add_command(label="About", command=self.help_about)
        self.menubar.add_cascade(label="Help", menu=self.helpmenu)

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

        # Set up card images

        self.backimg = PhotoImage(file="{0}b.gif".format(self.gifdir))

        for num in range(5):
            lbl = Label(self.root, image=self.backimg)
            lbl.grid(row=0, column=num, padx=10, pady=10)
            lbl.bind("<Button-1>", self.flip)
            lbl.flipped = True
            lbl.pos = str(num + 1)
            self.cardimg.append(lbl)

        # Set up labels, fields and buttons

        self.pot_lbl = Label(self.root, text="Pot:")
        self.pot_lbl.grid(row=1, column=0,
                          padx=10, pady=2, sticky=W)

        self.pot_amt_lbl = Label(self.root, text="")
        self.pot_amt_lbl.grid(row=1, column=1, columnspan=2,
                              padx=10, pady=2, sticky=W)
        self._update_pot()

        self.bet_lbl = Label(self.root, text="Bet ($):")
        self.bet_lbl.grid(row=2, column=0,
                          padx=10, pady=2, sticky=W)

        self.bet_str = StringVar()
        self.bet_str.set(str(self.defaultbet))

        self.bet_amt_fld = Entry(self.root, textvariable=self.bet_str)
        self.bet_amt_fld.grid(row=2, column=1, columnspan=2,
                              padx=10, pady=2, sticky=W)

        self.button = Button(self.root, text="Deal",
                             command=self.button_clicked)
        self.button.grid(row=1, column=3, rowspan=2, columnspan=2,
                         sticky=W + E + S + N, padx=10)

        self.status_lbl = Label(self.root, bd=1, relief=SUNKEN,
                                text="Welcome to the casino! " +
                                     "Click 'Deal' to play!")
        self.status_lbl.grid(row=3, column=0, columnspan=5,
                             padx=10, pady=10, ipadx=10, ipady=10,
                             sticky=W + E + S + N)

        # Show winnings table

        lbl = Label(self.root, text="Winnings Table", relief=RAISED)
        lbl.grid(row=4, column=1, columnspan=3,
                 pady=15, ipadx=10, ipady=10, sticky=W + E)

        # Two different tables, one for easy mode, one for normal
        # mode, so be prepared to show either one.

        wte = {2500: "Royal Flush", 250: "Straight Flush",
               100: "Four of a Kind", 50: "Full House", 20: "Flush",
               15: "Straight", 4: "Three of a Kind", 3: "Two Pair",
               2: "Jacks or Higher"}
        wtn = {800: "Royal Flush", 50: "Straight Flush", 25: "Four of a Kind",
               9: "Full House", 6: "Flush", 4: "Straight",
               3: "Three of a Kind", 2: "Two Pair", 1: "Jacks or Higher"}
        wtxt = wte if self.game_easy else wtn

        row = 5
        for key in sorted(wtxt.keys(), reverse=True):
            lbl = Label(self.root, text=wtxt[key])
            lbl.grid(row=row, column=1, columnspan=2, sticky=W)
            lbl = Label(self.root, text="{0} : 1".format(key))
            lbl.grid(row=row, column=3, sticky=E)
            row += 1

        lbl = Label(self.root, text="")
        lbl.grid(row=row, column=0, columnspan=5, pady=15)
Example #48
0
class Chord(Frame):
    RIGHT_ARROW_ICON = 'I2RlZmluZSBpbWFnZV93aWR0aCAxNwojZGVmaW5lIGltYWdlX2hlaWdodCAxNwpzdGF0aWMgY2hhciBpbWFnZV9iaXRzW10gPSB7CjB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLAoweDYwLDB4MDAsMHgwMCwweGUwLDB4MDAsMHgwMCwweGUwLDB4MDMsMHgwMCwweGUwLDB4MGYsMHgwMCwweGUwLDB4MDMsMHgwMCwKMHhlMCwweDAxLDB4MDAsMHg2MCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsCjB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwCn07'
    DOWN_ARROW_ICON = 'I2RlZmluZSBpbWFnZV93aWR0aCAxNwojZGVmaW5lIGltYWdlX2hlaWdodCAxNwpzdGF0aWMgY2hhciBpbWFnZV9iaXRzW10gPSB7CjB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLAoweDAwLDB4MDAsMHgwMCwweGUwLDB4MGYsMHgwMCwweGUwLDB4MGYsMHgwMCwweGMwLDB4MDcsMHgwMCwweGMwLDB4MDMsMHgwMCwKMHg4MCwweDAzLDB4MDAsMHgwMCwweDAxLDB4MDAsMHgwMCwweDAxLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsCjB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwCn07'

    def __init__(self, master, title, width, body_background="white", background="#f0f0f0", foreground="#333333", selected_background="#1ba1e2", selected_foreground="white", active_foreground="#0067cb", cursor="hand1"):
        Frame.__init__(self, master, background="white")
        self._title = title

        self._background = background
        self._foreground = foreground
        self._active_foreground = active_foreground
        self._selected_foreground = selected_foreground
        self._selected_background = selected_background

        self._cursor = cursor
        
        self._right_arrow_icon = BitmapImage(data=base64.b64decode(Chord.RIGHT_ARROW_ICON))
        self._down_arrow_icon = BitmapImage(data=base64.b64decode(Chord.DOWN_ARROW_ICON))
        
        self._caption = Frame(self, width =width, background=background, padx=2)
        self._caption.pack(fill=X, pady=(0,2))
        self._caption.pack_propagate(False)

        self._icon_label = Label(self._caption, image=self._right_arrow_icon, background=background)
        self._icon_label.pack(side=LEFT)

        self._title_label = Label(self._caption, text=title, bg = background, fg=foreground)
        self._title_label.pack(side=LEFT, padx=4, fill=X)

        self._caption.configure(height= self._title_label.winfo_reqheight())

        self.body = Frame(self, background=body_background)
        self._body_height = None

        self._is_opened = False
        self._is_animating = False

        self._caption.bind('<Button-1>', self._on_click)
        self._title_label.bind('<Button-1>', self._on_click)
        self._icon_label.bind('<Button-1>', self._on_click)

        self._caption.bind('<Enter>', self._on_enter)
        self._caption.bind('<Leave>', self._on_leave)
    
    @property
    def title(self):
        return self._title
        
    @title.setter
    def title(self, text):
        self._title = text
        self._title_label.configure(text=text)

    def _on_enter(self, event):
        if not self._is_opened:
            self._down_arrow_icon.configure(foreground=self._active_foreground)
            self._right_arrow_icon.configure(foreground=self._active_foreground)

        self.config(cursor=self._cursor)

    def _on_leave(self, event):
        if not self._is_opened:
            self._down_arrow_icon.configure(foreground=self._foreground)
            self._right_arrow_icon.configure(foreground=self._foreground)
        
        self.config(cursor="arrow")

    def _on_click(self, event):
        if self._is_animating: return

        self.toggle()

    def open(self):
        if self._is_animating: return

        if not self._is_opened: self._open()

    def _open(self):        
        self.body.pack()
        self.body.pack_propagate(False)
        
        self._icon_label.configure(image=self._down_arrow_icon, background = self._selected_background)
        self._title_label.configure(foreground= self._selected_foreground, background = self._selected_background)
        self._caption.configure(background = self._selected_background)
        
        self._down_arrow_icon.configure(foreground=self._selected_foreground)

        if self._body_height is None:
            self._body_height= self.body.winfo_reqheight()

        end_value = self._body_height

        self.body.configure(width=self.winfo_width())
        self._is_opened = True
        self._is_animating = True

        animation = Animation(
            self,
            ticks=16,
            interval_time=0.01,
            start_value=0, 
            end_value=end_value,
            config_function=lambda height: self.body.configure(height=int(height)), 
            callback=self._on_finnish_animation)

        animation.start_animation()
        
    def _on_finnish_animation(self):
        self._is_animating = False
        
        if not self._is_opened:
            self.body.pack_forget()

    def close(self):
        if self._is_animating:
            return

        if self._is_opened: self._close()
    
    def _close(self):
        self._icon_label.configure(image=self._right_arrow_icon, background = self._background)
        self._title_label.configure(foreground= self._foreground, background = self._background)
        self._caption.configure(background = self._background)
        
        self._right_arrow_icon.configure(foreground=self._foreground)

        start_value = self.body.winfo_height()

        self._is_opened = False
        self._is_animating = True

        animation = Animation(
            self,
            ticks=16,
            interval_time=0.01,
            start_value=start_value, 
            end_value=0,
            config_function=lambda height: self.body.configure(height=int(height)), 
            callback=self._on_finnish_animation)

        animation.start_animation()
        
    def toggle(self):
        if self._is_opened:
            self._close()
        else:
            self._open()
Example #49
0
class Palette_frame(Frame):
    def __init__(self,
                 master,
                 text=None,
                 borderwidth=2,
                 width=0,
                 height=16,
                 interior_padx=0,
                 interior_pady=8,
                 background=None,
                 caption_separation=4,
                 caption_font=None,
                 caption_builder=None,
                 icon_x=5):
        Frame.__init__(self, master)

        self._is_opened = False

        self._interior_padx = interior_padx
        self._interior_pady = interior_pady

        self._iconOpen = PhotoImage(
            data=
            "R0lGODlhEwATAPcAAAAAAAAAAQD/AAIAAQUAAgcFAAoEAAwHABALABQMBBUPARUSAhUTBhgQBBgVCRsUACEWACIcACYgACggACshACwoADElATEpADEtATQkADQpADYxBDctATk0AT8uAEA6AEE1AEU0AUY3AEY7AUc/Ako7AUpFBUxAA1BHAVE6AFRHAFU/AFdGAFdQAFhCAFlUAVpMAFxGAF1DAF5TAGBaAGNIAGRYAGReAmVSAGhMAGpPAGpWAmpfAm1SAG9RAHFXAHFhAXFrAXJbAXJnAHZuA3dYAHxcAnxfAXxkAHxuAH1gAH5qAX5zAIBcAoRiAIRxAIR5AIdmAIhqAIlyAImAAop6AIxmAI9xAY95AY+BAJJtAJRvAJSIAJV5AZWAAJd1AJl0App5AJtxAZuJAJx/AJyKAZyPAJ+UAKB2AKGAAKKIAaSUAKV7AKeAAaeJAKqeA6uQAKuaAKyVAa+BAK+JALCiALOEALORALSWALSiALWaALeqAbmLALuhALyXALyqALywAL6LAMC0AMGfAMGkAMKRAMOWAMOpAMOvAMO6AMqYAMqiAMqyAMunAMuuAMu+AMy5AM2dAs7DANGfAtG7AdKwANPFANWoANXFANihANi4ANi9ANmyANnEANrLANunAN6mAN/MAOC/AODFAOK5AOLRAOOsAOWxAOasAOfFAefWAOm5AenNAOnTAOu/AOyzBezaAO3YAO60Be7dAPDFAPG1APLQAPO9APPLAPPdAPPjAfS2APTBAPTDAPW/APa/APbAAPbDAPbXAPe/APfIAPfPAPi9APjLAPjjAPm9APnXAPnbAPnkAPrRAPrqAPu8APu/APvBAPvDAPvNAPvUAPvXAPvdAPviAPzHAPzLAPzTAfzWAPzdAPzhAPzkAPzlAPzuAP2+AP3MAP3PAP3VAP3ZAP3iAP3kAP3pAP3sAP3tAP3vAP68AP7FAP7IAP7KAP7RAP7TAf7XAP7aAP7dAP7fAP7jAP7lAP7oAP7qAP7xAP/GAP/pAP/uAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFBwACACwAAAAAEwATAAAIuAABCBxIsKDBgwgFRuBhpqHDLCYSjtiTq6LFVmM0aNyoIUKBEoSaiRzZbBSiPyj/EOrzZEKIQr5+AZsJLNgydThzqktEosShZcusCRV6L5/Ro/kSmTjB6J7Tp1CjIiLB1JzVq1izTj3hiJ7Xr2DDHqLaSJ7Zs2jRljtUokSjeHDjyp1LqO2icXjz6t07yK67v4ADC+5bwlC0w4gTKzYkwsMcU5AjS548xwMCDzkya97M2XLCz6ARBgQAIfkEBQYAAgAsAAACABMAEAAAAg+Uj6nL7Q+jnLTai7PeHBUAIfkEBQcAAgAsAAACABIACgAAAgyUj6nL7Q+jnLTaVgAAIfkEBQcAAgAsAwAFAAUAAgAAAgOUjwUAOw=="
        )
        self._iconClose = PhotoImage(
            data=
            "R0lGODlhEwATAPcAAAAAAAAAAgD/AAEAAAEBAAIAAQUEAAoFAAsJAA4LABMOABUSBRcPAhkUABoYBx4XBB8YACEbASQfASgiACoeAC4jAS4nADEsADMvATQnADUuBTYuADk2ATsxADwtAT84AUI7AEQzAEQ5AEZBAEo5Ako9AUpDAU88AVBGAVBLAVQ9AVRCAFZQAVhGAFhLAVtUAV9CAF9LAWFQAmFZAWFaAGJRAGRLAWVHAGVeAGdiAGtTAmtZBGxZAGxkAG1PAG1iAnFdAHFpAXRUAnRWA3RZAXRiAXZeAHhqAXpiAXpvAXtzAYBcAIFrAYJjAoNgAYN1AoV9AYhrAop0AYtlAI2FAY59AY9jAJB4AJFrApFsApJyAZOFAZRoAZSMAZV+AJmCAJuPAJxmAJxzAJ15AJ2IAJ+CAKGQAaGXAaV6AKV7AKeLAKh8AKiRAKmXAatpAqyhAK2BAK+IAbGEALGYALKEBbOlArV6AbWIALaaAbiLALiUArihArqtAb2NAL+uAMCQA8CZAMGkAMGoAMOAAMO1AcWuAMaTAMa7AMeZAcuYA8uZAMunAMy1AM2YAM29Ac6wAM+bANLFAtSeANSoAdS3AdW+AdaCANahAdfMAdmIANqmAN2wAd3EAN3NAt6oAN7BAOCTAOC4AeHWAeKJAOOsAOSaAOStAOXJAOaMAOeQAOqTAOrQAOuyAOu9AOvKAOvWAOvfAuyWAO2gAO6oAO+bAO+2AO+4APGvAPG8APKfAPLeAPPPAPSiAPSoAPS7APTFAPTXAPW1APW4APXAAPXlAPbKAPemAPerAPfOAPfgAPfqAPjVAPjaAPmwAPm8APm/APnMAPq1APq5APrHAPrgAPvCAPvOAPvXAPvrAfzUAPzgAPzmAPztAPzvAP27AP3AAP3FAP3HAP3KAP3MAP3VAP3ZAP3iAP3kAP3qAP3vAP7FAP7IAP7JAP7MAP7PAP7SAP7TAP7XAP7YAP7cAf7eAP7fAP7jAP7nAP7qAP7sAP7uAP/QAP/TAP/bAP/oAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFBwACACwAAAAAEwATAAAIygABCBxIsKDBgwgHGlCwoGFDBQcSAugQRImSJ0+UBPkgEQosYiBB6jojgkRJkx0aCNyyDZ/Ll6sEBZo5c44MgVWuzdvJsyfPZVUEaoHWrqjRduOSjitaTIpALMGkSZ0aTZgwZ1id+dLC4IATVbFo0cpF1teys2iXVWLxotIuZHDRanv5Mh+xHj+SmdvLt6/fVS9kuPJJuOcjEyUWwVvMuLHjOR0yqFFKubLSMREUZKllq7Pnz55rRTEAgMQULKhTq07tJITE17ANBgQAIfkEBQYAAgAsAAACABMADwAACDUABQgcSLCgwYMIExoUIUKhQ4LMHkok2E7gtILRJmo8iMxhvnz4NoocqbCduJMoU6YkyVJAQAAh+QQFBwABACwBAAMAEgANAAAIHgADCBxIsKDBgwgTKlzIkKGVhhAjSpxIMaK4ihEDAgAh+QQFBwABACwCAAMAEAANAAAIIQADCBxIsKDBgwgTKlzIsOFAYQRzOUyYb6LFiwTbYWwYEAA7"
        )

        height_of_icon = max(self._iconOpen.height(), self._iconClose.height())
        width_of_icon = max(self._iconOpen.width(), self._iconClose.width())

        containerFrame_pady = (height_of_icon // 2) + 1

        self._height = height
        self._width = width

        self._containerFrame = Frame(self,
                                     borderwidth=borderwidth,
                                     width=width,
                                     height=height,
                                     relief=RIDGE,
                                     background=background)
        self._containerFrame.pack(expand=True,
                                  fill=X,
                                  pady=(containerFrame_pady, 0))

        self.interior = Frame(self._containerFrame, background=background)

        self._collapseButton = Label(self,
                                     borderwidth=0,
                                     image=self._iconOpen,
                                     relief=RAISED)
        self._collapseButton.place(in_=self._containerFrame,
                                   x=icon_x,
                                   y=-(height_of_icon // 2),
                                   anchor=N + W,
                                   bordermode="ignore")
        self._collapseButton.bind("<Button-1>", lambda event: self.toggle())

        if caption_builder is None:
            self._captionLabel = Label(self,
                                       anchor=W,
                                       borderwidth=1,
                                       text=text)
            if caption_font is not None:
                self._captionLabel.configure(font=caption_font)
        else:
            self._captionLabel = caption_builder(self)

            if not isinstance(self._captionLabel, Widget):
                raise Exception(
                    "'caption_builder' doesn't return a Tkinter widget")

        self.after(
            0, lambda: self._place_caption(caption_separation, icon_x,
                                           width_of_icon))

    def _place_caption(self, caption_separation, icon_x, width_of_icon):
        self.update()
        x = caption_separation + icon_x + width_of_icon
        y = -(self._captionLabel.winfo_reqheight() // 2)

        self._captionLabel.place(in_=self._containerFrame,
                                 x=x,
                                 y=y,
                                 anchor=N + W,
                                 bordermode="ignore")

    def open(self):
        self._collapseButton.configure(image=self._iconClose)

        self._containerFrame.configure(height=self.interior.winfo_reqheight())
        self.interior.pack(expand=True,
                           fill=X,
                           padx=self._interior_padx,
                           pady=self._interior_pady)

        self._is_opened = True

    def close(self):
        self.interior.pack_forget()
        self._containerFrame.configure(height=self._height)
        self._collapseButton.configure(image=self._iconOpen)

        self._is_opened = False

    def toggle(self):
        if self._is_opened:
            self.close()
        else:
            self.open()
Example #50
0
class TreeNode:
    def __init__(self, canvas, parent, item):
        self.canvas = canvas
        self.parent = parent
        self.item = item
        self.state = 'collapsed'
        self.selected = False
        self.children = []
        self.x = self.y = None
        self.iconimages = {}  # cache of PhotoImage instances for icons

    def destroy(self):
        for c in self.children[:]:
            self.children.remove(c)
            c.destroy()
        self.parent = None

    def geticonimage(self, name):
        try:
            return self.iconimages[name]
        except KeyError:
            pass
        file, ext = os.path.splitext(name)
        ext = ext or ".gif"
        fullname = os.path.join(ICONDIR, file + ext)
        image = PhotoImage(master=self.canvas, file=fullname)
        self.iconimages[name] = image
        return image

    def select(self, event=None):
        if self.selected:
            return
        self.deselectall()
        self.selected = True
        self.canvas.delete(self.image_id)
        self.drawicon()
        self.drawtext()

    def deselect(self, event=None):
        if not self.selected:
            return
        self.selected = False
        self.canvas.delete(self.image_id)
        self.drawicon()
        self.drawtext()

    def deselectall(self):
        if self.parent:
            self.parent.deselectall()
        else:
            self.deselecttree()

    def deselecttree(self):
        if self.selected:
            self.deselect()
        for child in self.children:
            child.deselecttree()

    def flip(self, event=None):
        if self.state == 'expanded':
            self.collapse()
        else:
            self.expand()
        self.item.OnDoubleClick()
        return "break"

    def expand(self, event=None):
        if not self.item._IsExpandable():
            return
        if self.state != 'expanded':
            self.state = 'expanded'
            self.update()
            self.view()

    def collapse(self, event=None):
        if self.state != 'collapsed':
            self.state = 'collapsed'
            self.update()

    def view(self):
        top = self.y - 2
        bottom = self.lastvisiblechild().y + 17
        height = bottom - top
        visible_top = self.canvas.canvasy(0)
        visible_height = self.canvas.winfo_height()
        visible_bottom = self.canvas.canvasy(visible_height)
        if visible_top <= top and bottom <= visible_bottom:
            return
        x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
        if top >= visible_top and height <= visible_height:
            fraction = top + height - visible_height
        else:
            fraction = top
        fraction = float(fraction) / y1
        self.canvas.yview_moveto(fraction)

    def lastvisiblechild(self):
        if self.children and self.state == 'expanded':
            return self.children[-1].lastvisiblechild()
        else:
            return self

    def update(self):
        if self.parent:
            self.parent.update()
        else:
            oldcursor = self.canvas['cursor']
            self.canvas['cursor'] = "watch"
            self.canvas.update()
            self.canvas.delete(ALL)  # XXX could be more subtle
            self.draw(7, 2)
            x0, y0, x1, y1 = self.canvas.bbox(ALL)
            self.canvas.configure(scrollregion=(0, 0, x1, y1))
            self.canvas['cursor'] = oldcursor

    def draw(self, x, y):
        # XXX This hard-codes too many geometry constants!
        self.x, self.y = x, y
        self.drawicon()
        self.drawtext()
        if self.state != 'expanded':
            return y + 17
        # draw children
        if not self.children:
            sublist = self.item._GetSubList()
            if not sublist:
                # _IsExpandable() was mistaken; that's allowed
                return y + 17
            for item in sublist:
                child = self.__class__(self.canvas, self, item)
                self.children.append(child)
        cx = x + 20
        cy = y + 17
        cylast = 0
        for child in self.children:
            cylast = cy
            self.canvas.create_line(x + 9, cy + 7, cx, cy + 7, fill="gray50")
            cy = child.draw(cx, cy)
            if child.item._IsExpandable():
                if child.state == 'expanded':
                    iconname = "minusnode"
                    callback = child.collapse
                else:
                    iconname = "plusnode"
                    callback = child.expand
                image = self.geticonimage(iconname)
                id = self.canvas.create_image(x + 9, cylast + 7, image=image)
                # XXX This leaks bindings until canvas is deleted:
                self.canvas.tag_bind(id, "<1>", callback)
                self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
        id = self.canvas.create_line(
            x + 9,
            y + 10,
            x + 9,
            cylast + 7,
            ##stipple="gray50",     # XXX Seems broken in Tk 8.0.x
            fill="gray50")
        self.canvas.tag_lower(id)  # XXX .lower(id) before Python 1.5.2
        return cy

    def drawicon(self):
        if self.selected:
            imagename = (self.item.GetSelectedIconName()
                         or self.item.GetIconName() or "openfolder")
        else:
            imagename = self.item.GetIconName() or "folder"
        image = self.geticonimage(imagename)
        id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)
        self.image_id = id
        self.canvas.tag_bind(id, "<1>", self.select)
        self.canvas.tag_bind(id, "<Double-1>", self.flip)

    def drawtext(self):
        textx = self.x + 20 - 1
        texty = self.y - 1
        labeltext = self.item.GetLabelText()
        if labeltext:
            id = self.canvas.create_text(textx,
                                         texty,
                                         anchor="nw",
                                         text=labeltext)
            self.canvas.tag_bind(id, "<1>", self.select)
            self.canvas.tag_bind(id, "<Double-1>", self.flip)
            x0, y0, x1, y1 = self.canvas.bbox(id)
            textx = max(x1, 200) + 10
        text = self.item.GetText() or "<no text>"
        try:
            self.entry
        except AttributeError:
            pass
        else:
            self.edit_finish()
        try:
            label = self.label
        except AttributeError:
            # padding carefully selected (on Windows) to match Entry widget:
            self.label = Label(self.canvas, text=text)
            if not TTK:
                self.label.configure(bd=0, padx=2, pady=2)
        theme = idleConf.GetOption('main', 'Theme', 'name')
        if self.selected:
            self.label.configure(idleConf.GetHighlight(theme, 'hilite'))
        else:
            self.label.configure(idleConf.GetHighlight(theme, 'normal'))
        id = self.canvas.create_window(textx,
                                       texty,
                                       anchor="nw",
                                       window=self.label)
        self.label.bind("<1>", self.select_or_edit)
        self.label.bind("<Double-1>", self.flip)
        self.text_id = id

    def select_or_edit(self, event=None):
        if self.selected and self.item.IsEditable():
            self.edit(event)
        else:
            self.select(event)

    def edit(self, event=None):
        self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
        self.entry.insert(0, self.label['text'])
        self.entry.selection_range(0, END)
        self.entry.pack(ipadx=5)
        self.entry.focus_set()
        self.entry.bind("<Return>", self.edit_finish)
        self.entry.bind("<Escape>", self.edit_cancel)

    def edit_finish(self, event=None):
        try:
            entry = self.entry
            del self.entry
        except AttributeError:
            return
        text = entry.get()
        entry.destroy()
        if text and text != self.item.GetText():
            self.item.SetText(text)
        text = self.item.GetText()
        self.label['text'] = text
        self.drawtext()
        self.canvas.focus_set()

    def edit_cancel(self, event=None):
        try:
            entry = self.entry
            del self.entry
        except AttributeError:
            return
        entry.destroy()
        self.drawtext()
        self.canvas.focus_set()
Example #51
0
class TreeNode:

    def __init__(self, canvas, parent, item):
        self.canvas = canvas
        self.parent = parent
        self.item = item
        self.state = 'collapsed'
        self.selected = False
        self.children = []
        self.x = self.y = None
        self.iconimages = {} # cache of PhotoImage instances for icons

    def destroy(self):
        for c in self.children[:]:
            self.children.remove(c)
            c.destroy()
        self.parent = None

    def geticonimage(self, name):
        try:
            return self.iconimages[name]
        except KeyError:
            pass
        file, ext = os.path.splitext(name)
        ext = ext or ".gif"
        fullname = os.path.join(ICONDIR, file + ext)
        image = PhotoImage(master=self.canvas, file=fullname)
        self.iconimages[name] = image
        return image

    def select(self, event=None):
        if self.selected:
            return
        self.deselectall()
        self.selected = True
        self.canvas.delete(self.image_id)
        self.drawicon()
        self.drawtext()

    def deselect(self, event=None):
        if not self.selected:
            return
        self.selected = False
        self.canvas.delete(self.image_id)
        self.drawicon()
        self.drawtext()

    def deselectall(self):
        if self.parent:
            self.parent.deselectall()
        else:
            self.deselecttree()

    def deselecttree(self):
        if self.selected:
            self.deselect()
        for child in self.children:
            child.deselecttree()

    def flip(self, event=None):
        if self.state == 'expanded':
            self.collapse()
        else:
            self.expand()
        self.item.OnDoubleClick()
        return "break"

    def expand(self, event=None):
        if not self.item._IsExpandable():
            return
        if self.state != 'expanded':
            self.state = 'expanded'
            self.update()
            self.view()

    def collapse(self, event=None):
        if self.state != 'collapsed':
            self.state = 'collapsed'
            self.update()

    def view(self):
        top = self.y - 2
        bottom = self.lastvisiblechild().y + 17
        height = bottom - top
        visible_top = self.canvas.canvasy(0)
        visible_height = self.canvas.winfo_height()
        visible_bottom = self.canvas.canvasy(visible_height)
        if visible_top <= top and bottom <= visible_bottom:
            return
        x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
        if top >= visible_top and height <= visible_height:
            fraction = top + height - visible_height
        else:
            fraction = top
        fraction = float(fraction) / y1
        self.canvas.yview_moveto(fraction)

    def lastvisiblechild(self):
        if self.children and self.state == 'expanded':
            return self.children[-1].lastvisiblechild()
        else:
            return self

    def update(self):
        if self.parent:
            self.parent.update()
        else:
            oldcursor = self.canvas['cursor']
            self.canvas['cursor'] = "watch"
            self.canvas.update()
            self.canvas.delete(ALL)     # XXX could be more subtle
            self.draw(7, 2)
            x0, y0, x1, y1 = self.canvas.bbox(ALL)
            self.canvas.configure(scrollregion=(0, 0, x1, y1))
            self.canvas['cursor'] = oldcursor

    def draw(self, x, y):
        # XXX This hard-codes too many geometry constants!
        dy = 20
        self.x, self.y = x, y
        self.drawicon()
        self.drawtext()
        if self.state != 'expanded':
            return y + dy
        # draw children
        if not self.children:
            sublist = self.item._GetSubList()
            if not sublist:
                # _IsExpandable() was mistaken; that's allowed
                return y+17
            for item in sublist:
                child = self.__class__(self.canvas, self, item)
                self.children.append(child)
        cx = x+20
        cy = y + dy
        cylast = 0
        for child in self.children:
            cylast = cy
            self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50")
            cy = child.draw(cx, cy)
            if child.item._IsExpandable():
                if child.state == 'expanded':
                    iconname = "minusnode"
                    callback = child.collapse
                else:
                    iconname = "plusnode"
                    callback = child.expand
                image = self.geticonimage(iconname)
                id = self.canvas.create_image(x+9, cylast+7, image=image)
                # XXX This leaks bindings until canvas is deleted:
                self.canvas.tag_bind(id, "<1>", callback)
                self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
        id = self.canvas.create_line(x+9, y+10, x+9, cylast+7,
            ##stipple="gray50",     # XXX Seems broken in Tk 8.0.x
            fill="gray50")
        self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2
        return cy

    def drawicon(self):
        if self.selected:
            imagename = (self.item.GetSelectedIconName() or
                         self.item.GetIconName() or
                         "openfolder")
        else:
            imagename = self.item.GetIconName() or "folder"
        image = self.geticonimage(imagename)
        id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)
        self.image_id = id
        self.canvas.tag_bind(id, "<1>", self.select)
        self.canvas.tag_bind(id, "<Double-1>", self.flip)

    def drawtext(self):
        textx = self.x+20-1
        texty = self.y-4
        labeltext = self.item.GetLabelText()
        if labeltext:
            id = self.canvas.create_text(textx, texty, anchor="nw",
                                         text=labeltext)
            self.canvas.tag_bind(id, "<1>", self.select)
            self.canvas.tag_bind(id, "<Double-1>", self.flip)
            x0, y0, x1, y1 = self.canvas.bbox(id)
            textx = max(x1, 200) + 10
        text = self.item.GetText() or "<no text>"
        try:
            self.entry
        except AttributeError:
            pass
        else:
            self.edit_finish()
        try:
            self.label
        except AttributeError:
            # padding carefully selected (on Windows) to match Entry widget:
            self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2)
        theme = idleConf.CurrentTheme()
        if self.selected:
            self.label.configure(idleConf.GetHighlight(theme, 'hilite'))
        else:
            self.label.configure(idleConf.GetHighlight(theme, 'normal'))
        id = self.canvas.create_window(textx, texty,
                                       anchor="nw", window=self.label)
        self.label.bind("<1>", self.select_or_edit)
        self.label.bind("<Double-1>", self.flip)
        self.text_id = id

    def select_or_edit(self, event=None):
        if self.selected and self.item.IsEditable():
            self.edit(event)
        else:
            self.select(event)

    def edit(self, event=None):
        self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
        self.entry.insert(0, self.label['text'])
        self.entry.selection_range(0, END)
        self.entry.pack(ipadx=5)
        self.entry.focus_set()
        self.entry.bind("<Return>", self.edit_finish)
        self.entry.bind("<Escape>", self.edit_cancel)

    def edit_finish(self, event=None):
        try:
            entry = self.entry
            del self.entry
        except AttributeError:
            return
        text = entry.get()
        entry.destroy()
        if text and text != self.item.GetText():
            self.item.SetText(text)
        text = self.item.GetText()
        self.label['text'] = text
        self.drawtext()
        self.canvas.focus_set()

    def edit_cancel(self, event=None):
        try:
            entry = self.entry
            del self.entry
        except AttributeError:
            return
        entry.destroy()
        self.drawtext()
        self.canvas.focus_set()
    def init_user_interface(self):

        # The 2-dimensional array keys holds the locations, names and after the
        # for loops are executed below, the Labels that are needed
        # to create each key, both white and black.
        keys = [
            [0, 'C1'],
            [35, 'C#1'],
            [50, 'D1'],
            [85, 'D#1'],
            [100, 'E1'],
            [150, 'F1'],
            [185, 'F#1'],
            [200, 'G1'],
            [235, 'G#1'],
            [250, 'A1'],
            [285, 'A#1'],
            [300, 'B1'],
            [350, 'C2'],
            [385, 'C#2'],
            [400, 'D2'],
            [435, 'D#2'],
            [450, 'E2'],
            [500, 'F2'],
            [535, 'F#2'],
            [550, 'G2'],
            [585, 'G#2'],
            [600, 'A2'],
            [635, 'A#2'],
            [650, 'B2']
        ]

        # This for loop populates the window with the white key Labels
        # and appends a Label to each slot in keys.
        for key in keys:
            if len(key[1]) == 2:
                img = 'pictures/white_key.gif'
                key.append(self.create_key(img, key))

        # This for loop populates the window with the black key Labels
        # and appends a Label to each slot in keys.
        for key in keys:
            if len(key[1]) > 2:
                img = 'pictures/black_key.gif'
                key.append(self.create_key(img, key))

        # This group of lines creates the record Label.
        img = PhotoImage(file='pictures/red_button.gif')
        record_button = Label(self, image=img, bd=0)
        record_button.image = img
        record_button.place(x=700, y=0)
        record_button.name = 'red_button'
        record_button.bind('<Button-1>', record_on_off)

        # This group of lines creates the play Label.
        img = PhotoImage(file='pictures/green_button.gif')
        play_button = Label(self, image=img, bd=0)
        play_button.image = img
        play_button.place(x=700, y=50)
        play_button.name = 'green_button'
        play_button.bind('<Button-1>', play_back)
        play_button.bind('<ButtonRelease-1>', label_released)

        # This titles the window.
        self.parent.title('The Piano')

        # This group of lines centers the window on the screen
        # and specifies the size of the window.
        w = 750
        h = 200
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w) / 2
        y = (sh - h) / 2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))

        # This group of lines saves a reference to keys so that
        # it does not go out of scope and binds the presses and
        # releases of keys to their respective methods
        self.parent.keys = keys
        self.parent.bind('<KeyPress>', key_pressed)
        self.parent.bind('<KeyRelease>', key_released)

        # These 2 lines bind the '1' and '2' keys on the keyboard
        # to the playback method, which then hooks them up to their
        # respective files. This is mostly for demonstration and
        # experimentation purposes.
        self.parent.bind('1', play_back)
        self.parent.bind('2', play_back)

        # This line packs all elements bound to the window.
        self.pack(fill=BOTH, expand=1)
Example #53
0
 def input_link(self, e):
     w = Label(self.frame, text=self.compile_text(e.content), foreground='#0000ff')
     w.bind('<1>', lambda event: webbrowser.open_new_tab(e.url))
     self.pack_element(w)
Example #54
0
class Viewer():
    def __init__(self, image):
        self.original = image
        self.image = image.copy()
        self.window = Tk()

        self.genViews()
        self.currentView = StringVar(self.window)
        self.currentView.set('Original')
        options = self.filters.keys()
        options.sort()
        self.views = OptionMenu(self.window,
                                self.currentView,
                                *options,
                                command=self.applyFilter)
        self.views.pack()

        self.tkImage = ImageTk.PhotoImage(image)
        self.lblImage = Label(image=self.tkImage)
        self.lblImage.bind('<Button-1>', self.displayInfos)
        self.lblImage.bind('<Button-3>', self.save)
        self.lblImage.image = self.tkImage
        self.lblImage.pack()

        self.status = StringVar()
        self.lblStatus = Label(textvariable=self.status, justify='right')
        self.lblStatus.pack()

        self.window.mainloop()

    def displayInfos(self, event):
        """
        Displays the coordinates in the status bar
        """
        x = int((event.x - 0.1) / args.scalefactor)
        y = int((event.y - 0.1) / args.scalefactor)
        pixel = orig.getpixel((x, y))
        self.setStatus("Coordinates : (%s:%s) - Pixel value : %s" %
                       (x, y, str(pixel)))

    def setStatus(self, text):
        """
        Changes the text in the status bar
        """
        self.status.set(text)

    def save(self, event):
        """
        Saves the filtered image to a file
        """
        options = {'filetypes': [('PNG', '.png'), ('GIF', '.gif')]}
        outfile = tkFileDialog.asksaveasfilename(**options)
        if outfile == '':
            return
        else:
            self.image.save(outfile)
            return

    def genViews(self):
        """
        Generates filters based on the source image
        """
        self.filters = {}
        for plug in viewPlugins:
            self.filters.update({plug.name: viewPlugins.index(plug)})

    def applyFilter(self, view):
        """
        Applies a filter to the image
        """
        view = self.filters[self.currentView.get()]
        plugin = viewPlugins[view]
        if plugin.parameters:
            for param in plugin.parameters.keys():
                a = tkSimpleDialog.askinteger('Question',
                                              plugin.parameters[param])
                if a is not None:
                    setattr(viewPlugins[view], param, a)
        self.image = viewPlugins[view].process(self.original)

        self.showImage(self.currentView.get(), self.image)
        self.setStatus("")
        return

    def showImage(self, title, image):
        """
        Updates the image in the window
        """
        self.tkImage = ImageTk.PhotoImage(image)
        self.lblImage.configure(image=self.tkImage)
        self.lblImage.image = self.tkImage
Example #55
0
class TreeNode:

    def __init__(self, canvas, parent, item, menuList = []):
        self.canvas = canvas
        self.parent = parent
        self.item = item
        self.state = 'collapsed'
        self.selected = 0
        self.children = {}
        self.kidKeys = []
        self.x = self.y = None
        self.iconimages = {} # cache of PhotoImage instances for icons
        self.menuList = menuList
        self.menuVar = IntVar()
        self.menuVar.set(0)
        self._popupMenu = None
        self.image_id = None
        if self.menuList:
            if self.menuList[-1] == 'Separator':
                self.menuList = self.menuList[:-1]
            self._popupMenu = Menu(self.canvas, tearoff = 0)
            for i in range(len(self.menuList)):
                item = self.menuList[i]
                if item == 'Separator':
                    self._popupMenu.add_separator()
                else:
                    self._popupMenu.add_radiobutton(
                        label = item,
                        variable = self.menuVar,
                        value = i,
                        indicatoron = 0,
                        command = self.popupMenuCommand)
                    
    def destroy(self):
        for key in self.kidKeys:
            c = self.children[key]
            del self.children[key]
            c.destroy()
        self.parent = None

    def geticonimage(self, name):
        try:
            return self.iconimages[name]
        except KeyError:
            pass
        file, ext = os.path.splitext(name)
        ext = ext or ".gif"
        fullname = os.path.join(ICONDIR, file + ext)
        image = PhotoImage(master=self.canvas, file=fullname)
        self.iconimages[name] = image
        return image

    def select(self, event=None):
        if self.selected:
            return
        self.deselectall()
        self.selected = 1
        if self.parent != None:
            if self.parent.state == 'expanded':
                self.canvas.delete(self.image_id)
                self.drawicon()
                self.drawtext()
        self.item.OnSelect(event)

    def deselect(self, event=None):
        if not self.selected:
            return
        self.selected = 0
        if self.parent != None:
            if self.parent.state == 'expanded':
                self.canvas.delete(self.image_id)
                self.drawicon()
                self.drawtext()

    def deselectall(self):
        if self.parent:
            self.parent.deselectall()
        else:
            self.deselecttree()

    def deselecttree(self):
        if self.selected:
            self.deselect()
        for key in self.kidKeys:
            child = self.children[key]
            child.deselecttree()

    def flip(self, event=None):
        if self.state == 'expanded':
            self.collapse()
        else:
            self.expand()
        self.item.OnDoubleClick()
        return "break"

    def popupMenu(self, event=None):
        if self._popupMenu:
            self._popupMenu.post(event.widget.winfo_pointerx(),
                                 event.widget.winfo_pointery())
            return "break"

    def popupMenuCommand(self):
        command = self.menuList[self.menuVar.get()]
        self.item.MenuCommand(command)
        if self.parent and (command != 'Update Explorer'):
            # Update parent to try to keep explorer up to date
            self.parent.update()

    def expand(self, event=None):
        if not self.item.IsExpandable():
            return
        if self.state != 'expanded':
            self.state = 'expanded'
            self.update()
            self.view()

    def collapse(self, event=None):
        if self.state != 'collapsed':
            self.state = 'collapsed'
            self.update()

    def view(self):
        top = self.y - 2
        bottom = self.lastvisiblechild().y + 17
        height = bottom - top
        visible_top = self.canvas.canvasy(0)
        visible_height = self.canvas.winfo_height()
        visible_bottom = self.canvas.canvasy(visible_height)
        if visible_top <= top and bottom <= visible_bottom:
            return
        x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
        if top >= visible_top and height <= visible_height:
            fraction = top + height - visible_height
        else:
            fraction = top
        fraction = float(fraction) / y1
        self.canvas.yview_moveto(fraction)

    def reveal(self):
        # Make sure all parent nodes are marked as expanded
        parent = self.parent
        while parent:
            if parent.state == 'collapsed':
                parent.state = 'expanded'
                parent = parent.parent
            else:
                break
        # Redraw tree accordingly
        self.update()
        # Bring this item into view
        self.view()

    def lastvisiblechild(self):
        if self.kidKeys and self.state == 'expanded':
            return self.children[self.kidKeys[-1]].lastvisiblechild()
        else:
            return self

    def update(self):
        if self.parent:
            self.parent.update()
        else:
            oldcursor = self.canvas['cursor']
            self.canvas['cursor'] = "watch"
            self.canvas.update()
            self.canvas.delete(Tkinter.ALL)     # XXX could be more subtle
            self.draw(7, 2)
            x0, y0, x1, y1 = self.canvas.bbox(Tkinter.ALL)
            self.canvas.configure(scrollregion=(0, 0, x1, y1))
            self.canvas['cursor'] = oldcursor

    def draw(self, x, y):
        # XXX This hard-codes too many geometry constants!
        self.x, self.y = x, y
        self.drawicon()
        self.drawtext()
        if self.state != 'expanded':
            return y+17
        # draw children
        sublist = self.item._GetSubList()
        if not sublist:
            # IsExpandable() was mistaken; that's allowed
            return y+17
        self.kidKeys = []
        for item in sublist:
            key = item.GetKey()
            if self.children.has_key(key):
                child = self.children[key]
            else:
                child = TreeNode(self.canvas, self, item, self.menuList)
            self.children[key] = child
            self.kidKeys.append(key)
        # Remove unused children
        for key in self.children.keys():
            if key not in self.kidKeys:
                del(self.children[key])
        cx = x+20
        cy = y+17
        cylast = 0
        for key in self.kidKeys:
            child = self.children[key]
            cylast = cy
            self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50")
            cy = child.draw(cx, cy)
            if child.item.IsExpandable():
                if child.state == 'expanded':
                    iconname = "minusnode"
                    callback = child.collapse
                else:
                    iconname = "plusnode"
                    callback = child.expand
                image = self.geticonimage(iconname)
                id = self.canvas.create_image(x+9, cylast+7, image=image)
                # XXX This leaks bindings until canvas is deleted:
                self.canvas.tag_bind(id, "<1>", callback)
                self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
        id = self.canvas.create_line(x+9, y+10, x+9, cylast+7,
            ##stipple="gray50",     # XXX Seems broken in Tk 8.0.x
            fill="gray50")
        self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2
        return cy

    def drawicon(self):
        if self.selected:
            imagename = (self.item.GetSelectedIconName() or
                         self.item.GetIconName() or
                         "openfolder")
        else:
            imagename = self.item.GetIconName() or "folder"
        image = self.geticonimage(imagename)
        id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)
        self.image_id = id
        self.canvas.tag_bind(id, "<1>", self.select)
        self.canvas.tag_bind(id, "<Double-1>", self.flip)
        self.canvas.tag_bind(id, "<3>", self.popupMenu)
        
    def drawtext(self, text=None):
        textx = self.x+20-1
        texty = self.y-1
        labeltext = self.item.GetLabelText()
        if labeltext:
            id = self.canvas.create_text(textx, texty, anchor="nw",
                                         text=labeltext)
            self.canvas.tag_bind(id, "<1>", self.select)
            self.canvas.tag_bind(id, "<Double-1>", self.flip)
            x0, y0, x1, y1 = self.canvas.bbox(id)
            textx = max(x1, 200) + 10
        if text==None:
            text = self.item.GetText() or "<no text>"
        try:
            self.entry
        except AttributeError:
            pass
        else:
            self.edit_finish()
        try:
            label = self.label
        except AttributeError:
            # padding carefully selected (on Windows) to match Entry widget:
            self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2)
        if self.selected:
            self.label.configure(fg="white", bg="darkblue")
        else:
            fg = self.item.GetTextFg()
            self.label.configure(fg=fg, bg="white")
        id = self.canvas.create_window(textx, texty,
                                       anchor="nw", window=self.label)
        self.label.bind("<1>", self.select_or_edit)
        self.label.bind("<Double-1>", self.flip)
        self.label.bind("<3>", self.popupMenu)
        # Update text if necessary
        if text != self.label['text']:
            self.label['text'] = text
        self.text_id = id

    def select_or_edit(self, event=None):
        if self.selected and self.item.IsEditable():
            text = self.item.GetTextForEdit()
            self.label['text'] = text
            self.drawtext(text)
            self.edit(event)
        else:
            self.select(event)

    def edit(self, event=None):
        self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
        self.entry.insert(0, self.label['text'])
        self.entry.selection_range(0, Tkinter.END)
        self.entry.pack(ipadx=5)
        self.entry.focus_set()
        self.entry.bind("<Return>", self.edit_finish)
        self.entry.bind("<Escape>", self.edit_cancel)

    def edit_finish(self, event=None):
        try:
            entry = self.entry
            del self.entry
        except AttributeError:
            return
        text = entry.get()
        entry.destroy()
        if text and text != self.item.GetText():
            self.item.SetText(text)
        text = self.item.GetText()
        self.label['text'] = text
        self.drawtext()
        self.canvas.focus_set()

    def edit_cancel(self, event=None):
        self.drawtext()
        self.canvas.focus_set()

    def find(self, searchKey):
        # Search for a node who's key matches the given key
        # Is it this node
        if searchKey == self.item.GetKey():
            return self
        # Nope, check the children
        sublist = self.item._GetSubList()
        for item in sublist:
            key = item.GetKey()
            # Use existing child or create new TreeNode if none exists
            if self.children.has_key(key):
                child = self.children[key]
            else:
                child = TreeNode(self.canvas, self, item, self.menuList)
                # Update local list of children and keys
                self.children[key] = child
                self.kidKeys.append(key)
            # See if node is child (or one of child's descendants)
            retVal = child.find(searchKey)
            if retVal:
                return retVal
        # Not here
        return None
Example #56
0
class FalconGUI:
    def __init__(self, master):
        self.master = master
        self.master.title("Credo QSFP-SFP Tester")
        self.api = Falcon_lib()

        self.tab_1 = Frame(self.master,relief=)
        self.tab_1.grid(row=0,column=0)
        self.monitor_1 = Label(self.tab_1, text='RX Monitor 1')
        self.monitor_1.bind("<Button-3>", self.print_click)
        self.monitor_1.pack(ipady=5)
        self.table_1 = Frame(self.tab_1)
        self.table_1.pack(fill='both', padx=10)

        self.link_status = Label(self.table_1, text='Link Status')
        self.link_status.grid(row=1, sticky='W', padx=10)
        self.eye = Label(self.table_1, text='Eye Margin')
        self.eye.grid(row=3, sticky='W', padx=10)
        self.BER = Label(self.table_1, text='BER')
        self.BER.grid(row=4, sticky='W', padx=10)
        self.passfail = Label(self.table_1, text='Pass/Fail')
        self.passfail.grid(row=5, sticky='W', padx=10)



        self.table_2 = Frame(self.master)
        self.table_2.grid(row=0,column=1)#pack(fill='both', padx=10)
        self.monitor_2 = Label(self.tab_1, text='RX Monitor 2')
        self.monitor_2.pack(pady=10)

        self.link_status = Label(self.table_2, text='Link Status')
        self.link_status.grid(row=1, sticky='W', padx=10)
        self.eye = Label(self.table_2, text='Eye Margin')
        self.eye.grid(row=3, sticky='W', padx=10)
        self.BER = Label(self.table_2, text='BER')
        self.BER.grid(row=4, sticky='W', padx=10)
        self.passfail = Label(self.table_2, text='Pass/Fail')
        self.passfail.grid(row=5, sticky='W', padx=10)
        self.count = 0

        self.all_button = Button(self.tab_1, text='Reset All',
                                 command=self.prbs_reset)
        self.all_button.pack(pady=10)

        self.all_button1 = Button(self.tab_1, text='Reset All  1',
                                 command=self.testGPIO)
        self.all_button1.pack(pady=11)

        self.main_menu = Menu(self.master)
        self.master.config(menu=self.main_menu)
        self.option_menu = Menu(self.main_menu, tearoff=0)
        self.option_menu.add_command(label='Load Alternate Script',
                                     command=self.load_window)
        self.option_menu.add_separator()
        self.option_menu.add_command(label='Exit', command=the_end)
        self.main_menu.add_cascade(label='Options', menu=self.option_menu)

        self.table()
        self.display()

    def print_click(self):
        print 'You right clicked!'

    def prbs_reset(self):
        for i in range(16):
            self.api.Falcon_Reset_PRBS_Cntr_B(i + 1)
        self.count = 0

    def table(self):
        eye = []
        ber = []
        ar = []
        br = []

        for i in range(1, 9):
            eye.append('eye_%d' % i)
            ber.append('ber_%d' % i)
            ar.append('AR%d' % i)

            ar[i - 1] = Label(self.table_1, text='AR%d' % i, bg='grey')
            eye[i - 1] = Label(self.table_1, bg='white')
            ber[i - 1] = Label(self.table_1, bg='white')

            ar[i - 1].grid(row=0, column=i, sticky='S', ipadx=41, pady=1)
            eye[i - 1].grid(row=3, column=i, ipadx=52, ipady=5)
            ber[i - 1].grid(row=4, column=i, ipadx=52, ipady=5)

        for i in range(1, 9):
            v = i + 8
            eye.append('eye_%d' % i)
            ber.append('ber_%d' % i)
            br.append('BR%d' % i)

            br[i - 1] = Label(self.table_2, text='BR%d' % i, bg='grey')
            eye[v - 1] = Label(self.table_2, bg='white')
            ber[v - 1] = Label(self.table_2, bg='white')

            br[i - 1].grid(row=0, column=i, ipadx=41, pady=1)
            eye[v - 1].grid(row=3, column=i, ipadx=52, ipady=5)
            ber[v - 1].grid(row=4, column=i, ipadx=52, ipady=5)

    def data(self):

        link = []
        eye = []
        ber = []
        fail = []

        self.count += 1
        timer = Label(self.master, text='Test Time: %d' % self.count)
        timer.grid(row=1, pady=10, ipadx=7)

        for i in range(1, 9):
            link.append('link_%d' % i)
            eye.append('eye_%d' % i)
            ber.append('ber_%d' % i)
            fail.append('fail_%d' % i)

            link[i - 1] = Label(self.table_2, width=3, height=1)
            fail[i - 1] = Label(self.table_2, width=3, height=1, relief='solid', bd=1)
            
            if self.link_stat(i) == 1:
                link[i - 1].config(text='ON', bg='green')
                if self.ber(i) <= 1e-13:
                    fail[i - 1].config(text='PASS', bg='green')
                else:
                    fail[i - 1].config(text='FAIL', bg='red')
            else:
                link[i - 1].config(text='OFF', bg='red')
                fail[i - 1].config(text='FAIL', bg='red')
            eye[i - 1] = Label(self.table_2, text='%.3f' % self.eye_marg(i),
                               bg='white', width=3, height=1)
            ber[i - 1] = Label(self.table_2, text='%.2E' % self.ber(i),
                               bg='white', width=3, height=1)
                               
            if (i<5):
                link[i - 1].grid(row=1, column=i+4, ipadx=41, ipady=5)
                eye[i - 1].grid(row=3, column=i+4, ipadx=14)
                ber[i - 1].grid(row=4, column=i+4, ipadx=14)
                fail[i - 1].grid(row=5, column=i+4, ipadx=40, ipady=5)
            else:
                link[i - 1].grid(row=1, column=i-4, ipadx=41, ipady=5)
                eye[i - 1].grid(row=3, column=i-4, ipadx=14)
                ber[i - 1].grid(row=4, column=i-4, ipadx=14)
                fail[i - 1].grid(row=5, column=i-4, ipadx=40, ipady=5)

            
        for i in range(1, 9):
            v = i + 8
            link.append('link_%d' % i)
            eye.append('eye_%d' % i)
            ber.append('ber_%d' % i)
            fail.append('fail_%d' % i)

            link[v - 1] = Label(self.table_1, width=3, height=1)
            fail[v - 1] = Label(self.table_1, width=3, height=1, relief='solid', bd=1)
            if self.link_stat(v) == 1:
                link[v - 1].config(text='ON', bg='green')
                if self.ber(v) <= 1e-13:
                    fail[v - 1].config(text='PASS', bg='green')
                else:
                    fail[v - 1].config(text='FAIL', bg='red')
            else:
                link[v - 1].config(text='OFF', bg='red')
                fail[v - 1].config(text='FAIL', bg='red')
            eye[v - 1] = Label(self.table_1, text='%.3f' % self.eye_marg(v),
                               bg='white', width=3, height=1)
            ber[v - 1] = Label(self.table_1, text='%.2E' % self.ber(v),
                               bg='white', width=3, height=1)
          
            if (i<5):
                link[v - 1].grid(row=1, column=i+4, ipadx=41, ipady=5)
                eye[v - 1].grid(row=3, column=i+4, ipadx=14)
                ber[v - 1].grid(row=4, column=i+4, ipadx=14)
                fail[v - 1].grid(row=5, column=i+4, ipadx=40, ipady=5)
            else:
                link[v - 1].grid(row=1, column=i-4, ipadx=41, ipady=5)
                eye[v - 1].grid(row=3, column=i-4, ipadx=14)
                ber[v - 1].grid(row=4, column=i-4, ipadx=14)
                fail[v - 1].grid(row=5, column=i-4, ipadx=40, ipady=5)
            '''
            link[v - 1].grid(row=1, column=i, ipadx=41, ipady=5)
            eye[v - 1].grid(row=3, column=i, ipadx=14)
            ber[v - 1].grid(row=4, column=i, ipadx=14)
            fail[v - 1].grid(row=5, column=i, ipadx=40, ipady=5)
            '''
    def display(self):
        self.data()
        self.master.after(1000, self.display)

    def testGPIO(self):
        adr=0
        a=self.api.MdioRd(0)
        print "addr %x's value0x%x" %(adr,a)

    def connect(self):
        self.api.connect()

    def link_stat(self, m):
        return int(self.api.Falcon_Link_Status_B(m))

    def eye_marg(self, m):
        eye = float(self.api.Falcon_Read_Eyemargin_B(m))
        return eye

    def ber(self, m):
        return self.api.RxReadPRBSCounterB(m) / float((40 * 50 * 10 ** 9))

    def load_window(self):
        new = Toplevel(self.master)
        what = Fetch(new)
Example #57
0
class TreeNode:
    def __init__(self, canvas, parent, item, colortheme, vspace=20):
        self.canvas = canvas
        self.parent = parent
        self.item = item
        self.state = 'collapsed'
        self.selected = False
        self.edited = False
        self.children = []
        self.colortheme = colortheme
        self.x = self.y = None
        self.vspace = vspace
        self.halfvspace = int(round(self.vspace / 2))
        self.evenodd = 0
        if not self.parent:
            self.canvas.bind('<Configure>', self.reconfig)

    def reconfig(self, *args):
        if len(self.canvas['scrollregion']) > 0:
            w, n, e, s = self.canvas._getints(self.canvas['scrollregion'])
            if e < self.canvas.winfo_width():
                e = self.canvas.winfo_width()
            for item in self.canvas.windows:
                win, x = item
                rightside = x + self.canvas._getints(
                    self.canvas.itemcget(win, 'width'))[0]
                if rightside < e:
                    self.canvas.itemconfigure(win, width=e - x)

    def destroy(self):
        for c in self.children[:]:
            self.children.remove(c)
            c.destroy()
        self.parent = None

    def geticonimage(self, name):
        return name

    def select(self, event=None):
        if self.selected:
            return
        self.deselectall()
        self.selected = True
        #		self.canvas.delete(self.image_id)
        self.drawicon()
        self.drawtext()
        self.item.OnClick()

    def deselect(self, event=None):
        if not self.selected:
            return
        self.selected = False
        #		self.canvas.delete(self.image_id)
        self.drawicon()
        self.drawtext()

    def deselectall(self):
        if self.parent:
            self.parent.deselectall()
        else:
            self.deselecttree()

    def deselecttree(self):
        if self.selected:
            self.deselect()
        for child in self.children:
            child.deselecttree()

    def flip(self, event=None):
        if self.state == 'expanded':
            self.collapse()
        else:
            self.expand()
        self.item.OnDoubleClick()
        return "break"

    def expand(self, event=None):
        if not self.item._IsExpandable():
            return
        if self.state != 'expanded':
            self.state = 'expanded'
            self.update()
            self.view()

    def collapse(self, event=None):
        self.deselecttree()
        if self.state != 'collapsed':
            self.state = 'collapsed'
            self.update()

    def view(self):
        top = self.y
        bottom = self.lastvisiblechild().y + self.vspace
        height = bottom - top
        visible_top = self.canvas.canvasy(0)
        visible_height = self.canvas.winfo_height()
        visible_bottom = self.canvas.canvasy(visible_height)
        if visible_top <= top and bottom <= visible_bottom:
            return
        x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
        if top >= visible_top and height <= visible_height:
            fraction = top + height - visible_height
        else:
            fraction = top
        fraction = float(fraction) / y1
        self.canvas.yview_moveto(fraction)

    def lastvisiblechild(self):
        if self.children and self.state == 'expanded':
            return self.children[-1].lastvisiblechild()
        else:
            return self

    def update(self):
        if self.parent:
            self.parent.update()
        else:
            self.canvas.evenodd = 1
            self.canvas.windows = []
            oldcursor = self.canvas['cursor']
            self.canvas['cursor'] = "watch"
            self.canvas.update()
            self.canvas.delete(ALL)
            self.draw(5, 3)
            x0, y0, x1, y1 = self.canvas.bbox(ALL)
            self.canvas.configure(scrollregion=(0, 0, x1, y1))
            self.canvas['cursor'] = oldcursor
            self.reconfig()

    def draw(self, x, y):
        if self.canvas.evenodd:
            self.evenodd = 0
            self.canvas.evenodd = 0
        else:
            self.evenodd = 1
            self.canvas.evenodd = 1
        self.x, self.y = x, y
        self.drawicon()
        self.drawtext()
        if self.state != 'expanded':
            return y + self.vspace
        # draw children
        if not self.children:
            sublist = self.item._GetSubList()
            if not sublist:
                # _IsExpandable() was mistaken; that's allowed
                return y + self.vspace
            for item in sublist:
                child = self.__class__(self.canvas, self, item,
                                       self.colortheme, self.vspace)
                self.children.append(child)
        cx = x + self.vspace
        cy = y + self.vspace
        cylast = 0
        for child in self.children:
            cylast = cy
            self.canvas.create_line(x + self.halfvspace,
                                    cy + self.halfvspace,
                                    cx,
                                    cy + self.halfvspace,
                                    fill=self.colortheme.treelinescolor,
                                    stipple="gray50")
            cy = child.draw(cx, cy)
            if child.item._IsExpandable():
                if child.state == 'expanded':
                    iconname = "tree_minus"
                    callback = child.collapse
                else:
                    iconname = "tree_plus"
                    callback = child.expand
                image = self.geticonimage(iconname)
                id = self.canvas.create_image(x + self.halfvspace,
                                              cylast + self.halfvspace,
                                              image=image)
                self.canvas.tag_bind(id, "<1>", callback)
                self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
        id = self.canvas.create_line(x + self.halfvspace,
                                     y + self.halfvspace,
                                     x + self.halfvspace,
                                     cylast + self.halfvspace,
                                     stipple="gray50",
                                     fill=self.colortheme.treelinescolor)
        self.canvas.tag_lower(id)
        return cy

    def drawicon(self):
        return

    def drawtext(self):
        textx = self.x
        texty = self.y
        labeltext = self.item.GetLabelText()
        if labeltext:
            id = self.canvas.create_text(textx,
                                         texty,
                                         anchor="nw",
                                         text=labeltext)
            self.canvas.tag_bind(id, "<1>", self.select)
            self.canvas.tag_bind(id, "<Double-1>", self.flip)
            x0, y0, x1, y1 = self.canvas.bbox(id)
            textx = max(x1, 200) + self.halfvspace
        text = self.item.GetText() or "<no text>"

        if self.selected:
            imagename = (self.item.GetSelectedIconName()
                         or self.item.GetIconName() or "tree_node")
        else:
            imagename = self.item.GetIconName() or "tree_node"
        image = self.geticonimage(imagename)

        try:
            self.entry
        except AttributeError:
            pass
        else:
            self.edit_finish()
        try:
            label = self.label
        except AttributeError:

            self.frame = Frame(self.canvas, border=1, relief='flat')
            self.iconlabel = Label(self.frame,
                                   image=image,
                                   bd=0,
                                   padx=1,
                                   pady=1,
                                   anchor=W)
            self.label = Label(self.frame,
                               text=text,
                               bd=0,
                               padx=3,
                               pady=1,
                               anchor=W)
            self.iconlabel.pack(side='left')
            self.label.pack(side='left', fill='y')

        widgets = [self.label, self.iconlabel, self.frame]

        if self.evenodd:
            bgcolor = self.colortheme.evencolor
        else:
            bgcolor = self.colortheme.editfieldbackground

        for widget in widgets:
            if self.selected:
                widget['bg'] = self.colortheme.selectbackground
            else:
                widget['bg'] = bgcolor

        if self.selected:
            self.label['fg'] = self.colortheme.selectforeground
        else:
            self.label['fg'] = self.colortheme.foreground

        width = self.frame.winfo_reqwidth()
        if width < self.canvas.winfo_width() - textx:
            width = self.canvas.winfo_width() - textx

        id = self.canvas.create_window(textx,
                                       texty,
                                       anchor=NW,
                                       window=self.frame,
                                       width=width)
        self.canvas.windows.append((id, textx))
        self.label.bind("<1>", self.select_or_edit)
        self.label.bind("<Double-1>", self.flip)
        self.iconlabel.bind("<1>", self.select_or_edit)
        self.iconlabel.bind("<Double-1>", self.flip)
        self.frame.bind("<1>", self.select_or_edit)
        self.frame.bind("<Double-1>", self.flip)
        self.label.bind("<Button-4>", self.unit_up)
        self.label.bind("<Button-5>", self.unit_down)
        self.iconlabel.bind("<Button-4>", self.unit_up)
        self.iconlabel.bind("<Button-5>", self.unit_down)
        self.frame.bind("<Button-4>", self.unit_up)
        self.frame.bind("<Button-5>", self.unit_down)
        self.text_id = id

    def unit_up(self, event):
        first, last = self.canvas.yview()
        if first <= 0 and last >= 1:
            return "break"
        self.canvas.yview_scroll(-1, "unit")
        return "break"

    def unit_down(self, event):
        first, last = self.canvas.yview()
        if first <= 0 and last >= 1:
            return "break"
        self.canvas.yview_scroll(1, "unit")
        return "break"

    def select_or_edit(self, event=None):
        if self.selected and self.item.IsEditable():
            self.edit(event)
        else:
            self.select(event)

    def edit(self, event=None):
        if self.edited:
            return
        self.edited = True
        self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
        self.entry.insert(0, self.label['text'])
        self.entry.selection_range(0, END)
        self.entry.pack(ipadx=5)
        self.entry.focus_set()
        self.entry.bind("<Return>", self.edit_finish)
        self.entry.bind("<Escape>", self.edit_cancel)

    def edit_finish(self, event=None):
        try:
            entry = self.entry
            del self.entry
            self.edited = False
        except AttributeError:
            return
        text = entry.get()
        entry.destroy()
        if text and text != self.item.GetText():
            self.item.SetText(text)
        text = self.item.GetText()
        self.label['text'] = text
        self.drawtext()
        self.canvas.focus_set()

    def edit_cancel(self, event=None):
        try:
            entry = self.entry
            del self.entry
            self.edited = False
        except AttributeError:
            return
        entry.destroy()
        self.drawtext()
        self.canvas.focus_set()
Example #58
0
class SearchBox(Frame):
    def __init__(self,
                 master,
                 entry_width=30,
                 entry_font=None,
                 entry_background="white",
                 entry_highlightthickness=1,
                 button_text="Search",
                 button_ipadx=10,
                 button_background="#009688",
                 button_foreground="white",
                 button_font=None,
                 opacity=0.8,
                 placeholder=None,
                 placeholder_font=None,
                 placeholder_color="grey",
                 spacing=3,
                 command=None):
        Frame.__init__(self, master)

        self._command = command

        self.entry = Entry(self,
                           width=entry_width,
                           background=entry_background,
                           highlightcolor=button_background,
                           highlightthickness=entry_highlightthickness)
        self.entry.pack(side=LEFT, fill=BOTH, ipady=1, padx=(0, spacing))

        if entry_font:
            self.entry.configure(font=entry_font)

        if placeholder:
            add_placeholder_to(self.entry,
                               placeholder,
                               color=placeholder_color,
                               font=placeholder_font)

        self.entry.bind("<Escape>",
                        lambda event: self.entry.nametowidget(".").focus())
        self.entry.bind("<Return>", self._on_execute_command)

        opacity = float(opacity)

        if button_background.startswith("#"):
            r, g, b = hex2rgb(button_background)
        else:
            # Color name
            r, g, b = master.winfo_rgb(button_background)

        r = int(opacity * r)
        g = int(opacity * g)
        b = int(opacity * b)

        if r <= 255 and g <= 255 and b <= 255:
            self._button_activebackground = '#%02x%02x%02x' % (r, g, b)
        else:
            self._button_activebackground = '#%04x%04x%04x' % (r, g, b)

        self._button_background = button_background

        self.button_label = Label(self,
                                  text=button_text,
                                  background=button_background,
                                  foreground=button_foreground,
                                  font=button_font)
        if entry_font:
            self.button_label.configure(font=button_font)

        self.button_label.pack(side=LEFT, fill=Y, ipadx=button_ipadx)

        self.button_label.bind("<Enter>", self._state_active)
        self.button_label.bind("<Leave>", self._state_normal)

        self.button_label.bind("<ButtonRelease-1>", self._on_execute_command)

    def get_text(self):
        entry = self.entry
        if hasattr(entry, "placeholder_state"):
            if entry.placeholder_state.contains_placeholder:
                return ""
            else:
                return entry.get()
        else:
            return entry.get()

    def set_text(self, text):
        entry = self.entry
        if hasattr(entry, "placeholder_state"):
            entry.placeholder_state.contains_placeholder = False

        entry.delete(0, END)
        entry.insert(0, text)

    def clear(self):
        self.entry_var.set("")

    def focus(self):
        self.entry.focus()

    def _on_execute_command(self, event):
        text = self.get_text()
        self._command(text)

    def _state_normal(self, event):
        self.button_label.configure(background=self._button_background)

    def _state_active(self, event):
        self.button_label.configure(background=self._button_activebackground)
Example #59
0
class MsgBinder(object):
    def __init__(self, frame, **kwargs):
        text = get_dict_item(kwargs, 'text', 'None')
        font = get_dict_item(kwargs, 'font', 'Arial')
        width = get_dict_item(kwargs, 'width', '+10')
        height = get_dict_item(kwargs, 'height', '+5')
        self.fg = get_dict_item(kwargs, 'fg', 'black')
        self.fg_hov = get_dict_item(kwargs, 'fg_hov', '')
        self.bg = get_dict_item(kwargs, 'bg', '')
        self.bg_hov = get_dict_item(kwargs, 'bg_hov', '')
        self.function = get_dict_item(kwargs, 'func', 'False')
        self.function_exc = get_dict_item(kwargs, 'command', 'False')
        self.img = get_dict_item(kwargs, 'img', '')
        self.img_hov = get_dict_item(kwargs, 'img_hov', '')

        if self.img == '':
            self.msg = Message(frame, text=text)
            self.msg.config(bg=self.bg, fg=self.fg, width=width, font=font)
        else:
            self.msg = Label(frame,
                             image=self.img,
                             width=width,
                             background=self.bg)

        self.msg.bind("<Enter>", self._enter)
        self.msg.bind("<Leave>", self._leave)
        self.msg.bind("<Button-1>", self._click)

    def destroy(self):
        self.msg.destroy()

    def bind(self, func):
        self.msg.bind(func)

    def pack(self, **kwargs):
        side = get_dict_item(kwargs, 'side', 'top')
        anchor = get_dict_item(kwargs, 'anchor', 'nw')
        padx = get_dict_item(kwargs, 'padx', '0')
        pady = get_dict_item(kwargs, 'pady', '0')
        self.msg.pack(side=side, anchor=anchor, padx=padx, pady=pady)

    def _enter(self, event):
        self.msg.config(cursor="hand2")
        if self.fg_hov != '':
            self.msg.config(fg=self.fg_hov)
        if self.bg_hov != '':
            self.msg.config(bg=self.bg_hov)
        if self.img_hov != '':
            self.msg.config(image=self.img_hov)

    def _leave(self, event):
        self.msg.config(cursor="")
        if self.fg_hov != '':
            self.msg.config(fg=self.fg)
        if self.bg_hov != '':
            self.msg.config(bg=self.bg)
        if self.img_hov != '':
            self.msg.config(image=self.img)

    def _click(self, event):
        if self.function == 'func':
            self.function_exc()
        elif self.function == 'link' and self.function_exc != 'none':
            open_address_in_webbrowser(self.function_exc)

    def configure(self, **kwargs):
        self.bg = get_dict_item(kwargs, 'bg', '')
        self.msg.config(bg=self.bg)