Пример #1
0
    def _init_components(self):
        self._panes = PanedWindow(self, orient='horizontal', sashrelief="raised")
        self._panes.pack(expand=True, fill='both')

        self._left_pane = Frame(self._panes, padx=10, pady=5)
        self._right_pane = PanedWindow(self._panes)
        self._panes.add(self._left_pane, sticky='n')
        self._panes.add(self._right_pane)

        self._group_select = GroupSelect(self._left_pane)
        self._group_select.pack(expand=True, fill='x')

        # spacer
        Frame(self._left_pane, height=10).pack()

        graph_controls = LabelFrame(self._left_pane, text="Graph options", padx=10, pady=5)
        graph_controls.columnconfigure(1, weight=1)
        graph_controls.pack(expand=True, fill='x')

        self._show_graph_checkbutton = CheckBox(graph_controls, text='Show graph')
        self._show_graph_checkbutton.select()
        self._show_graph_checkbutton.grid(row=0, columnspan=2, sticky='w')

        Label(graph_controls, text='Algorithm').grid(row=1, sticky='w')
        self._graph_type = OptionList(graph_controls, values=MainWindow.GRAPH_TYPES.keys())
        self._graph_type.config(width=15)
        self._graph_type.grid(row=1, column=1, sticky='we')

        # spacer
        Frame(self._left_pane, height=10).pack()

        self._go_button = Button(self._left_pane, text='Go', command=self._go)
        self._go_button.pack()
Пример #2
0
    def __init__(self, master, skeleton):
        PanedWindow.__init__(self, master=master, height=400)
        self.skeleton = skeleton

        self.figure = Figure(figsize=(5,4), dpi=100)

        self.subplots = {}

        nrows = len(self.skeleton.units)
        ncols = 3
        plot_counter = 1

        for u in self.skeleton.units.keys():
            subplots = [None, None, None]
            history = self.skeleton.units[u].history()
            t = range(0, len(history[0]))

            for a in range(0, 3):
                subplot = self.figure.add_subplot(nrows, ncols, plot_counter, xlim=[0,200], ylim=[-90,90])
                s = history[a]
                subplot.plot(t,s)
                plot_counter += 1
                subplots[a] = subplot

            self.subplots[u] = subplots

        self.canvas = FigureCanvasTkAgg(self.figure, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side="top", fill="both", expand=1)

        self.canvas.mpl_connect("key_press_event", self.pressed_key)

        self.pack(fill="both", expand="yes")
Пример #3
0
    def __init__(self, master, color="gray", size=60, sashpad=2, disallow_dragging=False, on_click=None, image=None, cursor=None, opaqueresize=True):
        Tk_PanedWindow.__init__(self, master, showhandle = False, orient=self.ORIENT, sashpad=sashpad, opaqueresize=opaqueresize)
    
        self._active_sash = None
        self._on_click = on_click
        self._image = image
        self._color = color
        self._cursor = cursor

        self._configure_callbacks = []
        
        if not opaqueresize:
            disallow_dragging = True

        self._disallow_dragging = disallow_dragging

        self._handle_list = []
        self._list_of_panes = []
        
        if self.ORIENT == VERTICAL:           
            self._width= size
            self._height = 2*sashpad
        else:            
            self._width = 2*sashpad
            self._height= size
        
        if opaqueresize:
            self.bind('<Button-1>', self._on_mark_sash)
            self.bind('<B1-Motion>', self._on_drag_sash)
            self.bind('<ButtonRelease-1>', self._on_release)
Пример #4
0
    def _on_drag_sash(self, event):
        coord_x = event.x
        coord_y = event.y

        Tk_PanedWindow.sash_place(self, self._active_sash, coord_x, coord_y)
        self._update_position_all_handles()

        return "break"
Пример #5
0
    def _on_drag_sash(self, event):
        coord_x = event.x
        coord_y = event.y

        Tk_PanedWindow.sash_place(self, self._active_sash, coord_x, coord_y)
        self._update_position_all_handles()

        return "break"
Пример #6
0
    def __init__(self, gesture, master=None):
        self.gesture = gesture
        PanedWindow.__init__(self, master=master, height=500, orient="vertical")

        self.pack(fill="both", expand="yes")

        self.gesture_view = GestureView(gesture=self.gesture, master=self)
        self.tools_view = ToolsView(gesture=self.gesture, master=self)
Пример #7
0
 def __init__(self, root, title, map, width=WINDOW_W, height=WINDOW_H):
     PanedWindow.__init__(self)
     self.root = root
     self.set_title(title)
     self.set_map(map)
     self.width = width
     self.height = height
     self.add_pane()
     self.add_panel()
    def initGUI(self):
        frame = Frame(self, width=630, height=500)
        self.panel = PanedWindow(frame, orient=HORIZONTAL)

        self.LeftFrame(self.panel)
        self.RightFrame(self.panel)
        self.panel.add(self.LFrame)
        self.panel.add(self.RFrame)
        self.panel.pack()
        frame.pack()
 def printInfoAnt(self, i):
     self.frameAnt = PanedWindow(self.FrameInfo, orient=VERTICAL)
     t_Ant = Label(self.frameAnt, text="Information Ant : %d" % (i))
     (t_brain, t_energie, t_acide) = self.getInfoAnt(i)
     a_b = Label(self.frameAnt, text=t_brain)
     a_e = Label(self.frameAnt, text=t_energie)
     a_a = Label(self.frameAnt, text=t_acide)
     t_Ant.pack(side=TOP)
     self.frameAnt.add(t_Ant)
     self.frameAnt.add(a_b)
     self.frameAnt.add(a_e)
     self.frameAnt.add(a_a)
     self.frameAnt.pack()
Пример #10
0
 def add_pane(self):
     master = PanedWindow(bg=BACKGROUND_COLOR)
     master.pack(side=LEFT)
     master.propagate(0)
     canvas = self.get_map().get_canvas()
     hbar = Scrollbar(master, orient=HORIZONTAL)
     hbar.pack(side=BOTTOM, fill=X)
     hbar.config(command=canvas.xview)
     vbar = Scrollbar(master, orient=VERTICAL)
     vbar.pack(side=RIGHT, fill=Y)
     vbar.config(command=canvas.yview)
     canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
     canvas.pack(side=LEFT, expand=True, fill=BOTH)
     master.config(width=PANE_W, height=PANE_H)
     master.add(canvas)
Пример #11
0
      def __init__(self, parent, objectList):
            Toplevel.__init__(self, parent)
            self.protocol('WM_DELETE_WINDOW', self.destroy)

            self._objectList = objectList
            
            self._lb = Listbox(self, selectmode = SINGLE)
            self._lb.pack()
            self._buttons = PanedWindow(self)

            for i in objectList.getKeysInOrder():
                  self._lb.insert(END, i)

            addButton = Button(self._buttons, text="Add", command=self.onAdd)
            addButton.pack(side=LEFT)

            modifyButton = Button(self._buttons, text="Modify", command=self.onModify)
            modifyButton.pack(side=LEFT)
            
            deleteButton = Button(self._buttons, text="Delete", command=self.onDelete)
            deleteButton.pack(side=LEFT)

            cancelButton = Button(self._buttons, text="Cancel", command=self.onCancel)
            cancelButton.pack(side=RIGHT)

            self._buttons.pack(side=BOTTOM)
Пример #12
0
    def __init__(self,
                 master,
                 color="gray",
                 size=60,
                 sashpad=2,
                 disallow_dragging=False,
                 on_click=None,
                 image=None,
                 cursor=None,
                 opaqueresize=True):
        Tk_PanedWindow.__init__(self,
                                master,
                                showhandle=False,
                                orient=self.ORIENT,
                                sashpad=sashpad,
                                opaqueresize=opaqueresize)

        self._active_sash = None
        self._on_click = on_click
        self._image = image
        self._color = color
        self._cursor = cursor

        self._configure_callbacks = []

        if not opaqueresize:
            disallow_dragging = True

        self._disallow_dragging = disallow_dragging

        self._handle_list = []
        self._list_of_panes = []

        if self.ORIENT == VERTICAL:
            self._width = size
            self._height = 2 * sashpad
        else:
            self._width = 2 * sashpad
            self._height = size

        if opaqueresize:
            self.bind('<Button-1>', self._on_mark_sash)
            self.bind('<B1-Motion>', self._on_drag_sash)
            self.bind('<ButtonRelease-1>', self._on_release)
    def initGUI(self):
        frame = Frame(self, width =630, height = 500)
        self.panel = PanedWindow(frame, orient=HORIZONTAL)

        self.LeftFrame(self.panel)
        self.RightFrame(self.panel)
        self.panel.add(self.LFrame)
        self.panel.add(self.RFrame)
        self.panel.pack()
        frame.pack()
Пример #14
0
    def add(self, pane, **kwargs):
        Tk_PanedWindow.add(self, pane, **kwargs)

        self._list_of_panes.append(pane)
        quantity_of_panes = len(self._list_of_panes)

        if quantity_of_panes >= 2:
            handle_index = quantity_of_panes-2
            handle = self.HANDLE_CLASS(self, handle_index, bg=self._color, height=self._height, width=self._width, cursor = self._cursor, disallow_dragging=self._disallow_dragging, on_click=self._on_click, image=self._image)

            if self.ORIENT == VERTICAL:
                handle.place(relx=0.5, anchor="c")
            else:
                handle.place(rely=0.5, anchor="c")

            self._handle_list.append(handle)

            callback_id1 = pane.bind("<Configure>", lambda event, handle_index=handle_index: self._on_configure_pane(handle_index), "+")
            callback_id2 = self._list_of_panes[handle_index].bind("<Configure>", lambda event, handle_index=handle_index: self._on_configure_pane(handle_index), "+")
            self._configure_callbacks.append((callback_id1,callback_id2))
Пример #15
0
    def _init_components(self):
        self._panes = PanedWindow(self, orient='horizontal',
            sashrelief="raised")
        self._panes.pack(expand=True, fill='both')

        self._left_pane = Frame(self._panes)
        self._right_pane = PanedWindow(self._panes)
        self._panes.add(self._left_pane, sticky='n')
        self._panes.add(self._right_pane)

        self._group_select = GroupSelect(self._left_pane)
        self._group_select.pack(expand=True, fill='x')

        self._show_graph_checkbutton = CheckBox(self._left_pane,
            text='Show graph')
        self._show_graph_checkbutton.select()
        self._show_graph_checkbutton.pack()

        self._go_button = Button(self._left_pane, text='Go', command=self._go)
        self._go_button.pack()
Пример #16
0
    def _init_components(self):
        self._panes = PanedWindow(self,
                                  orient='horizontal',
                                  sashrelief="raised")
        self._panes.pack(expand=True, fill='both')

        self._left_pane = Frame(self._panes)
        self._right_pane = PanedWindow(self._panes)
        self._panes.add(self._left_pane, sticky='n')
        self._panes.add(self._right_pane)

        self._group_select = GroupSelect(self._left_pane)
        self._group_select.pack(expand=True, fill='x')

        self._show_graph_checkbutton = CheckBox(self._left_pane,
                                                text='Show graph')
        self._show_graph_checkbutton.select()
        self._show_graph_checkbutton.pack()

        self._go_button = Button(self._left_pane, text='Go', command=self._go)
        self._go_button.pack()
Пример #17
0
    def _init_components(self):
        self._panes = PanedWindow(self, orient='horizontal',
            sashrelief='raised')
        self._panes.pack(expand=True, fill='both')

        self._left_pane = Frame(self._panes, padx=2, pady=2)
        self._right_pane = Frame(self._panes)
        self._panes.add(self._left_pane, width=500)
        self._panes.add(self._right_pane)

        # group name
        group_name_pane = LabelFrame(self._left_pane, text="Group")
        group_name_pane.pack(fill='x')

        self._group_name = GroupNameLabel(group_name_pane, self._group)
        self._group_name.pack(expand=True, fill='both')

        # group order
        group_order_pane = LabelFrame(self._left_pane, text="Order")
        group_order_pane.pack(fill='x')

        self._group_order = IntegerContainer(group_order_pane,
            integer=self._group.order())
        self._group_order.pack(expand=True, fill='both')

        # apex
        self._apex_pane = LabelFrame(self._left_pane, text="Apex")
        self._apex_pane.pack(expand=True, fill='both')

        self._apex_container = ApexListContainer(self._apex_pane,
            apex=self._group.apex())
        self._apex_container.pack(expand=True, fill='both')

        self._show_graph_button = Button(self._right_pane, text='Show graph',
            command=self._show_graph_canvas)
        self._graph_canvas = None
        if self._show_graph:
            self._show_graph_canvas()
        else:
            self._show_graph_button.pack()
 def printInfoAnt(self, i):
     self.frameAnt = PanedWindow(self.FrameInfo, orient=VERTICAL)
     t_Ant = Label(self.frameAnt, text="Information Ant : %d" %(i))
     (t_brain,t_energie,t_acide) = self.getInfoAnt(i)
     a_b = Label(self.frameAnt, text=t_brain)
     a_e = Label(self.frameAnt, text=t_energie)
     a_a = Label(self.frameAnt, text=t_acide)
     t_Ant.pack(side = TOP)
     self.frameAnt.add(t_Ant)
     self.frameAnt.add(a_b)
     self.frameAnt.add(a_e)
     self.frameAnt.add(a_a)
     self.frameAnt.pack()
Пример #19
0
    def _init_components(self):
        self._panes = PanedWindow(self, orient='horizontal', sashrelief='raised')
        self._panes.pack(expand=True, fill='both')

        self._left_pane = Frame(self._panes, padx=2, pady=2)
        self._right_pane = Frame(self._panes)
        self._panes.add(self._left_pane, width=250)
        self._panes.add(self._right_pane)

        # group name
        group_name_pane = LabelFrame(self._left_pane, text="Group", padx=10, pady=5)
        group_name_pane.pack(fill='x')

        self._group_name = GroupNameLabel(group_name_pane, self._group)
        self._group_name.pack(expand=True, fill='both')

        # group order
        group_order_pane = LabelFrame(self._left_pane, text="Order", padx=10, pady=5)
        group_order_pane.pack(fill='x')

        self._group_order = IntegerContainer(group_order_pane, integer=self._group.order())
        self._group_order.pack(expand=True, fill='both')

        # apex
        self._apex_pane = LabelFrame(self._left_pane, text="Apex", padx=10, pady=5)
        self._apex_pane.pack(expand=True, fill='both')

        self._apex_container = ApexListContainer(self._apex_pane, apex=self._group.apex())
        self._apex_container.pack(expand=True, fill='both')

        # graph controls
        cocliques_frame = LabelFrame(self._left_pane, text="Cocliques", padx=10, pady=5)
        cocliques_frame.pack(fill='x')

        self._cocliques_button = Button(cocliques_frame, text="Calculate", command=self._show_cocliques)
        self._cocliques_button.pack(anchor='nw')

        self._cocliques_container = ListContainer(cocliques_frame)
        self._cocliques_list = Listbox(self._cocliques_container)
        self._cocliques_container.set_listbox(self._cocliques_list)

        # Button(graph_controls, text='Group equivalent vertices').pack(anchor='nw')

        # this is a button that show up instead of graph canvas if we uncheck 'Show graph' checkbox.
        self._show_graph_button = Button(self._right_pane, text='Show graph',
                                         command=self._show_graph_canvas)
        self._graph_canvas = None
        if self._show_graph:
            self._show_graph_canvas()
        else:
            self._show_graph_button.pack()
 def printTurn(self):
     frameS = PanedWindow(self.FrameInfo, orient=HORIZONTAL)
     turns = Label(frameS, text="Tour :")
     self.var.set(str(self.selectTurn))
     self.Spin_T = Spinbox(frameS,
                           values=self.turns.keys(),
                           command=self.updateSpin_turn,
                           textvariable=self.var)
     self.Spin_T.bind('<Return>', self.validateTurn)
     turns.pack()
     self.Spin_T.pack()
     frameS.add(turns)
     frameS.add(self.Spin_T)
     frameS.pack()
     self.frameT = frameS
 def printTurn(self):
     frameS = PanedWindow(self.FrameInfo, orient=HORIZONTAL)
     turns = Label(frameS, text="Tour :")
     self.var.set(str(self.selectTurn))
     self.Spin_T = Spinbox(frameS, values=self.turns.keys(), command =
             self.updateSpin_turn ,textvariable=self.var)
     self.Spin_T.bind('<Return>', self.validateTurn)
     turns.pack()
     self.Spin_T.pack()
     frameS.add(turns)
     frameS.add(self.Spin_T)
     frameS.pack()
     self.frameT = frameS
Пример #22
0
    def add(self, pane, **kwargs):
        Tk_PanedWindow.add(self, pane, **kwargs)

        self._list_of_panes.append(pane)
        quantity_of_panes = len(self._list_of_panes)

        if quantity_of_panes >= 2:
            handle_index = quantity_of_panes - 2
            handle = self.HANDLE_CLASS(
                self,
                handle_index,
                bg=self._color,
                height=self._height,
                width=self._width,
                cursor=self._cursor,
                disallow_dragging=self._disallow_dragging,
                on_click=self._on_click,
                image=self._image)

            if self.ORIENT == VERTICAL:
                handle.place(relx=0.5, anchor="c")
            else:
                handle.place(rely=0.5, anchor="c")

            self._handle_list.append(handle)

            callback_id1 = pane.bind("<Configure>",
                                     lambda event, handle_index=handle_index:
                                     self._on_configure_pane(handle_index),
                                     "+")
            callback_id2 = self._list_of_panes[handle_index].bind(
                "<Configure>",
                lambda event, handle_index=handle_index: self.
                _on_configure_pane(handle_index),
                "+")
            self._configure_callbacks.append((callback_id1, callback_id2))
Пример #23
0
class Facade(Frame):
    """This is a Frame that contains group info, group order, apex and prime
    graph.
    """
    def __init__(self, parent, group, show_graph=True, graph_class=None, **kw):
        """
        Parameters:
            show_graph: whether to create and show graph instantly or provide a button to do that lately
            graph_factory: callable accepting one argument - the Group instance and returning Graph instance. Note that
                __str__ method of the callable is used in the UI.
        """
        Frame.__init__(self, parent, **kw)
        self._group = group
        #        self._show_apex = True
        self._show_graph = show_graph
        self._graph_class = graph_class
        self._init_variables()
        self._init_menu()
        self._init_components()

    @property
    def group(self):
        return self._group

    @property
    def apex_list_container(self):
        return self._apex_container

    @property
    def graph_canvas(self):
        return self._graph_canvas

    def _show_graph_canvas(self):
        self._show_graph_button.forget()
        # TODO: add different layouts and other options
        graph_class = self._graph_class
        self.graph = graph_class(self._group)
        self._graph_canvas = GraphCanvas(self._right_pane, SpringLayout(self.graph), caption=str(graph_class))
        self._graph_canvas.pack(expand=True, fill='both')

        self._graph_canvas.vertex_label_mode = self.getvar(
            name=self.winfo_name() + ".vertexlabelposition")

        self._iterations_plugin = IterationsPlugin()
        self._iterations_plugin.apply(self._graph_canvas)

        self.update_layout()

    def _init_components(self):
        self._panes = PanedWindow(self, orient='horizontal', sashrelief='raised')
        self._panes.pack(expand=True, fill='both')

        self._left_pane = Frame(self._panes, padx=2, pady=2)
        self._right_pane = Frame(self._panes)
        self._panes.add(self._left_pane, width=250)
        self._panes.add(self._right_pane)

        # group name
        group_name_pane = LabelFrame(self._left_pane, text="Group", padx=10, pady=5)
        group_name_pane.pack(fill='x')

        self._group_name = GroupNameLabel(group_name_pane, self._group)
        self._group_name.pack(expand=True, fill='both')

        # group order
        group_order_pane = LabelFrame(self._left_pane, text="Order", padx=10, pady=5)
        group_order_pane.pack(fill='x')

        self._group_order = IntegerContainer(group_order_pane, integer=self._group.order())
        self._group_order.pack(expand=True, fill='both')

        # apex
        self._apex_pane = LabelFrame(self._left_pane, text="Apex", padx=10, pady=5)
        self._apex_pane.pack(expand=True, fill='both')

        self._apex_container = ApexListContainer(self._apex_pane, apex=self._group.apex())
        self._apex_container.pack(expand=True, fill='both')

        # graph controls
        cocliques_frame = LabelFrame(self._left_pane, text="Cocliques", padx=10, pady=5)
        cocliques_frame.pack(fill='x')

        self._cocliques_button = Button(cocliques_frame, text="Calculate", command=self._show_cocliques)
        self._cocliques_button.pack(anchor='nw')

        self._cocliques_container = ListContainer(cocliques_frame)
        self._cocliques_list = Listbox(self._cocliques_container)
        self._cocliques_container.set_listbox(self._cocliques_list)

        # Button(graph_controls, text='Group equivalent vertices').pack(anchor='nw')

        # this is a button that show up instead of graph canvas if we uncheck 'Show graph' checkbox.
        self._show_graph_button = Button(self._right_pane, text='Show graph',
                                         command=self._show_graph_canvas)
        self._graph_canvas = None
        if self._show_graph:
            self._show_graph_canvas()
        else:
            self._show_graph_button.pack()

    def _init_variables(self):
        def set_default_var(self, name):
            """Sets widget-specific var with same value as root.
            """
            default_var = self.getvar(name)
            local_var_name = self.winfo_name() + "." + name
            self.setvar(local_var_name, default_var)
            return local_var_name

        local_name = set_default_var(self, "vertexlabelposition")
        tools.trace_variable(self, local_name, "w",
                             self._change_vertex_label_position)

    def _change_vertex_label_position(self, name, *arg):
        # override default value
        self.setvar("vertexlabelposition", self.getvar(name))
        if self._graph_canvas is not None:
            self._graph_canvas.vertex_label_mode = self.getvar(name)

    def _init_menu(self):
        """Init menu bar content.
        """
        toplevel = self.winfo_toplevel()
        if toplevel['menu']:
            self._menu = self.nametowidget(name=toplevel['menu'])
        else:
            self._menu = Menu(toplevel)
            toplevel['menu'] = self._menu

        graph_options = Menu(self._menu, tearoff=0)
        self._menu.add_cascade(label="Graph", menu=graph_options)
        self._menu_index = self._menu.index("end")

        vertex_label_position_menu = Menu(graph_options, tearoff=0)
        graph_options.add_cascade(label="Label position", menu=vertex_label_position_menu)

        menu_var = self.winfo_name() + ".vertexlabelposition"
        vertex_label_position_menu.add_radiobutton(variable=menu_var, label="Auto", value="auto")
        vertex_label_position_menu.add_radiobutton(variable=menu_var, label="Center", value="center")

        graph_options.add_command(label="Save graph...", command=self.call_graph_save_dialog)

        self.bind("<Destroy>", self.__destroy_menu)

    #noinspection PyUnusedLocal
    def __destroy_menu(self, event):
        try:
            self._menu.delete(self._menu_index)
        except TclError:
            pass

    def _show_cocliques(self):
        cocliques = self.graph.max_cocliques()

        def select_coclique(*_):
            index = next(iter(self._cocliques_list.curselection()), None)
            if index is not None:
                selected = cocliques[int(index)]
                pick_state = self._graph_canvas.picked_vertex_state
                pick_state.clear()
                for value in selected:
                    pick_state.pick(self._graph_canvas.get_vertex(value))

        self._cocliques_list.insert(0, *[', '.join(map(str, coclique)) for coclique in cocliques])
        self._cocliques_list.bind("<Double-Button-1>", select_coclique)

        self._cocliques_button.forget()
        self._cocliques_container.pack(expand=True, fill='both')

    def call_graph_save_dialog(self):
        file_name = tkFileDialog.asksaveasfilename(defaultextension='.ps',
                                                   filetypes=[('PostScript', '.ps')], parent=self.winfo_toplevel(),
                                                   title="Save graph as image")
        if file_name:
            with codecs.open(file_name, 'w', encoding='utf-8') as f:
                f.write(self._graph_canvas.postscript())

    def update_layout(self):
        try:
            self._iterations_plugin.iterate(50)
        except AttributeError:
            pass
Пример #24
0
 def _setup_ui(self):
     self.parent.title('p2paste')
     self.style = Style()
     self.style.theme_use('default')
     self.pack(fill=BOTH, expand=True)
     
     '''Fixed top-frame with connection controls'''
     frame_top = Frame(self)
     frame_top.pack(fill=X, side=TOP)
     label_nick = Label(frame_top, text="nickname:")
     label_nick.pack(side=LEFT, padx=2, pady=2)
     self.entry_nick = Entry(frame_top)
     self.entry_nick.pack(side=LEFT, padx=2)
     label_ip = Label(frame_top, text="ip:port")
     label_ip.pack(side=LEFT, padx=2, pady=2)
     self.entry_ip = Entry(frame_top)
     self.entry_ip.pack(side=LEFT, padx=2)
     self.button_connect = Button(frame_top, text="connect")
     self.button_connect.pack(side=LEFT, padx=2)
     self.button_disconnect = Button(frame_top, text="disconnect")
     self.button_disconnect.pack(side=LEFT, padx=2)
     label_port = Label(frame_top, text="port:")
     label_port.pack(side=LEFT, padx=2, pady=2)
     self.entry_port = Entry(frame_top, width=10)
     self.entry_port.pack(side=LEFT, padx=2, pady=2)
     self.button_host = Button(frame_top, text="host")
     self.button_host.pack(side=LEFT, padx=2, pady=2)
     self.button_close_server = Button(frame_top, text="close server")
     self.button_close_server.pack(side=LEFT, padx=2)
     
     '''Bottom frame with a PanedWindow, the main screen part'''
     frame_bottom = Frame(self)
     frame_bottom.pack(fill=BOTH, expand=True, side=TOP)
     pw_main = PanedWindow(frame_bottom)
     pw_main.pack(fill=BOTH, expand=True)
     
     '''Left part of screen, contains paste-text, chat-text and chat-entry'''
     frame_left = Frame(pw_main)
     pw_main.add(frame_left)
     
     '''Left-Bottom chat entry Frame with input controls'''        
     frame_chat_entry = Frame(frame_left)
     frame_chat_entry.pack(fill=X, expand=True, side=BOTTOM)
     self.entry_chat = Entry(frame_chat_entry)
     self.entry_chat.pack(fill=X, expand=True, side=LEFT, padx=2, pady=2)
     self.button_send_message = Button(frame_chat_entry, text="send")
     self.button_send_message.pack(side=LEFT, padx=2, pady=2)
     self.button_copy_chat = Button(frame_chat_entry, text="copy")
     self.button_copy_chat.pack(side=LEFT, padx=2, pady=2)
     '''Paste and chat box on the left side wrapped in a PanedWindow for resizability'''
     pw_center = PanedWindow(frame_left, orient=VERTICAL)
     pw_center.pack(fill=BOTH, expand=True, side=TOP)
     
     '''Pastebox container'''
     frame_paste = Frame(pw_center)
     '''Input controls for Pastebox'''
     frame_paste_controls = Frame(frame_paste)
     frame_paste_controls.pack(fill=X, side=BOTTOM)
     label_has_paste = Label(frame_paste_controls, text="paste permission:")
     label_has_paste.pack(side=LEFT, padx=2, pady=2)
     self.entry_has_paste = Entry(frame_paste_controls, width=8, state=DISABLED)
     self.entry_has_paste.pack(side=LEFT, padx=2, pady=2)
     self.button_request_paste = Button(frame_paste_controls, text="request")
     self.button_request_paste.pack(side=LEFT, padx=2, pady=2)
     self.button_clear_pastebox = Button(frame_paste_controls, text="clear")
     self.button_clear_pastebox.pack(side=LEFT, padx=2, pady=2)
     self.button_selectall_pastebox = Button(frame_paste_controls, text="select all")
     self.button_selectall_pastebox.pack(side=LEFT, padx=2, pady=2)
     self.button_copy_pastebox = Button(frame_paste_controls, text="copy")
     self.button_copy_pastebox.pack(side=LEFT, padx=2, pady=2)
     self.button_paste_pastebox = Button(frame_paste_controls, text="paste")
     self.button_paste_pastebox.pack(side=LEFT, padx=2, pady=2)
     self.button_send_pastebox = Button(frame_paste_controls, text="send")
     self.button_send_pastebox.pack(side=LEFT, padx=2, pady=2)
     '''Pastebox with scrollbars'''
     sbx_text_paste = Scrollbar(frame_paste, orient=HORIZONTAL)
     sbx_text_paste.pack(side=BOTTOM, fill=X, padx=2)
     sby_text_paste = Scrollbar(frame_paste)
     sby_text_paste.pack(side=RIGHT, fill=Y, pady=2)
     self.text_paste = Text(
         frame_paste,
         wrap=NONE,
         xscrollcommand=sbx_text_paste.set,
         yscrollcommand=sby_text_paste.set
     )
     self.text_paste.pack(fill=BOTH, expand=True, padx=2, pady=2)
     sbx_text_paste.config(command=self.text_paste.xview)
     sby_text_paste.config(command=self.text_paste.yview)
     pw_center.add(frame_paste)
     self.pastebox_disabled()
     
     '''Chatbox container'''
     frame_chat = Frame(pw_center)
     sby_text_chat = Scrollbar(frame_chat)
     sby_text_chat.pack(side=RIGHT, fill=Y, pady=2)
     self.text_chat = Text(
         frame_chat,
         wrap=WORD,
         state=DISABLED,
         yscrollcommand=sby_text_chat.set)
     self.text_chat.pack(fill=BOTH, expand=True, padx=2, pady=2)
     sby_text_chat.config(command=self.text_chat.yview)
     pw_center.add(frame_chat)
     
     '''Chat list on the right side'''
     frame_chatlist = Frame(pw_main)
     sby_chatlist = Scrollbar(frame_chatlist)
     sby_chatlist.pack(side=RIGHT, fill=Y, pady=2)
     self.listbox_clients = Listbox(frame_chatlist, yscrollcommand=sby_chatlist.set)
     self.listbox_clients.pack(fill=BOTH, expand=True, padx=2, pady=2)
     sby_chatlist.config(command=self.listbox_clients.yview)
     pw_main.add(frame_chatlist)
Пример #25
0
 def __init__(self, parent, pack_location=None, **kwargs):
     pw.__init__(self, parent, **kwargs)
     if pack_location:
         self.pack(side=pack_location, fill='both', expand=True)
     self.elements = {}
Пример #26
0
    def __init__(self, root):
        self.root = root

        # Radio action buttons
        self.action = None
        self.sgmap_single_btn, self.krn_lib_btn, self.multi_map_btn = None, None, None

        self.file_log_var = StringVar()
        self.csv_file_var = StringVar()
        self.krn_folder_var = StringVar()
        self.output_folder_var = StringVar()
        self.sgmap_folder_var = StringVar()

        self.krn_ent_var = StringVar()
        self.krn_var, self.hem_var = IntVar(), IntVar()
        self.img, self.cdiag = None, None
        self.lat_lbl, self.lat_entry = None, None
        self.k_lbl, self.k_entry = None, None
        self.zen_lbl, self.zen_entry = None, None
        self.azi_lbl, self.azi_entry = None, None
        self.krn_lvl, self.krn_entry, self.krn_btn = None, None, None
        self.txt_redir, self.prg_log = None, None
        self.map_btn, self.gen_krn_btn = None, None

        # Sets window title, size, and icon on screen.
        self.root.title("Skyglow Estimation Toolbox (SET)")
        self.root.geometry('%dx%d+%d+%d' %
                           (constants.SW * 0.75, constants.SH * 0.75, 25, 25))
        self.root.iconbitmap(os.path.join(os.getcwd(), constants.ICO))
        self.root.resizable(False, False)
        self.root.update_idletasks()

        # Creates three paned windows for the main screen.
        base = PanedWindow()
        base.pack(fill=BOTH, expand=1)
        sub1 = PanedWindow(base,
                           orient=VERTICAL,
                           height=self.root.winfo_height() * 3 / 4)
        base.add(sub1)
        sub2 = PanedWindow(sub1,
                           orient=HORIZONTAL,
                           height=self.root.winfo_height() / 5)
        sub1.add(sub2)

        # Creates frame for holding inputs.
        self.input_frame = Frame(sub2)
        sub2.add(self.input_frame)

        # Creates frame for bottom half of main screen.
        self.img_frame = Frame(sub1, bd=2, bg='white', relief="sunken")
        sub1.add(self.img_frame)

        # Creates canvas for displaying images.
        self.img_canvas = Canvas(self.img_frame,
                                 bd=2,
                                 relief="groove",
                                 width=constants.SW * 0.6,
                                 height=self.root.winfo_height() * 3 / 4 * 0.9)
        self.img_canvas.place(relx=.5, rely=.5, anchor=CENTER)

        # Creates help button for link to documentation, instructions, and about.
        self.help_btn = Menubutton(self.input_frame,
                                   text="Help",
                                   relief="raised",
                                   bd=2,
                                   width=8,
                                   pady=1)
        #self.help_btn.place(relx=1, rely=0, anchor=NE)
        self.help_btn.grid(column=4, columnspan=1, row=0)
        self.help_btn_menu = Menu(self.help_btn, tearoff=0)
        doc = 'https://github.com/NASA-DEVELOP'
        self.help_btn_menu.add_command(label="Documentation",
                                       command=lambda: self.open_url(doc))
        self.help_btn_menu.add_command(label="Instructions",
                                       command=self.instructions)
        self.help_btn_menu.add_separator()
        self.help_btn_menu.add_command(label="About", command=self.about)
        self.help_btn["menu"] = self.help_btn_menu
Пример #27
0
class MainWindow(Frame):
    def __init__(self, **kw):
        Frame.__init__(self, **kw)
        self.winfo_toplevel().minsize(width=800, height=480)
        self.pack(expand=True, fill='both')
        self._init_variables()
        self._init_components()
        self._init_menu()

    def _init_components(self):
        self._panes = PanedWindow(self, orient='horizontal',
            sashrelief="raised")
        self._panes.pack(expand=True, fill='both')

        self._left_pane = Frame(self._panes)
        self._right_pane = PanedWindow(self._panes)
        self._panes.add(self._left_pane, sticky='n')
        self._panes.add(self._right_pane)

        self._group_select = GroupSelect(self._left_pane)
        self._group_select.pack(expand=True, fill='x')

        self._show_graph_checkbutton = CheckBox(self._left_pane,
            text='Show graph')
        self._show_graph_checkbutton.select()
        self._show_graph_checkbutton.pack()

        self._go_button = Button(self._left_pane, text='Go', command=self._go)
        self._go_button.pack()

    def _init_variables(self):
        # init default properties
        self.setvar("graphframeview", "onlyone")
        self.setvar("vertexlabelposition", "auto")

    def _init_menu(self):
        toplevel = self.winfo_toplevel()
        self._menu = Menu(toplevel)
        toplevel['menu'] = self._menu

        view = Menu(self._menu, tearoff=0)
        self._menu.add_cascade(label="View", menu=view)

        graph_view = Menu(view, tearoff=0)
        view.add_cascade(label="View graphs", menu=graph_view)

        graph_view.add_radiobutton(label="Only one", value="onlyone",
            variable="graphframeview")
        #        graph_view.add_radiobutton(label="In a row", value="row",
        #            variable=graph_view_var)
        graph_view.add_radiobutton(label="In separate window", value="window",
            variable="graphframeview")


    def _go(self):
        view = self.getvar("graphframeview")

        if view == "onlyone":
            for child in self._right_pane.winfo_children():
                child.destroy()
                #if view in ("onlyone", "row"):
            container = FrameWithCloseButton(self._right_pane)
            self._right_pane.add(container, minsize=600)
        else:
            container = Toplevel()

        facade = Facade(container, self._group_select.selected_group,
            show_graph=self._show_graph_checkbutton.is_selected())

        facade.pack(expand=True, fill='both')
Пример #28
0
    def __init__(self, master, max_num_features, num_frames, mser_image):
        Toplevel.__init__(self, master)

        self.protocol('WM_DELETE_WINDOW', self.withdraw)

        self.notebook = ttk.Notebook(self)
        frame_feats = ttk.Frame(self.notebook)
        frame_forest = ttk.Frame(self.notebook)
        frame_mser = ttk.Frame(self.notebook)
        frame_other = ttk.Frame(self.notebook)
        self.notebook.add(frame_feats, text="Features ")
        self.notebook.add(frame_forest, text=" Forest  ")
        self.notebook.add(frame_mser, text=" MSER  ")
        self.notebook.add(frame_other, text=" Other  ")

        self.max_num_feats = max_num_features
        self.selection = None

        self.mser_image = mser_image

        rand_row = random.randint(1, 512 - 200)
        rand_col = random.randint(1, 512 - 110)
        self.mser_area = mser_image[rand_row:rand_row + 180,
                                    rand_col:rand_col + 100]

        # read images from icons folder
        self.hf0_img = PhotoImage(file="./icons/hf0.gif")
        self.hf1_img = PhotoImage(file="./icons/hf1.gif")
        self.hf2_img = PhotoImage(file="./icons/hf2.gif")
        self.hf3_img = PhotoImage(file="./icons/hf3.gif")
        self.hf4_img = PhotoImage(file="./icons/hf4.gif")
        self.hf5_img = PhotoImage(file="./icons/hf5.gif")

        self.features_vars = list()
        for i in range(max_num_features):
            self.features_vars.append(IntVar())

        Label(frame_feats,
              text="Patch size (" + u"\N{GREEK SMALL LETTER PI}" + "):").grid(
                  row=0, column=0, pady=5)
        self.patch_size_spinbox = Spinbox(frame_feats, from_=3, to=30, width=3)
        self.patch_size_spinbox.delete(0, END)
        self.patch_size_spinbox.insert(END, 10)
        self.patch_size_spinbox.grid(row=0, column=1, padx=5)

        f1 = ttk.Labelframe(frame_feats, text='Mean filter')
        f1.grid(row=1, columnspan=2)

        Label(f1, text=u"\N{GREEK SMALL LETTER PI}").grid(row=0, column=0)
        Checkbutton(f1, text="R",
                    variable=self.features_vars[0]).grid(row=0, column=1)
        Checkbutton(f1, text="G",
                    variable=self.features_vars[1]).grid(row=0, column=2)
        Checkbutton(f1, text="B",
                    variable=self.features_vars[2]).grid(row=0, column=3)

        Label(f1, text=u"\N{GREEK SMALL LETTER PI}" + "/2").grid(row=1,
                                                                 column=0)
        Checkbutton(f1, text="R",
                    variable=self.features_vars[3]).grid(row=1, column=1)
        Checkbutton(f1, text="G",
                    variable=self.features_vars[4]).grid(row=1, column=2)
        Checkbutton(f1, text="B",
                    variable=self.features_vars[5]).grid(row=1, column=3)

        f2 = ttk.Labelframe(frame_feats, text="Gaussian filter")
        f2.grid(row=2, columnspan=2)

        Label(f2, text=str(1.0)).grid(row=0, column=0)
        Checkbutton(f2, text="R",
                    variable=self.features_vars[6]).grid(row=0, column=1)
        Checkbutton(f2, text="G",
                    variable=self.features_vars[7]).grid(row=0, column=2)
        Checkbutton(f2, text="B",
                    variable=self.features_vars[8]).grid(row=0, column=3)

        Label(f2, text=str(3.5)).grid(row=1, column=0)
        Checkbutton(f2, text="R",
                    variable=self.features_vars[9]).grid(row=1, column=1)
        Checkbutton(f2, text="G",
                    variable=self.features_vars[10]).grid(row=1, column=2)
        Checkbutton(f2, text="B",
                    variable=self.features_vars[11]).grid(row=1, column=3)

        f3 = ttk.Labelframe(frame_feats, text="Laplacian of gaussian")
        f3.grid(row=3, columnspan=2)

        Label(f3, text=str(2.0)).grid(row=0, column=0)
        Checkbutton(f3, text="R",
                    variable=self.features_vars[12]).grid(row=0, column=1)
        Checkbutton(f3, text="G",
                    variable=self.features_vars[13]).grid(row=0, column=2)
        Checkbutton(f3, text="B",
                    variable=self.features_vars[14]).grid(row=0, column=3)

        Label(f3, text=str(3.5)).grid(row=1, column=0)
        Checkbutton(f3, text="R",
                    variable=self.features_vars[15]).grid(row=1, column=1)
        Checkbutton(f3, text="G",
                    variable=self.features_vars[16]).grid(row=1, column=2)
        Checkbutton(f3, text="B",
                    variable=self.features_vars[17]).grid(row=1, column=3)

        f4 = ttk.Labelframe(frame_feats, text="Haar-like features")
        f4.grid(row=1, rowspan=2, column=3, padx=5)

        Checkbutton(f4, image=self.hf0_img,
                    variable=self.features_vars[18]).grid(row=0, column=0)
        Checkbutton(f4, image=self.hf1_img,
                    variable=self.features_vars[19]).grid(row=0, column=1)
        Checkbutton(f4, image=self.hf2_img,
                    variable=self.features_vars[20]).grid(row=1, column=0)
        Checkbutton(f4, image=self.hf3_img,
                    variable=self.features_vars[21]).grid(row=1, column=1)
        Checkbutton(f4, image=self.hf4_img,
                    variable=self.features_vars[22]).grid(row=2, column=0)
        Checkbutton(f4, image=self.hf5_img,
                    variable=self.features_vars[23]).grid(row=2, column=1)

        buttons_paned_window = PanedWindow(frame_feats, orient=VERTICAL)
        buttons_paned_window.grid(row=3, column=3)

        self.select_all_button = Button(buttons_paned_window,
                                        text="Select all",
                                        command=self._select_all)
        buttons_paned_window.add(self.select_all_button)

        self.clear_selection_button = Button(buttons_paned_window,
                                             text="Clear selection",
                                             command=self._clear_selection)
        buttons_paned_window.add(self.clear_selection_button)

        # default values
        for j in [0, 1, 3, 6, 7, 9, 15, 21, 23]:
            self.features_vars[j].set(1)

        # FOREST FRAMES
        # number of trees
        f5 = ttk.Labelframe(frame_forest, text="Number of trees")
        f5.grid(row=0, columnspan=2, pady=5, padx=5)
        Label(f5, text="N").grid(row=1, column=0)
        self.num_trees_scale = Scale(f5,
                                     from_=5,
                                     to=500,
                                     resolution=5,
                                     orient=HORIZONTAL)
        self.num_trees_scale.set(300)
        self.num_trees_scale.grid(row=0, column=1, rowspan=2)

        # depth single tree
        f6 = ttk.Labelframe(frame_forest, text="Depth single tree")
        f6.grid(row=1, columnspan=2, pady=5, padx=5)
        Label(f6, text="d").grid(row=1, column=0)
        self.depth_tree_scale = Scale(f6, from_=2, to=20, orient=HORIZONTAL)
        self.depth_tree_scale.set(3)
        self.depth_tree_scale.grid(row=0, column=1, rowspan=2)

        # percentage number of features
        f7 = ttk.Labelframe(frame_forest, text="% subset of features")
        f7.grid(row=2, columnspan=2, pady=5, padx=5)
        Label(f7, text="m").grid(row=1, column=0)
        self.percentage_feats_scale = Scale(f7,
                                            from_=0.0,
                                            to=1,
                                            resolution=0.05,
                                            orient=HORIZONTAL)
        self.percentage_feats_scale.set(0.5)
        self.percentage_feats_scale.grid(row=0, column=1, rowspan=2)

        # mser frame
        # delta
        f8 = ttk.Labelframe(frame_mser, text="Delta")
        f8.grid(row=0, columnspan=2, pady=5, padx=5)
        Label(f8, text=u"\N{GREEK SMALL LETTER DELTA}").grid(row=1, column=0)
        self.delta_scale = Scale(f8,
                                 from_=1,
                                 to=10,
                                 resolution=1,
                                 orient=HORIZONTAL)
        self.delta_scale.set(2)
        self.delta_scale.grid(row=0, column=1, rowspan=2)

        # min area
        f9 = ttk.Labelframe(frame_mser, text="Minimum area")
        f9.grid(row=1, columnspan=2, pady=5, padx=5)
        Label(f9, text="m").grid(row=1, column=0)
        self.min_area_scale = Scale(f9, from_=2, to=200, orient=HORIZONTAL)
        self.min_area_scale.set(10)
        self.min_area_scale.grid(row=0, column=1, rowspan=2)

        # percentage number of features
        f10 = ttk.Labelframe(frame_mser, text="Maximum area")
        f10.grid(row=2, columnspan=2, pady=5, padx=5)
        Label(f10, text="M").grid(row=1, column=0)
        self.max_area_scale = Scale(f10,
                                    from_=50,
                                    to=1000,
                                    resolution=5,
                                    orient=HORIZONTAL)
        self.max_area_scale.set(350)
        self.max_area_scale.grid(row=0, column=1, rowspan=2)

        # mser image
        f11 = ttk.Labelframe(frame_mser)
        f11.grid(row=0, rowspan=3, column=2, padx=5)

        self.mser_img_array = Image.fromarray(self.mser_area, "RGB")
        self.mser_img = ImageTk.PhotoImage(self.mser_img_array)

        img_label = Label(f11, image=self.mser_img)
        img_label.grid(row=0, column=0)

        buttons_p_w_mser = PanedWindow(f11, orient=HORIZONTAL)
        try_button = Button(f11, text="Try", command=self.try_mser)
        buttons_p_w_mser.add(try_button)
        change_button = Button(f11, text="New img", command=self.change_mser)
        buttons_p_w_mser.add(change_button)
        buttons_p_w_mser.grid(row=1, column=0)

        # other frame
        f12 = ttk.Labelframe(frame_other, text="Refinement")
        f12.grid(row=0, columnspan=2, pady=5, padx=5)
        Label(f12, text=u"\N{GREEK CAPITAL LETTER PHI}_l").grid(row=1,
                                                                column=0)
        self.low_thresh_scale = Scale(f12,
                                      from_=0,
                                      to=1,
                                      resolution=0.05,
                                      orient=HORIZONTAL,
                                      length=90)
        self.low_thresh_scale.set(0.45)
        self.low_thresh_scale.grid(row=0, column=1, rowspan=2)
        Label(f12, text=u"\N{GREEK CAPITAL LETTER PHI}_h").grid(row=3,
                                                                column=0)
        self.high_thresh_scale = Scale(f12,
                                       from_=0,
                                       to=1,
                                       resolution=0.05,
                                       orient=HORIZONTAL,
                                       length=90)
        self.high_thresh_scale.set(0.65)
        self.high_thresh_scale.grid(row=2, column=1, rowspan=2)

        f13 = ttk.Labelframe(frame_other, text="Dots distance")
        f13.grid(row=1, columnspan=2, pady=5, padx=5)
        Label(f13, text=u"     \N{GREEK SMALL LETTER SIGMA}").grid(row=1,
                                                                   column=0)
        self.dots_distance_scale = Scale(f13,
                                         from_=1,
                                         to=20,
                                         resolution=1,
                                         orient=HORIZONTAL,
                                         length=90)
        self.dots_distance_scale.set(6)
        self.dots_distance_scale.grid(row=0, column=1, rowspan=2)

        f14 = ttk.Labelframe(frame_other, text="Tracks")
        f14.grid(row=0, column=3, pady=5, padx=5)
        Label(f14, text="N").grid(row=1, column=0)
        self.num_frames_tracks_spinbox = Spinbox(f14,
                                                 from_=2,
                                                 to=num_frames,
                                                 width=10)
        self.num_frames_tracks_spinbox.delete(0, END)
        self.num_frames_tracks_spinbox.insert(END, num_frames)
        self.num_frames_tracks_spinbox.grid(row=0, column=1, rowspan=2)

        Label(f14, text=u"\N{GREEK SMALL LETTER TAU}").grid(row=3, column=0)
        self.gaps_scale = Scale(f14,
                                from_=1,
                                to=10,
                                resolution=1,
                                orient=HORIZONTAL,
                                length=90)
        self.gaps_scale.set(2)
        self.gaps_scale.grid(row=2, column=1, rowspan=2)

        self.notebook.pack(padx=1, pady=1)

        save_button = Button(self,
                             text=" Save and Close window ",
                             command=self.withdraw)
        save_button.pack(pady=2)
Пример #29
0
    def refreshWidget(self):
        #print "refresh"
        self.card_win.pack_forget()

        #Card window
        self.card_win = PanedWindow(self.card_win.master, orient=VERTICAL)
        self.card_win.pack(side=TOP, expand=True, fill=BOTH, pady=2, padx=2)

        #Create the name zone
        name_zone = PanedWindow(self.card_win, orient=HORIZONTAL)
        name = StringVar()
        name.set(self.name)
        from deck_creation import blocked_creature

        def modifName(*args):
            old = self.name in blocked_creature
            self.name = name.get()
            if old or self.name in blocked_creature:
                self.refreshWidget()

        name.trace("w", modifName)
        name_wid = Entry(name_zone, width=30, textvariable=name)
        name_wid.pack()
        name_zone.add(name_wid)
        #Create the cost ad star stringvar
        #print int(floor(self.getCost()))
        self.cost = StringVar()
        self.stars = StringVar()
        cost_wid = Label(None,
                         textvariable=self.cost,
                         background='red',
                         width=5,
                         anchor=W)
        star_wid = Label(None,
                         textvariable=self.stars,
                         background='blue',
                         anchor=E)
        self.cost.set(str(int(floor(self.getCost()))))
        self.stars.set("*" * self.getStars())
        #Add them in name zone
        name_zone.add(cost_wid)
        name_zone.add(star_wid)

        #Create an Image Zone
        image_zone = Button(self.card_win, command=self.choosePhoto)
        if hasattr(self, "photofile") and self.photofile:
            print "Image: ", self.photofile
            try:
                img = Image.open(self.photofile)
            except:
                decomp = self.photofile.split('/')
                for i in range(1, 6):
                    try:
                        fname = "/".join(decomp[-i:])
                        print "try to open", fname
                        img = Image.open(fname)
                        self.photofile = fname
                        break
                    except:
                        self.photofile = None
        if self.photofile:
            w, h = img.size
            if w > 300 or h > 200:
                img = img.resize((w / 2, h / 2), Image.LINEAR)
            image_zone.image = ImageTk.PhotoImage(img)
            image_zone.config(image=image_zone.image)
            #print "IMAGE CHANGED"
        else:
            from os import path
            fname = self.name.replace(" ", "_")
            if path.isfile("Cards/" + fname + ".png"):
                image_zone.config(text='image can be taken from\n' + "Cards/" +
                                  fname + ".png",
                                  background='white',
                                  anchor=CENTER)
            else:
                image_zone.config(text='clic to choose image',
                                  background='white',
                                  anchor=CENTER)

        image_zone.pack

        # POWER ZONE
        power_zone = PanedWindow(self.card_win, orient=VERTICAL)

        #fenetre=self.card_win.master
        def removePowerCreator(px):
            def removePower(*args):
                #print 'avant',list_pow
                self.bonus.remove(px)
                #print 'apres',list_pow
                #self.card_win.pack_forget()
                self.refreshWidget()

            return removePower

        for p in self.bonus:
            powline = PanedWindow(self.card_win, orient=HORIZONTAL)
            pow_wid = p.initWidget(powline)
            powline.add(pow_wid)
            removepow = Button(powline,
                               text="X",
                               command=removePowerCreator(p),
                               anchor=E)
            removepow.pack()
            powline.add(removepow)
            power_zone.add(powline)

        def addPower(*args):
            name = addBonus.get()
            print "added :", name
            import cardPowers
            self.bonus += [eval('cardPowers.' + name + '()')]
            self.bonus[-1].parent = self.bonus
            self.bonus[-1].card = self
            #self.card_win.pack_forget()
            self.refreshWidget()

        #Add bonus Option menu
        addBonus = StringVar(power_zone)
        addBonus.set("add bonus")  # default value
        if not self.pv: addBonus_wid = getSpellMenu(power_zone, addBonus)
        else: addBonus_wid = getBonusMenu(power_zone, addBonus)
        addBonus.trace('w', addPower)
        if self.pv > 0 or len(self.bonus) == 0:
            addBonus_wid.pack()
            #Add this to power zone
            power_zone.add(addBonus_wid)

        #Create save zone
        save_zone = PanedWindow(self.card_win, orient=HORIZONTAL)
        lv = int(localopen("progression", "r").read())
        if self.monster_type != "all" and not (lv < 8 and self.name
                                               in blocked_creature):
            save_wid = Button(save_zone, text="Save", command=self.postAndSave)
        elif self.monster_type != "all":
            save_wid = Button(save_zone,
                              text="creature in campaign",
                              command=None)
        else:
            save_wid = Button(save_zone, text="nead type", command=None)
        save_wid.pack()
        #Create the open button
        save_zone.pack()
        if Card.monster_list.keys():
            self.opening = StringVar(save_zone)
            self.opening.set("Open")
            choice = Card.monster_list.keys()
            choice.sort()
            #print all_monsters.keys()
            open_wid = OptionMenu(save_zone, self.opening, *choice)
            self.opening.trace('w', self.Open)
            open_wid.pack()
            save_zone.add(open_wid)

        if Card.monster_list.keys():
            self.delete = StringVar(save_zone)
            self.delete.set("Delete")
            choice = Card.monster_list.keys()
            choice.sort()
            delete_wid = OptionMenu(save_zone, self.delete, *choice)
            self.delete.trace('w', self.clicDelete)
            delete_wid.pack()
            save_zone.add(delete_wid)

        #Create the type button
        self.category = StringVar(save_zone)
        self.category.set(self.monster_type)
        choice = [
            file2name(t, "_monsters.sav")
            for t in glob.glob("CardFiles/*_monsters.sav")
        ]
        if "recup" in choice:
            choice.remove("recup")
        #print all_monsters.keys()
        category_wid = OptionMenu(save_zone, self.category, *choice)
        self.category.trace('w', self.setFile)

        category_wid.pack()

        #Add it to save zone
        save_zone.add(save_wid)
        save_zone.add(category_wid)

        #Create a new Strength zone for att and pv
        strength_zone = PanedWindow(self.card_win, orient=HORIZONTAL)
        att = StringVar()
        att.set(str(self.att))
        pv = StringVar()
        pv.set(str(self.pv))

        def modifiedAttPv(*args):
            print "modifiedAttPv"
            self.pv = int(pv.get())
            if self.pv < 1 and self.is_spell == False:
                if len(self.bonus) == 0:
                    self.is_spell = True
                    self.refreshWidget()
                else:
                    self.pv = 1
                    self.refreshWidget()
            if self.pv > 0 and self.is_spell == True:
                if len(self.bonus) == 0:
                    self.is_spell = False
                    self.refreshWidget()
                else:
                    self.pv = 0
                    self.refreshWidget()
            self.att = int(att.get())
            self.getCost()

        att_wid = Spinbox(strength_zone,
                          from_=0,
                          to=1000,
                          textvariable=att,
                          command=modifiedAttPv)
        att_wid.pack()
        strength_zone.add(att_wid)
        strength_zone.add(
            Label(strength_zone,
                  text='       ',
                  background='white',
                  anchor=CENTER))
        pv_wid = Spinbox(strength_zone,
                         from_=0,
                         to=1000,
                         textvariable=pv,
                         command=modifiedAttPv)
        pv_wid.pack()
        strength_zone.add(pv_wid)

        #Put it all in window
        self.card_win.add(name_zone)
        self.card_win.add(image_zone)
        self.card_win.add(power_zone)
        self.card_win.add(strength_zone)
        self.card_win.add(save_zone)

        self.card_win.pack()
Пример #30
0
class SelectionListbox(Toplevel):
      def __init__(self, parent, objectList):
            Toplevel.__init__(self, parent)
            self.protocol('WM_DELETE_WINDOW', self.destroy)

            self._objectList = objectList
            
            self._lb = Listbox(self, selectmode = SINGLE)
            self._lb.pack()
            self._buttons = PanedWindow(self)

            for i in objectList.getKeysInOrder():
                  self._lb.insert(END, i)

            addButton = Button(self._buttons, text="Add", command=self.onAdd)
            addButton.pack(side=LEFT)

            modifyButton = Button(self._buttons, text="Modify", command=self.onModify)
            modifyButton.pack(side=LEFT)
            
            deleteButton = Button(self._buttons, text="Delete", command=self.onDelete)
            deleteButton.pack(side=LEFT)

            cancelButton = Button(self._buttons, text="Cancel", command=self.onCancel)
            cancelButton.pack(side=RIGHT)

            self._buttons.pack(side=BOTTOM)

      def onAdd(self):
            self._inputPanel = InputPanel(self, self._objectList.getElementKeys(), self.addCallBack)

      def onModify(self):
            ctr = self._lb.curselection()
            key = self._lb.get(ctr)
            print key
            print self._objectList
            self._inputPanel = InputPanel(self, self._objectList.getElementKeys(), self.modifyCallBack, key, self._objectList._resources[key])
            
      def onDelete(self):
            idx = self._lb.curselection()
            self.deleteCallBack(idx)

      def onCancel(self):
            self.destroy()

      def destroy(self):
            Toplevel.destroy(self)
              
      def addCallBack(self, cdict, key):
            print "Add new element"

            key = self._objectList.addFromDict(cdict)
                  
            self._lb.insert(END, key)
            self._lb.update()
            # self._inputPanel.destroy()

      def modifyCallBack(self, cdict, key):
            print "Modify Existing Element"
            print cdict
            print key
            self._objectList.modifyElement(cdict, key)
            print self._objectList._resources[key]
                  
            self._lb.update()
            # self._inputPanel.destroy()

      def deleteCallBack(self, idx):
            print "Delete"
            print idx
            key = self._lb.get(idx)
            self._objectList.deleteElement(key)
            self._lb.delete(idx)
            self._lb.update()
Пример #31
0
class MainWindow(Frame):
    GRAPH_TYPES = OrderedDict([
        ("Prime Graph", graphs.PrimeGraph),
        ("Fast Graph", graphs.FastGraph)
    ])

    def __init__(self, **kw):
        Frame.__init__(self, **kw)
        self.winfo_toplevel().minsize(width=600, height=400)
        width = min(self.winfo_screenwidth(), 1280)
        height = min(self.winfo_screenheight(), 720)
        self.winfo_toplevel().geometry("{}x{}".format(width, height))
        self.pack(expand=True, fill='both')
        self._init_variables()
        self._init_components()
        self._init_menu()

    def _init_components(self):
        self._panes = PanedWindow(self, orient='horizontal', sashrelief="raised")
        self._panes.pack(expand=True, fill='both')

        self._left_pane = Frame(self._panes, padx=10, pady=5)
        self._right_pane = PanedWindow(self._panes)
        self._panes.add(self._left_pane, sticky='n')
        self._panes.add(self._right_pane)

        self._group_select = GroupSelect(self._left_pane)
        self._group_select.pack(expand=True, fill='x')

        # spacer
        Frame(self._left_pane, height=10).pack()

        graph_controls = LabelFrame(self._left_pane, text="Graph options", padx=10, pady=5)
        graph_controls.columnconfigure(1, weight=1)
        graph_controls.pack(expand=True, fill='x')

        self._show_graph_checkbutton = CheckBox(graph_controls, text='Show graph')
        self._show_graph_checkbutton.select()
        self._show_graph_checkbutton.grid(row=0, columnspan=2, sticky='w')

        Label(graph_controls, text='Algorithm').grid(row=1, sticky='w')
        self._graph_type = OptionList(graph_controls, values=MainWindow.GRAPH_TYPES.keys())
        self._graph_type.config(width=15)
        self._graph_type.grid(row=1, column=1, sticky='we')

        # spacer
        Frame(self._left_pane, height=10).pack()

        self._go_button = Button(self._left_pane, text='Go', command=self._go)
        self._go_button.pack()

    def _init_variables(self):
        # init default properties
        self.setvar("graphframeview", "onlyone")
        self.setvar("vertexlabelposition", "auto")

    def _init_menu(self):
        toplevel = self.winfo_toplevel()
        self._menu = Menu(toplevel)
        toplevel['menu'] = self._menu

        view = Menu(self._menu, tearoff=0)
        self._menu.add_cascade(label="View", menu=view)

        graph_view = Menu(view, tearoff=0)
        view.add_cascade(label="View graphs", menu=graph_view)

        graph_view.add_radiobutton(variable="graphframeview", label="Only one", value="onlyone")
        #        graph_view.add_radiobutton(label="In a row", value="row",
        #            variable=graph_view_var)
        graph_view.add_radiobutton(variable="graphframeview", label="In separate window", value="window")

    def _go(self):
        view = self.getvar("graphframeview")

        if view == "onlyone":
            for child in self._right_pane.winfo_children():
                child.destroy()
                #if view in ("onlyone", "row"):
            container = FrameWithCloseButton(self._right_pane)
            self._right_pane.add(container, minsize=600)
        else:
            container = Toplevel()

        graph_class = MainWindow.GRAPH_TYPES[self._graph_type.variable.get()]

        facade = Facade(container, self._group_select.selected_group,
                        show_graph=self._show_graph_checkbutton.is_selected(),
                        graph_class=graph_class)

        facade.pack(expand=True, fill='both')
Пример #32
0
    def __init__(self, master, smart_annotator):
        Toplevel.__init__(self, master)

        self.void_image = np.zeros((100, 100, 3))

        self.smart_annotator = smart_annotator
        self.current_point = None
        self.index_frame = None

        self.pos_data = list()
        self.neg_data = list()

        self.uncertain_dots = list()

        self.current_point_img_array = Image.fromarray(self.void_image, "RGB")
        self.current_point_img = ImageTk.PhotoImage(self.current_point_img_array)

        img_label = Label(self, image=self.current_point_img)
        img_label.pack()

        button_paned_window = PanedWindow(self, orient=HORIZONTAL)
        button_paned_window.pack()

        self.probability_label = Label(self, text="0.0")
        button_paned_window.add(self.probability_label)

        yes_but = Button(self, text="Y", command=self.yes_command)
        button_paned_window.add(yes_but)

        no_but = Button(self, text="N", command=self.no_command)
        button_paned_window.add(no_but)

        maybe_but = Button(self, text="?", command=self.maybe_command)
        button_paned_window.add(maybe_but)

        self.protocol('WM_DELETE_WINDOW', self.intercept_close_action)
Пример #33
0
 def initWidget(self,fenetre) :
     #print "init"
     self.card_win = PanedWindow(fenetre, orient=VERTICAL)
     fenetre.child=self
     self.refreshWidget()
Пример #34
0
    def refreshWidget(self) :
        #print "refresh"
        self.card_win.pack_forget()
        
        #Card window      
        self.card_win = PanedWindow(self.card_win.master, orient=VERTICAL)
        self.card_win.pack(side=TOP, expand=True, fill=BOTH, pady=2, padx=2)
        
        
        #Create the name zone
        name_zone=PanedWindow(self.card_win, orient=HORIZONTAL)
        name = StringVar() 
        name.set(self.name)
        def modifName(*args) :
            self.name=name.get()
        name.trace("w", modifName)
        name_wid=Entry(name_zone, width=30,textvariable=name)
        name_wid.pack()
        name_zone.add(name_wid)
        #Create the cost ad star stringvar
        #print int(floor(self.getCost()))
        self.cost=StringVar()
        self.stars=StringVar()
        cost_wid=Label(None, textvariable=self.cost, background='red',width=5, anchor=W)
        star_wid=Label(None, textvariable=self.stars, background='blue', anchor=E)
        self.cost.set(str(int(floor(self.getCost()))))
        self.stars.set("*"*self.getStars())
        #Add them in name zone
        name_zone.add(cost_wid)
        name_zone.add(star_wid)
        
        
        #Create an Image Zone
        image_zone=Button(self.card_win,  command=self.choosePhoto)
        if hasattr(self,"photofile") and self.photofile :            
            print "Image: ",self.photofile
            try :
               img=Image.open(self.photofile)
            except :
               decomp=self.photofile.split('/')
               for i in range(1,6) :
                   try :
                       fname="/".join(decomp[-i:])
                       print "try to open",fname
                       img=Image.open(fname)
                       self.photofile=fname
                       break
                   except :
                       self.photofile=None
        if self.photofile :
            w, h = img.size
            if w>300 or h>200 :
               img=img.resize((w/2,h/2),Image.LINEAR)
            image_zone.image=ImageTk.PhotoImage(img)
            image_zone.config(image=image_zone.image)
            #print "IMAGE CHANGED"
        else :
            from os import path
            name=self.name.replace(" ","_")
            if path.isfile("Cards/"+name+".png") :
                image_zone.config(text='image can be taken from\n'+"Cards/"+name+".png",background='white',anchor=CENTER)
            else :
                image_zone.config(text='clic to choose image',background='white',anchor=CENTER)

        image_zone.pack
        
        
        # POWER ZONE
        power_zone=PanedWindow(self.card_win, orient=VERTICAL)
        #fenetre=self.card_win.master
        def removePowerCreator(px) :
            def removePower(*args) :
                #print 'avant',list_pow
                self.bonus.remove(px)
                #print 'apres',list_pow
                #self.card_win.pack_forget()
                self.refreshWidget()
            return removePower
        for p in self.bonus :
            powline =  PanedWindow(self.card_win, orient=HORIZONTAL)
            pow_wid=p.initWidget(powline)
            powline.add(pow_wid)
            removepow=Button(powline, text="X", command=removePowerCreator(p), anchor=E)
            removepow.pack()
            powline.add(removepow)
            power_zone.add(powline) 
        def addPower(*args) :
            name=addBonus.get()
            print "added :",name
            import cardPowers
            self.bonus+=[eval('cardPowers.'+name+'()')]
            self.bonus[-1].parent=self.bonus
            self.bonus[-1].card=self
            #self.card_win.pack_forget()
            self.refreshWidget()
        #Add bonus Option menu
        addBonus = StringVar(power_zone)
        addBonus.set("add bonus") # default value
        if not self.pv:  addBonus_wid = getSpellMenu(power_zone, addBonus)
        else: addBonus_wid = getBonusMenu(power_zone, addBonus) 
        addBonus.trace('w', addPower)
        if self.pv>0 or len(self.bonus)==0 :
            addBonus_wid.pack()
            #Add this to power zone
            power_zone.add(addBonus_wid)
        
        #Create save zone
        save_zone = PanedWindow(self.card_win, orient=HORIZONTAL)
        if self.monster_type != "all":
            save_wid = Button(save_zone, text="Save", command=self.postAndSave)
        else:
            save_wid = Button(save_zone, text="---", command=None)
        save_wid.pack()
        #Create the open button
        save_zone.pack()        
        if Card.monster_list.keys():
            self.opening = StringVar(save_zone)
            self.opening.set("Open")
            choice = Card.monster_list.keys()
            choice.sort()
            #print all_monsters.keys()
            open_wid = OptionMenu(save_zone, self.opening,*choice)
            self.opening.trace('w', self.Open)
            open_wid.pack()
            save_zone.add(open_wid)
        
        if Card.monster_list.keys():
            self.delete = StringVar(save_zone)
            self.delete.set("Delete")
            choice = Card.monster_list.keys()
            choice.sort()
            delete_wid = OptionMenu(save_zone, self.delete,*choice)
            self.delete.trace('w', self.clicDelete)
            delete_wid.pack()
            save_zone.add(delete_wid)
        
        #Create the type button
        self.category = StringVar(save_zone)
        self.category.set(self.monster_type)
        choice = [t[t.index("\\")+1:t.index("_monsters.sav")] for t in glob.glob("CardFiles/*_monsters.sav")]
        if "recup" in choice:
            choice.remove("recup")
        #print all_monsters.keys()
        category_wid = OptionMenu(save_zone, self.category,*choice)
        self.category.trace('w', self.setFile)
        
        
        
        category_wid.pack()
        
        #Add it to save zone
        save_zone.add(save_wid)
        save_zone.add(category_wid)
        
        #Create a new Strength zone for att and pv
        strength_zone=PanedWindow(self.card_win, orient=HORIZONTAL)
        att=StringVar()
        att.set(str(self.att))
        pv=StringVar() ; pv.set(str(self.pv))
        def modifiedAttPv(*args) :
            self.pv=int(pv.get())
            if self.pv<1 and self.is_spell==False :
                if len(self.bonus)==0 :
                    self.is_spell=True
                    self.refreshWidget()
                else :
                    self.pv=1
                    self.refreshWidget()
            if self.pv>0 and self.is_spell==True :
                if len(self.bonus)==0 :
                    self.is_spell=False
                    self.refreshWidget()
                else :
                    self.pv=0
                    self.refreshWidget()            
            self.att=int(att.get())
            self.getCost()
        att_wid = Spinbox(strength_zone, from_=0, to=1000,textvariable=att,command=modifiedAttPv)
        att_wid.pack()
        strength_zone.add(att_wid)
        strength_zone.add(Label(strength_zone, text='       ', background='white', 
             anchor=CENTER))
        pv_wid = Spinbox(strength_zone, from_=0, to=1000,textvariable=pv,command=modifiedAttPv)
        pv_wid.pack()
        strength_zone.add(pv_wid)
        
        #Put it all in window
        self.card_win.add(name_zone)
        self.card_win.add(image_zone)
        self.card_win.add(power_zone)  
        self.card_win.add(strength_zone)
        self.card_win.add(save_zone)
        
        
        self.card_win.pack()                      
Пример #35
0
    def _init_components(self):
        self._panes = PanedWindow(self,
                                  orient='horizontal',
                                  sashrelief='raised')
        self._panes.pack(expand=True, fill='both')

        self._left_pane = Frame(self._panes, padx=2, pady=2)
        self._right_pane = Frame(self._panes)
        self._panes.add(self._left_pane, width=250)
        self._panes.add(self._right_pane)

        # group name
        group_name_pane = LabelFrame(self._left_pane,
                                     text="Group",
                                     padx=10,
                                     pady=5)
        group_name_pane.pack(fill='x')

        self._group_name = GroupNameLabel(group_name_pane, self._group)
        self._group_name.pack(expand=True, fill='both')

        # group order
        group_order_pane = LabelFrame(self._left_pane,
                                      text="Order",
                                      padx=10,
                                      pady=5)
        group_order_pane.pack(fill='x')

        self._group_order = IntegerContainer(group_order_pane,
                                             integer=self._group.order())
        self._group_order.pack(expand=True, fill='both')

        # apex
        self._apex_pane = LabelFrame(self._left_pane,
                                     text="Apex",
                                     padx=10,
                                     pady=5)
        self._apex_pane.pack(expand=True, fill='both')

        self._apex_container = ApexListContainer(self._apex_pane,
                                                 apex=self._group.apex())
        self._apex_container.pack(expand=True, fill='both')

        # graph controls
        cocliques_frame = LabelFrame(self._left_pane,
                                     text="Cocliques",
                                     padx=10,
                                     pady=5)
        cocliques_frame.pack(fill='x')

        self._cocliques_button = Button(cocliques_frame,
                                        text="Calculate",
                                        command=self._show_cocliques)
        self._cocliques_button.pack(anchor='nw')

        self._cocliques_container = ListContainer(cocliques_frame)
        self._cocliques_list = Listbox(self._cocliques_container)
        self._cocliques_container.set_listbox(self._cocliques_list)

        # Button(graph_controls, text='Group equivalent vertices').pack(anchor='nw')

        # this is a button that show up instead of graph canvas if we uncheck 'Show graph' checkbox.
        self._show_graph_button = Button(self._right_pane,
                                         text='Show graph',
                                         command=self._show_graph_canvas)
        self._graph_canvas = None
        if self._show_graph:
            self._show_graph_canvas()
        else:
            self._show_graph_button.pack()
Пример #36
0
class Facade(Frame):
    """This is a Frame that contains group info, group order, apex and prime
    graph.
    """
    def __init__(self, parent, group, show_graph=True, graph_class=None, **kw):
        """
        Parameters:
            show_graph: whether to create and show graph instantly or provide a button to do that lately
            graph_factory: callable accepting one argument - the Group instance and returning Graph instance. Note that
                __str__ method of the callable is used in the UI.
        """
        Frame.__init__(self, parent, **kw)
        self._group = group
        #        self._show_apex = True
        self._show_graph = show_graph
        self._graph_class = graph_class
        self._init_variables()
        self._init_menu()
        self._init_components()

    @property
    def group(self):
        return self._group

    @property
    def apex_list_container(self):
        return self._apex_container

    @property
    def graph_canvas(self):
        return self._graph_canvas

    def _show_graph_canvas(self):
        self._show_graph_button.forget()
        # TODO: add different layouts and other options
        graph_class = self._graph_class
        self.graph = graph_class(self._group)
        self._graph_canvas = GraphCanvas(self._right_pane,
                                         SpringLayout(self.graph),
                                         caption=str(graph_class))
        self._graph_canvas.pack(expand=True, fill='both')

        self._graph_canvas.vertex_label_mode = self.getvar(
            name=self.winfo_name() + ".vertexlabelposition")

        self._iterations_plugin = IterationsPlugin()
        self._iterations_plugin.apply(self._graph_canvas)

        self.update_layout()

    def _init_components(self):
        self._panes = PanedWindow(self,
                                  orient='horizontal',
                                  sashrelief='raised')
        self._panes.pack(expand=True, fill='both')

        self._left_pane = Frame(self._panes, padx=2, pady=2)
        self._right_pane = Frame(self._panes)
        self._panes.add(self._left_pane, width=250)
        self._panes.add(self._right_pane)

        # group name
        group_name_pane = LabelFrame(self._left_pane,
                                     text="Group",
                                     padx=10,
                                     pady=5)
        group_name_pane.pack(fill='x')

        self._group_name = GroupNameLabel(group_name_pane, self._group)
        self._group_name.pack(expand=True, fill='both')

        # group order
        group_order_pane = LabelFrame(self._left_pane,
                                      text="Order",
                                      padx=10,
                                      pady=5)
        group_order_pane.pack(fill='x')

        self._group_order = IntegerContainer(group_order_pane,
                                             integer=self._group.order())
        self._group_order.pack(expand=True, fill='both')

        # apex
        self._apex_pane = LabelFrame(self._left_pane,
                                     text="Apex",
                                     padx=10,
                                     pady=5)
        self._apex_pane.pack(expand=True, fill='both')

        self._apex_container = ApexListContainer(self._apex_pane,
                                                 apex=self._group.apex())
        self._apex_container.pack(expand=True, fill='both')

        # graph controls
        cocliques_frame = LabelFrame(self._left_pane,
                                     text="Cocliques",
                                     padx=10,
                                     pady=5)
        cocliques_frame.pack(fill='x')

        self._cocliques_button = Button(cocliques_frame,
                                        text="Calculate",
                                        command=self._show_cocliques)
        self._cocliques_button.pack(anchor='nw')

        self._cocliques_container = ListContainer(cocliques_frame)
        self._cocliques_list = Listbox(self._cocliques_container)
        self._cocliques_container.set_listbox(self._cocliques_list)

        # Button(graph_controls, text='Group equivalent vertices').pack(anchor='nw')

        # this is a button that show up instead of graph canvas if we uncheck 'Show graph' checkbox.
        self._show_graph_button = Button(self._right_pane,
                                         text='Show graph',
                                         command=self._show_graph_canvas)
        self._graph_canvas = None
        if self._show_graph:
            self._show_graph_canvas()
        else:
            self._show_graph_button.pack()

    def _init_variables(self):
        def set_default_var(self, name):
            """Sets widget-specific var with same value as root.
            """
            default_var = self.getvar(name)
            local_var_name = self.winfo_name() + "." + name
            self.setvar(local_var_name, default_var)
            return local_var_name

        local_name = set_default_var(self, "vertexlabelposition")
        tools.trace_variable(self, local_name, "w",
                             self._change_vertex_label_position)

    def _change_vertex_label_position(self, name, *arg):
        # override default value
        self.setvar("vertexlabelposition", self.getvar(name))
        if self._graph_canvas is not None:
            self._graph_canvas.vertex_label_mode = self.getvar(name)

    def _init_menu(self):
        """Init menu bar content.
        """
        toplevel = self.winfo_toplevel()
        if toplevel['menu']:
            self._menu = self.nametowidget(name=toplevel['menu'])
        else:
            self._menu = Menu(toplevel)
            toplevel['menu'] = self._menu

        graph_options = Menu(self._menu, tearoff=0)
        self._menu.add_cascade(label="Graph", menu=graph_options)
        self._menu_index = self._menu.index("end")

        vertex_label_position_menu = Menu(graph_options, tearoff=0)
        graph_options.add_cascade(label="Label position",
                                  menu=vertex_label_position_menu)

        menu_var = self.winfo_name() + ".vertexlabelposition"
        vertex_label_position_menu.add_radiobutton(variable=menu_var,
                                                   label="Auto",
                                                   value="auto")
        vertex_label_position_menu.add_radiobutton(variable=menu_var,
                                                   label="Center",
                                                   value="center")

        graph_options.add_command(label="Save graph...",
                                  command=self.call_graph_save_dialog)

        self.bind("<Destroy>", self.__destroy_menu)

    #noinspection PyUnusedLocal
    def __destroy_menu(self, event):
        try:
            self._menu.delete(self._menu_index)
        except TclError:
            pass

    def _show_cocliques(self):
        cocliques = self.graph.max_cocliques()

        def select_coclique(*_):
            index = next(iter(self._cocliques_list.curselection()), None)
            if index is not None:
                selected = cocliques[int(index)]
                pick_state = self._graph_canvas.picked_vertex_state
                pick_state.clear()
                for value in selected:
                    pick_state.pick(self._graph_canvas.get_vertex(value))

        self._cocliques_list.insert(
            0, *[', '.join(map(str, coclique)) for coclique in cocliques])
        self._cocliques_list.bind("<Double-Button-1>", select_coclique)

        self._cocliques_button.forget()
        self._cocliques_container.pack(expand=True, fill='both')

    def call_graph_save_dialog(self):
        file_name = tkFileDialog.asksaveasfilename(
            defaultextension='.ps',
            filetypes=[('PostScript', '.ps')],
            parent=self.winfo_toplevel(),
            title="Save graph as image")
        if file_name:
            with codecs.open(file_name, 'w', encoding='utf-8') as f:
                f.write(self._graph_canvas.postscript())

    def update_layout(self):
        try:
            self._iterations_plugin.iterate(50)
        except AttributeError:
            pass
Пример #37
0
class Facade(Frame):
    """This is a Frame that contains group info, group order, apex and prime
    graph.
    """

    def __init__(self, parent, group, show_graph=True, **kw):
        Frame.__init__(self, parent, **kw)
        self._group = group
        #        self._show_apex = True
        self._show_graph = show_graph
        self._init_variables()
        self._init_menu()
        self._init_components()


    @property
    def group(self):
        return self._group

    @property
    def apex_list_container(self):
        return self._apex_container

    @property
    def graph_canvas(self):
        return self._graph_canvas

    def _show_graph_canvas(self):
        self._show_graph_button.forget()
        # TODO: add different layouts and other options
        graph = self._group.prime_graph()
        self._graph_canvas = GraphCanvas(self._right_pane, SpringLayout(graph))
        self._graph_canvas.pack(expand=True, fill='both')

        self._graph_canvas.vertex_label_mode = self.getvar(
            name=self.winfo_name() + ".vertexlabelposition")

        self._iterations_plugin = IterationsPlugin()
        self._iterations_plugin.apply(self._graph_canvas)

        self.update_layout()

    def _init_components(self):
        self._panes = PanedWindow(self, orient='horizontal',
            sashrelief='raised')
        self._panes.pack(expand=True, fill='both')

        self._left_pane = Frame(self._panes, padx=2, pady=2)
        self._right_pane = Frame(self._panes)
        self._panes.add(self._left_pane, width=500)
        self._panes.add(self._right_pane)

        # group name
        group_name_pane = LabelFrame(self._left_pane, text="Group")
        group_name_pane.pack(fill='x')

        self._group_name = GroupNameLabel(group_name_pane, self._group)
        self._group_name.pack(expand=True, fill='both')

        # group order
        group_order_pane = LabelFrame(self._left_pane, text="Order")
        group_order_pane.pack(fill='x')

        self._group_order = IntegerContainer(group_order_pane,
            integer=self._group.order())
        self._group_order.pack(expand=True, fill='both')

        # apex
        self._apex_pane = LabelFrame(self._left_pane, text="Apex")
        self._apex_pane.pack(expand=True, fill='both')

        self._apex_container = ApexListContainer(self._apex_pane,
            apex=self._group.apex())
        self._apex_container.pack(expand=True, fill='both')

        self._show_graph_button = Button(self._right_pane, text='Show graph',
            command=self._show_graph_canvas)
        self._graph_canvas = None
        if self._show_graph:
            self._show_graph_canvas()
        else:
            self._show_graph_button.pack()

    def _init_variables(self):
        def set_default_var(self, name):
            """Sets widget-specific var with same value as root.
            """
            default_var = self.getvar(name)
            local_var_name = self.winfo_name() + "." + name
            self.setvar(local_var_name, default_var)
            return local_var_name

        local_name = set_default_var(self, "vertexlabelposition")
        tools.trace_variable(self, local_name, "w",
            self._change_vertex_label_position)

    def _change_vertex_label_position(self, name, *arg):
        # override default value
        self.setvar("vertexlabelposition", self.getvar(name))
        if self._graph_canvas is not None:
            self._graph_canvas.vertex_label_mode = self.getvar(name)


    def _init_menu(self):
        toplevel = self.winfo_toplevel()
        if toplevel['menu']:
            self._menu = self.nametowidget(name=toplevel['menu'])
        else:
            self._menu = Menu(toplevel)
            toplevel['menu'] = self._menu

        graph_options = Menu(self._menu, tearoff=0)
        self._menu.add_cascade(label="Graph", menu=graph_options)
        self._menu_index = self._menu.index("end")

        vertex_label_position = Menu(graph_options, tearoff=0)
        graph_options.add_cascade(label="Label position",
            menu=vertex_label_position)

        vertexlabelposition_var = self.winfo_name() + ".vertexlabelposition"
        vertex_label_position.add_radiobutton(label="Auto", value="auto",
            variable=vertexlabelposition_var)
        vertex_label_position.add_radiobutton(label="Center", value="center",
            variable=vertexlabelposition_var)

        graph_options.add_command(label="Save graph...",
            command=self.call_graph_save_dialog)

        self.bind("<Destroy>", self.__destroy_menu)

    #noinspection PyUnusedLocal
    def __destroy_menu(self, event):
        try:
            self._menu.delete(self._menu_index)
        except TclError:
            pass

    def call_graph_save_dialog(self):
        file_name = tkFileDialog.asksaveasfilename(defaultextension='.ps',
            filetypes=[('PostScript', '.ps')], parent=self.winfo_toplevel(),
            title="Save graph as image")
        if file_name:
            with codecs.open(file_name, 'w', encoding='utf-8') as file:
                file.write(self._graph_canvas.postscript())


    def update_layout(self):
        try:
            self._iterations_plugin.iterate(50)
        except AttributeError:
            pass
Пример #38
0
    def initTextBoxes(self):
        panedWindow = PanedWindow(self.parent, width=DIM_X, height=(DIM_Y - TOOLBAR_Y)/2+5, relief=FLAT)


	# left-hand side: text box for the user to type into, plus a scrollbar
        leftPanel = Frame(panedWindow)
        scrollbar = Scrollbar(leftPanel, orient=VERTICAL)
        self.textEditor = Text(leftPanel, background="PaleTurquoise", width=MAX_CHARS, font=self.customFont2,
                               wrap=WORD, height=(DIM_Y - TOOLBAR_Y)/2, yscrollcommand=scrollbar.set,
                               selectbackground="Turquoise")
        self.textEditor.bind("<<Modified>>", self.textEditorModified)
        self.resettingModifiedFlag = False
	
	# add a scrollbar to the left-hand box
	scrollbar.config(command=self.textEditor.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.textEditor.pack(side=LEFT, fill=BOTH, expand=1)
        panedWindow.add(leftPanel)

	# right hand side: help box, plus buttons to see different help screens
	
	rightPanel = Frame(panedWindow)
	scrollbar1 = Scrollbar(rightPanel, orient=VERTICAL)
	boxPanel = Frame(rightPanel, width=DIM_Y/2, height=DIM_X - 2*TOOLBAR_Y)
        self.helpBox = Text(boxPanel, background="LemonChiffon", font=self.customFont2, selectbackground="Gold",
                            wrap=WORD, height=15, yscrollcommand=scrollbar1.set)
        
        # add a scrollbar to the right-hand box
	scrollbar1.config(command=self.helpBox.yview)
        scrollbar1.pack(side=RIGHT, fill=Y)
        self.helpBox.pack(expand=1)
        boxPanel.pack()

        # add buttons to help box
	helpboxWidth = self.helpBox.winfo_reqwidth()
        buttonBar = Frame(rightPanel, relief=FLAT, background="LemonChiffon", height=BUTTON_Y, width=helpboxWidth)

        img = Image.open("Graphics/backArrow.png")
        self.backImg = ImageTk.PhotoImage(img)
        prevButton =     Button(buttonBar, relief=RAISED, background="LemonChiffon", image=self.backImg, borderwidth=1,
                                activebackground="Turquoise", height=BUTTON_Y, command=self.prevScreen)
        prevButton.image = self.backImg
        
        img = Image.open("Graphics/yourCode.png")
        self.codeImg = ImageTk.PhotoImage(img)
        yourCodeButton = Button(buttonBar, relief=RAISED, background="LemonChiffon", image=self.codeImg, borderwidth=1,
                                activebackground="Turquoise", height=BUTTON_Y, command=self.lastScreen)
        yourCodeButton.image = self.codeImg

        img = Image.open("Graphics/nextArrow.png")
        self.nextImg = ImageTk.PhotoImage(img)
        nextButton =     Button(buttonBar, relief=RAISED, background="LemonChiffon", image=self.nextImg, borderwidth=1,
                                activebackground="Turquoise", height=BUTTON_Y, command=self.nextScreen)
        nextButton.image = self.nextImg

	prevButton.pack(side=LEFT)
	nextButton.pack(side=RIGHT)
	yourCodeButton.pack(padx=103)

	buttonBar.pack(fill=X)
	
	# set up tags to highlight errors in the text editor and do syntax highlighting
	self.textEditor.tag_config("error", background="OrangeRed", foreground="White")
	
	self.helpBox.tag_config("bold", font=self.boldFont)
	self.helpBox.tag_config("ital", font=self.italFont)
	self.helpBox.tag_config("underline", underline=1)
	self.helpBox.tag_config("code", font=self.boldFont, foreground="DarkViolet")
	
        panedWindow.add(rightPanel)
        panedWindow.pack(fill=BOTH, expand=1)
class AntroidGUI(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.protocol("WM_DELETE_WINDOW", self.myquit)
        self.etat = True
        self.readstate = True
        self.title("Antroid Map")
        self.turns = {}
        self.selectTurn = -1
        self.caselength = 10
        self.CaseMarge = 20
        self.var = StringVar()
        self.initGUI()

    def initGUI(self):
        frame = Frame(self, width=630, height=500)
        self.panel = PanedWindow(frame, orient=HORIZONTAL)

        self.LeftFrame(self.panel)
        self.RightFrame(self.panel)
        self.panel.add(self.LFrame)
        self.panel.add(self.RFrame)
        self.panel.pack()
        frame.pack()

    def LeftFrame(self, parent):
        self.LFrame = Frame(parent, width=500, height=500)
        self.maptroid = Canvas(self.LFrame, bg='black', width=500, height=500)
        if self.selectTurn >= 0:
            self.printMap()

        self.maptroid.pack()
        self.LFrame.pack()

    def RightFrame(self, parent):
        self.RFrame = Frame(parent, width=130, height=500)
        if self.selectTurn >= 0:
            self.printInfo()
        self.FrameInfo = None
        self.updateT = True
        self.RFrame.pack()

    def setreadstate(self, readstate):
        self.readstate = readstate

    def addTurn(self, turnnumber, turnvalue):
        self.turns[turnnumber] = turnvalue
        self.updateGui(turnnumber)
        return self.etat

    def updateGui(self, turn):
        self.selectTurn = turn
        self.updateMap()
        self.updateInfo()

    def updateMap(self):
        self.maptroid.delete(ALL)
        self.printMap()

    def updateInfo(self):
        if self.FrameInfo:
            if self.updateT:
                self.frameT.destroy()
                self.printTurn()
            self.frameAnts.destroy()
            self.frameAnt.destroy()
            self.printAnts()
            self.updateT = True
        else:
            self.printInfo()

    def updateSpin_turn(self):
        turn = int(self.Spin_T.get())
        self.updateT = False
        self.updateGui(turn)

    def validateTurn(self, event):
        try:
            turn = int(self.Spin_T.get())
        except ValueError:
            turn = self.selectTurn
        if turn in self.turns.keys():
            if turn != self.selectTurn:
                self.updateT = False
                self.updateGui(turn)
        else:
            turn = self.selectTurn

    def choiceAnt(self, event):
        i = self.listbox.curselection()
        id_a = self.listbox.get(i)
        self.frameAnt.destroy()
        self.printInfoAnt(int(id_a))

    def printInfo(self):
        self.FrameInfo = Frame(self.RFrame)
        self.printTurn()
        self.printAnts()
        self.FrameInfo.pack()

    def printTurn(self):
        frameS = PanedWindow(self.FrameInfo, orient=HORIZONTAL)
        turns = Label(frameS, text="Tour :")
        self.var.set(str(self.selectTurn))
        self.Spin_T = Spinbox(frameS,
                              values=self.turns.keys(),
                              command=self.updateSpin_turn,
                              textvariable=self.var)
        self.Spin_T.bind('<Return>', self.validateTurn)
        turns.pack()
        self.Spin_T.pack()
        frameS.add(turns)
        frameS.add(self.Spin_T)
        frameS.pack()
        self.frameT = frameS

    def printAnts(self):
        frameAnts = Frame(self.FrameInfo)
        Text_A = Label(frameAnts, text="Fourmie :")
        s1 = Scrollbar(frameAnts)
        l1 = Listbox(frameAnts)
        id_ants = self.checkAnts()
        for i in id_ants:
            l1.insert(i, str(i))
        s1.config(command=l1.yview)
        l1.config(yscrollcommand=s1.set)
        l1.bind('<ButtonRelease-1>', self.choiceAnt)
        self.listbox = l1
        Text_A.pack(side=TOP)
        l1.pack(side=LEFT)
        s1.pack(side=RIGHT)
        frameAnts.pack()

        self.printInfoAnt(id_ants[0])
        self.frameAnts = frameAnts

    def printInfoAnt(self, i):
        self.frameAnt = PanedWindow(self.FrameInfo, orient=VERTICAL)
        t_Ant = Label(self.frameAnt, text="Information Ant : %d" % (i))
        (t_brain, t_energie, t_acide) = self.getInfoAnt(i)
        a_b = Label(self.frameAnt, text=t_brain)
        a_e = Label(self.frameAnt, text=t_energie)
        a_a = Label(self.frameAnt, text=t_acide)
        t_Ant.pack(side=TOP)
        self.frameAnt.add(t_Ant)
        self.frameAnt.add(a_b)
        self.frameAnt.add(a_e)
        self.frameAnt.add(a_a)
        self.frameAnt.pack()

    def printMap(self):
        turn = self.turns[self.selectTurn]
        # Information on this turn
        config = turn[0]
        Yants = turn[1]
        EAnts = turn[2]
        InitMap = turn[3]
        Cases = turn[4]

        (MaxX, MaxY, N) = InitMap
        self.MinX = 0
        self.MinY = 0
        MaxX_map = MaxX * self.caselength + (self.CaseMarge * 2)
        MaxY_map = MaxY * self.caselength + (self.CaseMarge * 2)
        #configure canvas
        self.maptroid.config(scrollregion=(0, 0, MaxX_map, MaxY_map))
        x1 = self.CaseMarge
        y1 = self.CaseMarge
        x2 = MaxX * self.caselength + self.CaseMarge
        y2 = MaxY * self.caselength + self.CaseMarge
        self.maptroid.create_rectangle(x1, y1, x2, y2, fill="white")

        # affiche case
        for case in Cases:
            self.printCase(case)
        # affiche your ants
        for ant in Yants:
            # nb A : Your Ant 'ID X Y DX DY E A B'
            (id_a, x, y, dx, dy, e, a, b) = ant
            self.printAnt((x, y, dx, dy, b))
        # affiche enemy ants
        for ant in EAnts:
            self.printAnt(ant)

        #to move map
        self.maptroid.bind('<ButtonPress-1>', self.grab)
        self.maptroid.bind('<B1-Motion>', self.drag)
        self.maptroid.bind('<MouseWheel>', self.mapZoom)
        self.maptroid.bind("<Button-4>", self.mapZoom)
        self.maptroid.bind("<Button-5>", self.mapZoom)

    def printCase(self, case):
        (x, y, c, s) = case
        (x1, y1, x2, y2) = self.getPoint(x, y)
        color = COLOR[c][s]
        if c % 2 == 0:
            self.maptroid.create_rectangle(x1, y1, x2, y2, fill=color)
        else:
            self.maptroid.create_rectangle(x1,
                                           y1,
                                           x2,
                                           y2,
                                           fill=COLOR[GRASS][s])
            self.maptroid.create_oval(x1, y1, x2, y2, fill=color)

    def printAnt(self, ant):
        (x, y, dx, dy, brain) = ant
        (x1, y1, x2, y2) = self.getPoint(x, y)
        self.maptroid.create_oval(x1, y1, x2, y2, fill="red4")

    def getPoint(self, x, y):
        x1 = (x - self.MinX) * self.caselength + self.CaseMarge
        y1 = (y - self.MinY) * self.caselength + self.CaseMarge
        x2 = x1 + self.caselength
        y2 = y1 + self.caselength
        return (x1, y1, x2, y2)

    def grab(self, event):
        self._y = event.y
        self._x = event.x

    def drag(self, event):
        self.maptroid.yview('scroll', self._y - event.y, 'units')
        self.maptroid.xview('scroll', self._x - event.x, 'units')
        self._y = event.y
        self._x = event.x

    def mapZoom(self, event):
        # respond to Linux or Windows wheel event
        if event.num == 5 or event.delta == -120:
            self.caselength -= 5
            self.caselength = max(self.caselength, 10)
        if event.num == 4 or event.delta == 120:
            self.caselength += 5
            self.caselength = min(self.caselength, 40)
        self.CaseMarge = self.caselength
        self.updateMap()

    def getInfoAnt(self, id_ant):
        turn = self.turns[self.selectTurn]
        YAnt = turn[1]
        B_Text = "Brain :"
        E_Text = "Energie :"
        A_Text = "Acide :"
        for ant in YAnt:
            (id_a, x, y, dx, dy, e, a, b) = ant
            if b != 1:
                b = 0
            if (id_ant == id_a):
                B_Text = "Brain : " + BRAIN[b]
                E_Text = "Energie : %d" % (e)
                A_Text = "Acide : %d" % (a)

        return (B_Text, E_Text, A_Text)

    def checkAnts(self):
        turn = self.turns[self.selectTurn]
        YAnt = turn[1]
        ants_id = []
        for ant in YAnt:
            (id_a, x, y, dx, dy, e, a, b) = ant
            ants_id.append(id_a)
        return ants_id

    def myquit(self):
        self.etat = False
        if not self.readstate:
            self.quit()
Пример #40
0
class ClsGUI(Tk):
    """
    Попытка создать ГУИ для репортера.
    """

    def __init__(self):
        """
        Создаёт интерфейс пользователя для репортера.
        """
        def bind_win():
            """
            Привязка событий к окнам.
            """

            def quit_reporter(event=''):
                """
                Выходит из репортера.
                :param event:
                """
                import sys
                sys.exit()

            def save_reporter(event=''):
                """
                Сохраняет отчёт.
                :param event:
                """
                print '===report==='
                _reporter = ClsSmallReporter()
                self.txt_report.insert('1.0', _reporter.html_data)

            def generate_report(event=''):
                """
                Генерирует отчёт.
                :param event:
                """
                print '===report==='
                reporter = ClsSmallReporter()
                self.txt_report.insert('1.0', reporter.html_data)

            self.bind('<Control-Q>', quit_reporter)
            self.bind('<Control-q>', quit_reporter)

            self.bind('<Control-S>', save_reporter)
            self.bind('<Control-s>', save_reporter)

            self.bind('<Control-G>', generate_report)
            self.bind('<Control-g>', generate_report)

        Tk.__init__(self)
        self.frm_up = Frame(self)
        self.mnu_file = None
        self.mnu_custom = None
        self.btn_exit = None
        self.mnu_help = None
        self.mnu_edit = None
        self.txt_report = None
        self.btn_edit = None
        self.btn_save = None
        self.pnl_menu = None
        self.btn_custom = None
        self.btn_generate = None
        self.btn_file = None
        self.btn_help = None
        self.frm_midle = None
        self.frm_down = None

        self.title(LANG_RU['win_main'])
        self.minsize(GEOMETRY['winMain_minSizeX'], GEOMETRY['winMain_minSizeY'])
        self.maxsize(GEOMETRY['winMain_maxSizeX'], GEOMETRY['winMain_maxSizeY'])
        self.create_up_frame()
        self.create_frm_middle()
        self.create_frm_down()
        bind_win()
        self.mainloop()

    def create_up_frame(self):
        """
        Создаёт верхний фрейм.
        :type self: object
        """
        self.create_menu_bar()
        self.frm_up.pack(side='top', fill='x')

    def create_frm_middle(self):
        """
        Создаёт средний фрейм для отображения.
        """
        self.frm_midle = Frame(self, border=2, relief='raised')
        self.frm_midle.pack(side='top', expand=1, fill='both')
        self.txt_report = Text(self.frm_midle, font='Consolas 9 normal')
        self.txt_report.pack(side='top', fill='both', expand=1)


    def create_frm_down(self):
        """
        Создаёт нижний фрейм репортера.
        """

        def btn_generate_click(event=''):
            """
            Обработчик нижатия кнопки генератора отчёта.
            :param event:
            """
            print '===report==='
            _reporter = ClsSmallReporter()
            self.txt_report.insert('1.0', _reporter.html_data)

        def create_btn_exit():
            """
            Создаёт кнопки выхода из программы.
            """

            def report_exit(event=''):
                """
                Обработчик нажатия кнопки выхода из программы.
                :param event:
                """
                import sys

                sys.exit()

            self.btn_exit = Button(self.frm_down,
                                   text=LANG_RU['btn_exit'],
                                   command=report_exit,
                                   bg='red')
            self.btn_exit.pack(side='left', expand=1, fill='x')

        def create_btn_save():
            """
            Создаёт кнопку для сохранения отчёта.
            """
            self.btn_save = Button(self.frm_down, text=LANG_RU['btn_save'])
            self.btn_save.pack(side='left', expand=1, fill='x')

        def create_btn_generate():
            """
            Создаёт кнопку для генерации отчёта
            """
            self.btn_generate = Button(self.frm_down,
                                       text=LANG_RU['btn_generate'],
                                       command=btn_generate_click)
            self.btn_generate.pack(side='left', expand=1, fill='x')

        self.frm_down = Frame(self)

        create_btn_generate()
        create_btn_save()
        create_btn_exit()

        self.frm_down.pack(side='bottom', fill='x')

    def create_menu_bar(self):
        """
        Создаёт линейку для меню программы.
        """

        def create_mnu_file():
            """
            Создаёт меню файл.
            """
            self.btn_file = Menubutton(self.pnl_menu, text=LANG_RU['mnu_file'],
                                       border=3, relief='groove')
            self.mnu_file = Menu(self.btn_file)
            self.btn_file.config(menu=self.mnu_file)
            self.mnu_file.add_command(label=LANG_RU['mnuFile_New'],
                                      accelerator='Ctrl+N')
            self.mnu_file.add_command(label=LANG_RU['mnuFile_Open'],
                                      accelerator='Ctrl+O')
            self.mnu_file.add_separator()
            self.mnu_file.add_command(label=LANG_RU['mnuFile_Save'],
                                      accelerator='Ctrl+S')
            self.mnu_file.add_command(label=LANG_RU['mnuFile_SaveAs'])
            self.mnu_file.add_separator()
            self.mnu_file.add_command(label=LANG_RU['mnuFile_Print'],
                                      accelerator='Ctrl+P')
            self.mnu_file.add_separator()
            self.mnu_file.add_command(label=LANG_RU['mnuFile_Exit'],
                                      accelerator='Ctrl+Q')
            self.btn_file.pack(side='left')

        def create_mnu_edit():
            """
            Создаёт меню "Правка".
            """
            self.btn_edit = Menubutton(self.pnl_menu,
                                       text=LANG_RU['mnu_edit'],
                                       border=3,
                                       relief='groove')
            self.mnu_edit = Menu(self.btn_edit)
            self.btn_edit.config(menu=self.mnu_edit)
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Undo'],
                                      accelerator='Ctrl+Z')
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Redo'])
            self.mnu_edit.add_separator()
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Copy'],
                                      accelerator='Ctrl+C')
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Cut'],
                                      accelerator='Ctrl+X')
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Paste'],
                                      accelerator='Ctrl+V')
            self.mnu_edit.add_separator()
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Find'],
                                      accelerator='Ctrl+F')
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Replace'],
                                      accelerator='Ctrl+R')
            self.btn_edit.pack(side='left')

        def create_mnu_custom():
            """
            Создаёт меню нстроек.
            """
            self.btn_custom = Menubutton(self.pnl_menu, text='mnu_custom',
                                         border=3, relief='groove')
            self.mnu_custom = Menu(self.btn_custom)
            self.btn_custom.config(menu=self.mnu_custom)
            self.mnu_custom.add_command(label='Type files',
                                        accelerator='Ctrl+D')
            self.mnu_custom.add_command(label='--1')
            self.mnu_custom.add_separator()
            self.mnu_custom.add_command(label='--2', accelerator='---')
            self.mnu_custom.add_command(label='--3', accelerator='---')
            self.mnu_custom.add_command(label='--4', accelerator='---')
            self.mnu_custom.add_separator()
            self.btn_custom.pack(side='left')

        def create_mnu_help():
            """
            Создаёт меню "Справка".
            """
            self.btn_help = Menubutton(self.pnl_menu,
                                       text='mnu_help',
                                       border=3,
                                       relief='groove')
            self.mnu_help = Menu(self.btn_help)
            self.btn_help.config(menu=self.mnu_help)
            self.mnu_help.add_command(label='Type files', accelerator='Ctrl+D')
            self.mnu_help.add_command(label='--1')
            self.mnu_custom.add_separator()
            self.btn_help.pack(side='left')

        self.pnl_menu = PanedWindow(self.frm_up, border=2, relief='raised')
        create_mnu_file()
        create_mnu_edit()
        create_mnu_custom()
        create_mnu_help()

        self.pnl_menu.pack(side='left', expand=1, fill='x')
Пример #41
0
 def initWidget(self, fenetre):
     #print "init"
     self.card_win = PanedWindow(fenetre, orient=VERTICAL)
     fenetre.child = self
     self.refreshWidget()
Пример #42
0
    def __init__(self, *args, **kwargs):
        '''
nodeName:   The name of this node. Usually set by ModelNode.__setattr__ automatically.
figureMeta: Meta information of figure.
The rest parameters are passed to PanedWindow.__init__.
'''
        nodeName = kwargs.pop('nodeName', '')
        # lock

        super(FigureBook, self).__init__(nodeName=nodeName)

        figureMeta = None if 'figureMeta' not in kwargs \
            else kwargs.pop('figureMeta')
        kwargs['orient'] = HORIZONTAL

        panedWindow = PanedWindow(*args, **kwargs)

        panedWindow.config(sashwidth=4, sashrelief=GROOVE, bg='forestgreen')

        #        figureTabsStyle = Style()
        #        figureTabsStyle.configure('Figure.TNotebook', tabposition='sw')
        #        figureTabs    = Notebook(panedWindow, style='Figure.TNotebook')
        figureTabs = Notebook(panedWindow)

        self.figureTabs = figureTabs
        figureTabs.bind('<<NotebookTabChanged>>', self.onTabChange)
        self.lockAttribute('figureTabs')

        if figureMeta:
            self.makeFigures(figureMeta)

        self.lockElements()

        panedWindow.add(figureTabs, stretch='always')

        listPan = PanedWindow(panedWindow, orient=VERTICAL)
        listPan.config(sashwidth=4, sashrelief=GROOVE, bg='forestgreen')
        panedWindow.add(listPan, stretch='never')

        listFrm = Frame(listPan)
        listPan.add(listFrm, stretch='always')
        Label(listFrm, text='Curves', bg='#b5d6b0').pack(side=TOP, fill=X)
        self.__list = ScrolledList(listFrm, relief=GROOVE)
        self.__list.listConfig(width=20)
        self.__list.listClick = self.onListClick
        self.__list.pack(fill=BOTH, expand=YES)

        listFrm = Frame(listPan)
        listPan.add(listFrm, stretch='never')
        Label(listFrm, text='Indicators', bg='#b5d6b0').pack(side=TOP, fill=X)
        self.__indicatorListbox = ScrolledList(listFrm, relief=GROOVE)
        self.__indicatorListbox.listConfig(width=20)
        self.__indicatorListbox.pack(fill=BOTH, expand=YES)

        with self.attributeLock:
            setMultiAttr(
                self,
                panedWindow=panedWindow,
                gridGroupObserver=self.GridGroupObserver(self),
                axisGroupObserver=self.AxisGroupObserver(self),
                clearGroupObserver=self.ClearGroupObserver(self),
                labelGroupObserver=self.LabelGroupObserver(self),
                indicatorGroupObserver=self.IndicatorGroupObserver(self),
                dataFigureObserver=self.DataFigureObserver(self),
                dataPool=[])
Пример #43
0
class Card:
    def __init__(self,
                 name="Nom monstre",
                 att=1,
                 pv=1,
                 bonus=None,
                 photo='',
                 monster_type="unknown"):
        self.name = name
        self.att = att
        self.pv = pv
        if not bonus:
            bonus = [
            ]  # a cause du fonctionnement etrange de python pour les valeurs d arguments [] par defaut
        self.bonus = bonus
        self.is_spell = (pv < 1)
        self.photofile = photo
        self.dumping_file = os.path.join("CardFiles",
                                         monster_type + "_monsters.sav")
        self.monster_type = monster_type
        #global all_monsters
        name = self.name.replace(" ", "_")
#        try :
#            self.image = image.load(os.path.join("Card",name+".png"))
#        except :
#            self.image=None

    def constructor(self):
        return ('Card("' + self.name + '",' + str(self.att) + "," +
                str(self.pv) + ",[" +
                ",".join([p.constructor() for p in self.bonus]) + "]," +
                repr(self.photofile) + ",'" + self.monster_type + "')")

    def takePlace(self, *ar1, **ars):
        pass

    def addBonus(self, bonus):
        self.bonus.append(bonus)

    def getCost(self):
        if self.pv > 0:
            cost = self.att / 2. + self.pv / 2. + sum(
                [p.getCost(self) for p in self.bonus])
        else:
            #print self.bonus
            #if self.bonus :
            #print self.bonus[0].getCost
            #print self.bonus[0].getCost()
            if len(self.bonus) > 1: print "** anomalie **"
            cost = sum([p.getCost()
                        for p in self.bonus]) + 0.5 * (len(self.bonus) - 1)
        if cost < 0: cost = 0
        if hasattr(self, "cost") and self.cost != None:
            # pour les monstres du save, l attribut cost est None
            print "cout=", cost, " so ", int(floor(cost))
            self.cost.set(int(floor(cost)))
            self.getStars()
        return cost

    def getStars(self):
        stars = sum([p.getStars() for p in self.bonus])
        if stars > 2: stars = (stars - 1) * 2
        if hasattr(self, "stars") and self.stars != None:
            # pour les monstres du save, l attribut stars existe = None
            self.stars.set('* ' * stars)
        #print "stars=",stars
        return stars

    def getDescription(self):
        for b in reversed(self.bonus):
            try:
                b.getDescription()
            except Exception:
                self.bonus.remove(b)
        return self.name + " (" + str(self.att) + "  " + str(
            self.pv) + '\n' * bool(self.bonus) + '\n'.join(
                [b.getDescription() for b in self.bonus]) + " )"

    def getInlineDescription(self):
        for b in reversed(self.bonus):
            try:
                b.getInlineDescription()
            except Exception:
                self.bonus.remove(b)
        return self.name + " (" + str(self.att) + "  " + str(
            self.pv) + ' '.join([b.getInlineDescription()
                                 for b in self.bonus]) + " )"

    def postAndSave(self, *args):
        if self.name == "nom monstre":
            return
        if not self.verifyBonus():
            return
        self.deleteCreature(self.name)
        temp = self.category.get()
        pygame.init()
        fenetre = self.card_win.master
        self.card_win.pack_forget()
        self.save(None)

        done = False
        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
        pygame.display.quit()
        self = Card("nom monstre", 1, 1)
        #card.pack_forget()
        self.initWidget(fenetre)
        self.category.set(temp)
        self.setFile("dummy_arg")

    def verifyBonus(self):
        nb = [b.__class__.__name__ for b in self.bonus]
        if len(set(nb)) != len(nb):
            showinfo("Not Allowed", "You can't have twice the same bonus")
            return False
        for b1, b2 in [("Insaisissable", "Provocation"),
                       ("Insaisissable", "Inciblable"),
                       ("Camouflage", "Provocation"),
                       ("NePeutPasAttaquer", "ALaPlaceDeLAttaque"),
                       ("GardienDeVie", "QuandIlEstBlesse"),
                       ("Charge", "NePeutPasRisposter"),
                       ("NePeutPasRiposter", "NePeutPasAttaquer"),
                       ("NePeutPasRiposter", "CoutReduit"),
                       ("CoutReduit", "NePeutPasAttaquer")]:
            if b1 in nb and b2 in nb:
                showinfo(
                    "Not Allowed",
                    "You can't have this combination of powers: {0} and {1}".
                    format(b1, b2))
                return False
        return True

    def save(self, *args):

        image = self.createImage()

        print "apres createImage"
        name = self.name.replace(" ", "_")
        pygame.image.save(image, "Cards/" + name + ".png")
        print "save image done"
        # now new monster
        loaded_monsters = readMonsters(self.dumping_file)
        #print "Monsters from file = ",file_monsters
        #remove_widget(self)
        loaded_monsters[self.name] = self
        #print "Monsters from file (after) = ",file_monsters
        global all_monsters
        all_monsters.update(loaded_monsters)
        #print "window reinit done"
        with open(self.dumping_file, "wb") as savefile:
            savefile.write("\n".join(
                [m.constructor() for m in loaded_monsters.values()]))


#        with open(self.dumping_file+".old","rb") as filepickle :
#            print "now in file", self.dumping_file,":",pickle.load(filepickle).keys()
#            filepickle.close()
        with open(os.path.join("CardFiles", "all_monsters.sav"), "wb") as f:
            f.write("\n".join([m.constructor()
                               for m in all_monsters.values()]))
        recupfile = os.path.join("CardFiles", "recup_monsters.sav")
        if (not os.path.isfile(recupfile)) or len(all_monsters) >= len(
                open(recupfile, 'r').readlines()):
            with open(recupfile, "wb") as f:
                f.write("\n".join(
                    [m.constructor() for m in all_monsters.values()]))
            print "SAVED in all_monsters.sav and recup_monsters.sav"
        else:
            print "WARNING : Recup monster file bigger than all monsters file"

    def initWidget(self, fenetre):
        #print "init"
        self.card_win = PanedWindow(fenetre, orient=VERTICAL)
        fenetre.child = self
        self.refreshWidget()

    def Open(self, *args):
        print "open monster ", self.opening.get()
        #deck_with_card =  self.deck_check(self.opening.get())
        if True:
            self.card_win.pack_forget()
            fenetre = self.card_win.master
            #for i in Card.monster_list.keys() :
            #    print i, Card.monster_list[i].getInlineDescription()
            self = Card.monster_list[self.opening.get()]
            print self.name + " loaded"
            if self.pv < 1:
                self.is_spell = True
            else:
                self.is_spell = False
            #self.card_win.pack_forget()
            for b in self.bonus:
                b.parent = self.bonus
                b.card = self
            self.initWidget(fenetre)

    def clicDelete(self, *args):
        #self.card_win.pack_forget()
        #fenetre=self.card_win.master
        """
        for i in all_monsters.keys() :
            print i, all_monsters[i].getInlineDescription()
            
        """

        creature = self.delete.get()
        from deck_creation import blocked_creature
        if creature in blocked_creature:
            print "not possible : creature in campaign"
            self.delete.set('delete')
            return
        if askyesno('Beware!', 'Confirm the deletion of ' + creature + "?"):
            self.deleteCreature(creature)
        self.card_win.pack_forget()
        #self.initWidget(fenetre)
        self.setFile(*args)

    def deleteCreature(self, creature):
        dm = None
        global all_monsters
        if not creature in all_monsters:
            print creature, " is not in all_monsters"
            try:
                fm = os.path.join("CardFiles",
                                  self.category.get() + "_monsters.sav")
                dm = readMonsters(fm)
            except:
                print "error reading file ", fm
        else:
            print "delete monster ", creature
            try:
                fm = os.path.join("CardFiles",
                                  (all_monsters[creature].monster_type) +
                                  "_monsters.sav")
                dm = readMonsters(fm)
            except:
                print "ERROR : no type for ", creature, " or read error"
            del all_monsters[creature]
            fall = os.path.join("CardFiles", "all_monsters.sav")
            with open(fall, "wb") as savefile:
                savefile.write("\n".join(
                    [m.constructor() for m in all_monsters.values()]))
            print "deletion of monster ", creature, "done"
            shutil.copyfile(fall, "CardFiles/recup_monsters.sav")
        if dm and creature in dm:
            del dm[creature]
            with open(fm, "wb") as savefile:
                savefile.write("\n".join(
                    [m.constructor() for m in dm.values()]))
            print "deletion of monster ", creature, " in ", fm, " done"
        else:
            print creature, " not found in dedicated file"

    def choosePhoto(self, *args):
        from tkFileDialog import askopenfilename
        #Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
        filename = askopenfilename(
            defaultextension=".gif",
            filetypes=[('Jpg file', '*.jpg'), ('GIF file', '*.gif')]
        )  # show an "Open" dialog box and return the path to the selected file
        if filename:
            import os.path
            chem = os.path.dirname(os.path.realpath(__file__)).replace(
                '\\', '/') + '/'
            print chem
            if chem in filename:
                filename = filename.replace(chem, '')
                print "filename modif", filename
            try:
                Image.open(filename)
                #ImageTk.PhotoImage(monimage)
                self.photofile = filename
                print "photo choosen !"
            except Exception:
                print "echec ouverture"
        self.refreshWidget()

    def setFile(self, *args):
        self.dumping_file = os.path.join("CardFiles",
                                         self.category.get() + "_monsters.sav")
        print "Change dumping file to ", self.dumping_file
        self.monster_type = self.category.get()
        Card.monster_list = readMonsters(self.dumping_file)
        #from cardPowers import *
        self.refreshWidget()

    def refreshWidget(self):
        #print "refresh"
        self.card_win.pack_forget()

        #Card window
        self.card_win = PanedWindow(self.card_win.master, orient=VERTICAL)
        self.card_win.pack(side=TOP, expand=True, fill=BOTH, pady=2, padx=2)

        #Create the name zone
        name_zone = PanedWindow(self.card_win, orient=HORIZONTAL)
        name = StringVar()
        name.set(self.name)
        from deck_creation import blocked_creature

        def modifName(*args):
            old = self.name in blocked_creature
            self.name = name.get()
            if old or self.name in blocked_creature:
                self.refreshWidget()

        name.trace("w", modifName)
        name_wid = Entry(name_zone, width=30, textvariable=name)
        name_wid.pack()
        name_zone.add(name_wid)
        #Create the cost ad star stringvar
        #print int(floor(self.getCost()))
        self.cost = StringVar()
        self.stars = StringVar()
        cost_wid = Label(None,
                         textvariable=self.cost,
                         background='red',
                         width=5,
                         anchor=W)
        star_wid = Label(None,
                         textvariable=self.stars,
                         background='blue',
                         anchor=E)
        self.cost.set(str(int(floor(self.getCost()))))
        self.stars.set("*" * self.getStars())
        #Add them in name zone
        name_zone.add(cost_wid)
        name_zone.add(star_wid)

        #Create an Image Zone
        image_zone = Button(self.card_win, command=self.choosePhoto)
        if hasattr(self, "photofile") and self.photofile:
            print "Image: ", self.photofile
            try:
                img = Image.open(self.photofile)
            except:
                decomp = self.photofile.split('/')
                for i in range(1, 6):
                    try:
                        fname = "/".join(decomp[-i:])
                        print "try to open", fname
                        img = Image.open(fname)
                        self.photofile = fname
                        break
                    except:
                        self.photofile = None
        if self.photofile:
            w, h = img.size
            if w > 300 or h > 200:
                img = img.resize((w / 2, h / 2), Image.LINEAR)
            image_zone.image = ImageTk.PhotoImage(img)
            image_zone.config(image=image_zone.image)
            #print "IMAGE CHANGED"
        else:
            from os import path
            fname = self.name.replace(" ", "_")
            if path.isfile("Cards/" + fname + ".png"):
                image_zone.config(text='image can be taken from\n' + "Cards/" +
                                  fname + ".png",
                                  background='white',
                                  anchor=CENTER)
            else:
                image_zone.config(text='clic to choose image',
                                  background='white',
                                  anchor=CENTER)

        image_zone.pack

        # POWER ZONE
        power_zone = PanedWindow(self.card_win, orient=VERTICAL)

        #fenetre=self.card_win.master
        def removePowerCreator(px):
            def removePower(*args):
                #print 'avant',list_pow
                self.bonus.remove(px)
                #print 'apres',list_pow
                #self.card_win.pack_forget()
                self.refreshWidget()

            return removePower

        for p in self.bonus:
            powline = PanedWindow(self.card_win, orient=HORIZONTAL)
            pow_wid = p.initWidget(powline)
            powline.add(pow_wid)
            removepow = Button(powline,
                               text="X",
                               command=removePowerCreator(p),
                               anchor=E)
            removepow.pack()
            powline.add(removepow)
            power_zone.add(powline)

        def addPower(*args):
            name = addBonus.get()
            print "added :", name
            import cardPowers
            self.bonus += [eval('cardPowers.' + name + '()')]
            self.bonus[-1].parent = self.bonus
            self.bonus[-1].card = self
            #self.card_win.pack_forget()
            self.refreshWidget()

        #Add bonus Option menu
        addBonus = StringVar(power_zone)
        addBonus.set("add bonus")  # default value
        if not self.pv: addBonus_wid = getSpellMenu(power_zone, addBonus)
        else: addBonus_wid = getBonusMenu(power_zone, addBonus)
        addBonus.trace('w', addPower)
        if self.pv > 0 or len(self.bonus) == 0:
            addBonus_wid.pack()
            #Add this to power zone
            power_zone.add(addBonus_wid)

        #Create save zone
        save_zone = PanedWindow(self.card_win, orient=HORIZONTAL)
        lv = int(localopen("progression", "r").read())
        if self.monster_type != "all" and not (lv < 8 and self.name
                                               in blocked_creature):
            save_wid = Button(save_zone, text="Save", command=self.postAndSave)
        elif self.monster_type != "all":
            save_wid = Button(save_zone,
                              text="creature in campaign",
                              command=None)
        else:
            save_wid = Button(save_zone, text="nead type", command=None)
        save_wid.pack()
        #Create the open button
        save_zone.pack()
        if Card.monster_list.keys():
            self.opening = StringVar(save_zone)
            self.opening.set("Open")
            choice = Card.monster_list.keys()
            choice.sort()
            #print all_monsters.keys()
            open_wid = OptionMenu(save_zone, self.opening, *choice)
            self.opening.trace('w', self.Open)
            open_wid.pack()
            save_zone.add(open_wid)

        if Card.monster_list.keys():
            self.delete = StringVar(save_zone)
            self.delete.set("Delete")
            choice = Card.monster_list.keys()
            choice.sort()
            delete_wid = OptionMenu(save_zone, self.delete, *choice)
            self.delete.trace('w', self.clicDelete)
            delete_wid.pack()
            save_zone.add(delete_wid)

        #Create the type button
        self.category = StringVar(save_zone)
        self.category.set(self.monster_type)
        choice = [
            file2name(t, "_monsters.sav")
            for t in glob.glob("CardFiles/*_monsters.sav")
        ]
        if "recup" in choice:
            choice.remove("recup")
        #print all_monsters.keys()
        category_wid = OptionMenu(save_zone, self.category, *choice)
        self.category.trace('w', self.setFile)

        category_wid.pack()

        #Add it to save zone
        save_zone.add(save_wid)
        save_zone.add(category_wid)

        #Create a new Strength zone for att and pv
        strength_zone = PanedWindow(self.card_win, orient=HORIZONTAL)
        att = StringVar()
        att.set(str(self.att))
        pv = StringVar()
        pv.set(str(self.pv))

        def modifiedAttPv(*args):
            print "modifiedAttPv"
            self.pv = int(pv.get())
            if self.pv < 1 and self.is_spell == False:
                if len(self.bonus) == 0:
                    self.is_spell = True
                    self.refreshWidget()
                else:
                    self.pv = 1
                    self.refreshWidget()
            if self.pv > 0 and self.is_spell == True:
                if len(self.bonus) == 0:
                    self.is_spell = False
                    self.refreshWidget()
                else:
                    self.pv = 0
                    self.refreshWidget()
            self.att = int(att.get())
            self.getCost()

        att_wid = Spinbox(strength_zone,
                          from_=0,
                          to=1000,
                          textvariable=att,
                          command=modifiedAttPv)
        att_wid.pack()
        strength_zone.add(att_wid)
        strength_zone.add(
            Label(strength_zone,
                  text='       ',
                  background='white',
                  anchor=CENTER))
        pv_wid = Spinbox(strength_zone,
                         from_=0,
                         to=1000,
                         textvariable=pv,
                         command=modifiedAttPv)
        pv_wid.pack()
        strength_zone.add(pv_wid)

        #Put it all in window
        self.card_win.add(name_zone)
        self.card_win.add(image_zone)
        self.card_win.add(power_zone)
        self.card_win.add(strength_zone)
        self.card_win.add(save_zone)

        self.card_win.pack()

    def createImage(self, black=False):
        width = 189 * 2
        height = 277 * 2
        screen = pygame.display.set_mode((width, height))

        print "Type = ", self.monster_type
        if self.monster_type in all_backgrounds.keys():
            try:
                bg = pygame.image.load(all_backgrounds[self.monster_type])
            except:
                print "error (? when load of bg"
        else:
            bg = pygame.image.load('gameAnimationImages/Card_face_avant.gif')
        #fond = PhotoImage(file =bg,master=fenetre)
        #ligne1 = canvas.create_line(75, 0, 75, 120)
        #ligne2 = canvas.create_line(0, 60, 150, 60)
        if self.photofile and not black:
            try:
                img = pygame.image.load(self.photofile)
            except:
                decomp = self.photofile.split('/')
                for i in range(1, 6):
                    try:
                        fname = "/".join(decomp[-i:])
                        print "try to open", fname
                        img = pygame.image.load(fname)
                        self.photofile = fname
                        break
                    except:
                        pass
            img = pygame.image.load(self.photofile)
            w, h = img.get_size()
            factor = max(140. * 2. / w, 90. * 2. / h)
            img = pygame.transform.scale(img,
                                         (int(w * factor), int(h * factor)))
            #fenetre.photo=PhotoImage(file=self.photofile,master=canvas)
            #img=ImageTk.PhotoImage(img,master=fenetre)
            screen.blit(img,
                        (width / 2. - w * factor / 2., 140. - h * factor / 4.))
        else:
            try:
                name = self.name.replace(" ", "_")
                img = pygame.image.load("Cards/" + name + ".png")
                print "* Found for image ", "Cards/" + name + ".png"
                screen.blit(img, (0, 0))
            except:
                pass
        screen.blit(bg, (0, 0))

        pygame.font.init()
        #print  pygame.font.get_fonts()
        if self.monster_type in white_font_types:
            color = (255, 255, 255)
        else:
            color = (0, 0, 0)
        centerText(screen, (width / 2. + 10., 33. * 2.), self.name,
                   36 - (len(self.name) > 11) * (len(self.name) - 11) / 3,
                   color)
        #txt = canvas.create_text(101, 32, text=self.name, font=("Calibri",12-(len(self.name)>11)*(len(self.name)-11)/5,"bold"), anchor=CENTER)
        if not (self.is_spell):
            centerText(screen, (24 * 2., 258 * 2.), str(self.att), 40, color)
            centerText(screen, (169 * 2., 255 * 2.), str(self.pv), 40, color)
        else:
            centerText(screen, (width / 2., 265 * 2.), "SPELL", 30, color)
        #elif self.is_spell:
        #    txt = canvas.create_text(100,265, text="SPELL", anchor=CENTER, font=("Calibri",14,'bold'))
        #txt = canvas.create_text(22,35, text=int(floor(self.getCost())), anchor=CENTER, font=("Calibri",18,'bold'))
        centerText(screen, (22 * 2., 35 * 2.), str(int(floor(self.getCost()))),
                   50, color)
        #txt1 = canvas.create_text(92,257, text='*'*self.getStars(), anchor=CENTER, font=("Calibri",26,'bold'))
        centerText(screen, (92 * 2., 257 * 2.), '*' * self.getStars(), 60,
                   color)
        if not (self.monster_type == "unknown"):
            if self.monster_type in all_type_colors:
                Color = all_type_colors[self.monster_type]
            else:
                Color = "human"
        else:
            Color = "human"
        centerText(screen, (95 * 2., 142 * 2.), self.monster_type.capitalize(),
                   26, Color)

        if len(self.bonus) > 0:
            powers = "e%96".join([b.getDescription() for b in self.bonus])
            powers = [p.split("\n") for p in powers.split("e%96")]
            print "powers are ", powers
        else:
            powers = ""
        #print "POWERS = ", powers
        if powers:
            space = min([80., 160. / sum([len(p) * 3 + 2 for p in powers])])
            print "Space: ", space
        line = 0
        for i, b in enumerate(powers):
            size = min([36., 500. / max([len(p) for p in b]) * 2.])
            for x, part in enumerate(b):
                centerText(screen, (90 * 2., 167 * 2. + line * space), part,
                           int(size), color)
                line += 3
            line += 2
        #canvas.pack()
        #print "toto!"
        pygame.display.flip()
        return screen

    def init_as_invocation(self, master):
        # monster widget in invocation widget
        #print "monster init_as_invocation"
        self.content = StringVar()
        self.content.set(self.name)
        self.content.trace("w", self.is_changed_as_invocation)
        l = Card.monster_list.keys()
        """
        if self.parent.name in l:
            l.remove(self.parent.name)
        """
        self.widget = OptionMenu(master, self.content, *l)
        return self.widget

    def is_changed_as_invocation(self, *args):
        print "monster is_changed_as_invocation"
        if self.content.get() != "Troll gris":
            new = Card.monster_list[self.content.get()]
        else:
            new = Card("Troll gris", 4, 4)

        #print self.content.get()
        if self.parent:
            #parent.spell=new
            #print "self.parent = True"
            self.parent.monster = new
            new.parent = self.parent
            new.card = self.card
        else:
            raise "ce cas existe ?! me dire comment"
            self.bonus[self.bonus.index(self)] = new
        #self.card_win.pack_forget()
        self.card.refreshWidget()
Пример #44
0
    def __init__(self, *args, **kwargs):
        """
nodeName:   The name of this node. Usually set by ModelNode.__setattr__ automatically.
figureMeta: Meta information of figure.
The rest parameters are passed to PanedWindow.__init__.
"""
        nodeName = kwargs.pop("nodeName", "")
        # lock

        super(FigureBook, self).__init__(nodeName=nodeName)

        figureMeta = None if "figureMeta" not in kwargs else kwargs.pop("figureMeta")
        kwargs["orient"] = HORIZONTAL

        panedWindow = PanedWindow(*args, **kwargs)

        panedWindow.config(sashwidth=4, sashrelief=GROOVE, bg="forestgreen")

        #        figureTabsStyle = Style()
        #        figureTabsStyle.configure('Figure.TNotebook', tabposition='sw')
        #        figureTabs    = Notebook(panedWindow, style='Figure.TNotebook')
        figureTabs = Notebook(panedWindow)

        self.figureTabs = figureTabs
        figureTabs.bind("<<NotebookTabChanged>>", self.onTabChange)
        self.lockAttribute("figureTabs")

        if figureMeta:
            self.makeFigures(figureMeta)

        self.lockElements()

        panedWindow.add(figureTabs, stretch="always")

        listPan = PanedWindow(panedWindow, orient=VERTICAL)
        listPan.config(sashwidth=4, sashrelief=GROOVE, bg="forestgreen")
        panedWindow.add(listPan, stretch="never")

        listFrm = Frame(listPan)
        listPan.add(listFrm, stretch="always")
        Label(listFrm, text="Curves", bg="#b5d6b0").pack(side=TOP, fill=X)
        self.__list = ScrolledList(listFrm, relief=GROOVE)
        self.__list.listConfig(width=20)
        self.__list.listClick = self.onListClick
        self.__list.pack(fill=BOTH, expand=YES)

        listFrm = Frame(listPan)
        listPan.add(listFrm, stretch="never")
        Label(listFrm, text="Indicators", bg="#b5d6b0").pack(side=TOP, fill=X)
        self.__indicatorListbox = ScrolledList(listFrm, relief=GROOVE)
        self.__indicatorListbox.listConfig(width=20)
        self.__indicatorListbox.pack(fill=BOTH, expand=YES)

        with self.attributeLock:
            setMultiAttr(
                self,
                panedWindow=panedWindow,
                gridGroupObserver=self.GridGroupObserver(self),
                axisGroupObserver=self.AxisGroupObserver(self),
                clearGroupObserver=self.ClearGroupObserver(self),
                labelGroupObserver=self.LabelGroupObserver(self),
                indicatorGroupObserver=self.IndicatorGroupObserver(self),
                dataFigureObserver=self.DataFigureObserver(self),
                dataPool=[],
            )
Пример #45
0
    def __init__(self, data, master=None):
        PanedWindow.__init__(self, master=master)
        self.data = data

        self.create_widgets()
        self.pack(fill="both", expand="yes")
Пример #46
0
 def _on_configure_pane(self, sash_index):
     x, y = Tk_PanedWindow.sash_coord(self, sash_index)
     self._handle_list[sash_index].place(x=x)
Пример #47
0
 def __init__(self, parent, pack_location=None, **kwargs):
     pw.__init__(self, parent, **kwargs)
     if pack_location:
         self.pack(side=pack_location, fill='both', expand=True)
     self.elements = {}
Пример #48
0
class Card :
    def __init__(self,name,att,pv) :
        self.name=name
        self.att = att
        self.pv = pv
        self.bonus=[]
        self.is_spell=False
        self.photofile=None
        self.dumping_file = "CardFiles/unknown_monsters.sav"
        self.monster_type = "unknown"
        global all_monsters
        name=self.name.replace(" ","_")
        try :
            self.image = image.load("Card/"+name+".png")
        except :
            self.image=None
    def takePlace(self,*ar1,**ars) :
        pass
    def addBonus(self,bonus) :
        self.bonus.append(bonus)
    def getCost(self) :
        if self.pv > 0 :
            cost=self.att/2.+self.pv/2.+sum([p.getCost(self) for p in self.bonus])
        else :
            #print self.bonus
            #if self.bonus :
            #print self.bonus[0].getCost
            #print self.bonus[0].getCost()           
            if len(self.bonus)>1 : print "** anomalie **"
            cost=sum([p.getCost() for p in self.bonus])+0.5*(len(self.bonus)-1)
        if cost < 0:            cost = 0
        if hasattr(self,"cost") and self.cost!=None :
            # pour les monstres du save, l attribut cost est None        
            print "cout=",cost," so ",int(floor(cost))
            self.cost.set(int(floor(cost)))
            self.getStars()
        return cost
    def getStars(self):
        stars = sum([p.getStars() for p in self.bonus])
        if stars>2 : stars=(stars-1)*2
        if hasattr(self,"stars")  and self.stars != None :
            # pour les monstres du save, l attribut stars existe = None
            self.stars.set('* '*stars)
        #print "stars=",stars
        return stars
    def getDescription(self):
        for b in reversed(self.bonus) :
            try :
                b.getDescription()
            except Exception :
                self.bonus.remove(b)
        return self.name +" ("+str(self.att)+"  "+str(self.pv)+'\n'*bool(self.bonus)+'\n'.join(
            [b.getDescription() for b in self.bonus]) +" )"
    def getInlineDescription(self):
        for b in reversed(self.bonus) :
            try :
                b.getInlineDescription()
            except Exception :
                self.bonus.remove(b)
        return self.name +" ("+str(self.att)+"  "+str(self.pv)+' '.join(
            [b.getInlineDescription() for b in self.bonus]) +" )"
    def postAndSave(self,*args):
        if self.name=="nom monstre" :
            return
        if not self.verifyBonus() :
            return            
        self.deleteCreature(self.name)
        temp=self.category.get()
        pygame.init()
        fenetre=self.card_win.master
        self.card_win.pack_forget()
        self.save(None)
        

        done=False
        while not done :
            for event in pygame.event.get() :
                if event.type == pygame.QUIT :
                    done=True
        pygame.display.quit()
        self = Card("nom monstre",1,1)
        #card.pack_forget()
        self.initWidget(fenetre)
        self.category.set(temp)
        self.setFile("dummy_arg")

    def verifyBonus(self) :
        nb=[b.__class__.__name__ for b in self.bonus]
        if len(set(nb))!=len(nb) :
            showinfo("Not Allowed","You can't have twice the same bonus")
            return False
        for b1,b2 in [("Insaisissable","Provocation"),("Insaisissable","Inciblable"),
                      ("Camouflage","Provocation"),("NePeutPasAttaquer","ALaPlaceDeLAttaque"),
                    ("GardienDeVie","QuandIlEstBlesse")] :
            if b1 in nb and b2 in nb :
                showinfo("Not Allowed","You can't have this combination of powers: {0} and {1}".format(b1,b2))
                return False
        return True
 
    def save(self,*args):

        image = self.createImage()
        
        print "apres createImage"
        name=self.name.replace(" ","_")
        pygame.image.save(image,"Cards/"+name+".png")
        print "save image done"
        # now new monster
        global all_monsters
        with open(self.dumping_file,"rb") as filepickle :
            loaded_monsters = pickle.load(filepickle)
            filepickle.close()
        #print "Monsters from file = ",file_monsters
        remove_widget(self)
        loaded_monsters[self.name] = self
        #print "Monsters from file (after) = ",file_monsters
        all_monsters.update(loaded_monsters)
        print "window reinit done"
        with open(self.dumping_file,"wb") as filepickle :
            pickle.dump(loaded_monsters , filepickle,2 )
        with open(self.dumping_file,"rb") as filepickle :
            print "now in file", self.dumping_file,":",pickle.load(filepickle).keys()
            filepickle.close()
        with open("CardFiles/all_monsters.sav", "wb" ) as f :    
            pickle.dump(all_monsters , f ,2)
            f.close()
        import os.path
        if not os.path.isfile("CardFiles/recup_monsters.sav") or len(all_monsters)>=len(pickle.load(open("CardFiles/recup_monsters.sav","rb"))):
            shutil.copyfile("CardFiles/all_monsters.sav","CardFiles/recup_monsters.sav")
            print "SAVED in all_monsters.sav and recup_monsters.sav"
        else:
            print len(pickle.load(open("CardFiles/recup_monsters.sav","rb")))
            import time
            print "sleep"
            time.sleep(1) 
            shutil.copyfile("CardFiles/recup_monsters.sav","CardFiles/all_monsters.sav")
            pickle.dump(all_monsters , open( "CardFiles/all_monsters.sav", "wb" ),2 )
            all_monsters = pickle.load(open( "CardFiles/all_monsters.sav", "rb" ))
            print "ERROR IN ALL MONSTERS"


    def initWidget(self,fenetre) :
        #print "init"
        self.card_win = PanedWindow(fenetre, orient=VERTICAL)
        fenetre.child=self
        self.refreshWidget()
    def Open(self,*args) :
        print "open monster ",  self.opening.get()        
        lv = int(open("progression","r").read())
        deck_with_card =  self.deck_check(self.opening.get())
        if not(lv<8 and any(["Decks\\"+d.replace(" ","_")+".dek" in deck_with_card for d in blocked_decks])):            
            self.card_win.pack_forget()
            fenetre=self.card_win.master
            #for i in Card.monster_list.keys() :
            #    print i, Card.monster_list[i].getInlineDescription()
            self = Card.monster_list[self.opening.get()]
            print self.name +" loaded"
            if not("CardFiles" in self.dumping_file):
                self.dumping_file = "CardFiles\\"+self.dumping_file
            if self.pv<1 :
                self.is_spell=True
            else :
                self.is_spell=False
            #self.card_win.pack_forget()
            for b in self.bonus:
                b.parent = self.bonus
                b.card = self
            self.initWidget(fenetre)
        else:
            self.opening.set("Open")
            showinfo("Impossible","You can't open this card as it is in a deck of the Campaign")
        #self.refreshWidget()
        
    def clicDelete(self,*args) :
        #self.card_win.pack_forget()
        #fenetre=self.card_win.master
        """
        for i in all_monsters.keys() :
            print i, all_monsters[i].getInlineDescription()
            
        """
        
        creature= self.delete.get()
        if askyesno('Beware!', 'Confirm the deletion of '+creature+"?"):
            check = self.deck_check(creature)
            if not(check):                
                self.deleteCreature(creature)
            else:
                showinfo("Erreur","Impossible de detruire la creature car elle est dans "+",".join(check))
        self.card_win.pack_forget()
        #self.initWidget(fenetre)
        self.setFile(*args)
    
    def deck_check(self,creature):
        decks = glob.glob("Decks\\*.dek")
        content = []
        for d in decks:
            print "deck",d
            with open(d,"r") as fil: # problem with python : I wanted to use "rb"
                deck = pickle.load(fil)
                if creature in deck.keys():
                    content.append(d)
        return content

    def deleteCreature(self,creature) :
        global all_monsters
        if not creature in all_monsters :
            print creature," not in all_monsters"
            try :
                f="CardFiles/"+self.category.get()+"_monsters.sav"
                d = pickle.load(open(f,"rb"))
                del d[creature]
                pickle.dump(d,open(f,"wb"),2)
            except:
                pass
        else :
            print "delete monster ",  creature
            if hasattr(all_monsters[creature],"dumping_file") :
                files = glob.glob(all_monsters[creature].dumping_file)
            else:
                files=None
            if files :
                f = pickle.load(open(files[0],"rb"))
                try:
                    del f[creature]
                    pickle.dump(f,open(files[0],"wb"),2)
                    print "Deleted in ",files[0]
                except:
                    print "Error in deletion in dumping (dedicated) file"    
            else :
                if hasattr(all_monsters[creature],"dumping_file") :
                    print all_monsters[creature].dumping_file," not found"
                else :
                    print "no dumping file"
            del all_monsters[creature]
            pickle.dump(all_monsters , open( "CardFiles/all_monsters.sav", "wb" ),2 )
            print "deletion of monster ",  creature, "done"
            shutil.copyfile("CardFiles/all_monsters.sav","CardFiles/recup_monsters.sav")
        #print all_monsters.keys()
        
    def choosePhoto(self,*args) :
        from tkFileDialog import askopenfilename
        #Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
        filename = askopenfilename(defaultextension=".gif",filetypes=[('Jpg file','*.jpg'),('GIF file','*.gif')]) # show an "Open" dialog box and return the path to the selected file
        if filename:
            import os.path
            chem=os.path.dirname(os.path.realpath(__file__)).replace('\\','/')+'/'
            print chem
            if chem in filename :
                filename=filename.replace(chem,'')
                print "filename modif",filename
            try :
                Image.open(filename)
                #ImageTk.PhotoImage(monimage)
                self.photofile=filename
                print "photo choosen !"
            except Exception :
                print "echec ouverture"
        self.refreshWidget()
    
    def setFile(self,*args):
        self.dumping_file = "CardFiles/"+self.category.get()+"_monsters.sav"
        print "Change dumping file to ",self.dumping_file
        self.monster_type = self.category.get()
        with open( self.dumping_file, "rb") as f:
            Card.monster_list = pickle.load( f)
            f.close()
        self.refreshWidget()

    def refreshWidget(self) :
        #print "refresh"
        self.card_win.pack_forget()
        
        #Card window      
        self.card_win = PanedWindow(self.card_win.master, orient=VERTICAL)
        self.card_win.pack(side=TOP, expand=True, fill=BOTH, pady=2, padx=2)
        
        
        #Create the name zone
        name_zone=PanedWindow(self.card_win, orient=HORIZONTAL)
        name = StringVar() 
        name.set(self.name)
        def modifName(*args) :
            self.name=name.get()
        name.trace("w", modifName)
        name_wid=Entry(name_zone, width=30,textvariable=name)
        name_wid.pack()
        name_zone.add(name_wid)
        #Create the cost ad star stringvar
        #print int(floor(self.getCost()))
        self.cost=StringVar()
        self.stars=StringVar()
        cost_wid=Label(None, textvariable=self.cost, background='red',width=5, anchor=W)
        star_wid=Label(None, textvariable=self.stars, background='blue', anchor=E)
        self.cost.set(str(int(floor(self.getCost()))))
        self.stars.set("*"*self.getStars())
        #Add them in name zone
        name_zone.add(cost_wid)
        name_zone.add(star_wid)
        
        
        #Create an Image Zone
        image_zone=Button(self.card_win,  command=self.choosePhoto)
        if hasattr(self,"photofile") and self.photofile :            
            print "Image: ",self.photofile
            try :
               img=Image.open(self.photofile)
            except :
               decomp=self.photofile.split('/')
               for i in range(1,6) :
                   try :
                       fname="/".join(decomp[-i:])
                       print "try to open",fname
                       img=Image.open(fname)
                       self.photofile=fname
                       break
                   except :
                       self.photofile=None
        if self.photofile :
            w, h = img.size
            if w>300 or h>200 :
               img=img.resize((w/2,h/2),Image.LINEAR)
            image_zone.image=ImageTk.PhotoImage(img)
            image_zone.config(image=image_zone.image)
            #print "IMAGE CHANGED"
        else :
            from os import path
            name=self.name.replace(" ","_")
            if path.isfile("Cards/"+name+".png") :
                image_zone.config(text='image can be taken from\n'+"Cards/"+name+".png",background='white',anchor=CENTER)
            else :
                image_zone.config(text='clic to choose image',background='white',anchor=CENTER)

        image_zone.pack
        
        
        # POWER ZONE
        power_zone=PanedWindow(self.card_win, orient=VERTICAL)
        #fenetre=self.card_win.master
        def removePowerCreator(px) :
            def removePower(*args) :
                #print 'avant',list_pow
                self.bonus.remove(px)
                #print 'apres',list_pow
                #self.card_win.pack_forget()
                self.refreshWidget()
            return removePower
        for p in self.bonus :
            powline =  PanedWindow(self.card_win, orient=HORIZONTAL)
            pow_wid=p.initWidget(powline)
            powline.add(pow_wid)
            removepow=Button(powline, text="X", command=removePowerCreator(p), anchor=E)
            removepow.pack()
            powline.add(removepow)
            power_zone.add(powline) 
        def addPower(*args) :
            name=addBonus.get()
            print "added :",name
            import cardPowers
            self.bonus+=[eval('cardPowers.'+name+'()')]
            self.bonus[-1].parent=self.bonus
            self.bonus[-1].card=self
            #self.card_win.pack_forget()
            self.refreshWidget()
        #Add bonus Option menu
        addBonus = StringVar(power_zone)
        addBonus.set("add bonus") # default value
        if not self.pv:  addBonus_wid = getSpellMenu(power_zone, addBonus)
        else: addBonus_wid = getBonusMenu(power_zone, addBonus) 
        addBonus.trace('w', addPower)
        if self.pv>0 or len(self.bonus)==0 :
            addBonus_wid.pack()
            #Add this to power zone
            power_zone.add(addBonus_wid)
        
        #Create save zone
        save_zone = PanedWindow(self.card_win, orient=HORIZONTAL)
        if self.monster_type != "all":
            save_wid = Button(save_zone, text="Save", command=self.postAndSave)
        else:
            save_wid = Button(save_zone, text="---", command=None)
        save_wid.pack()
        #Create the open button
        save_zone.pack()        
        if Card.monster_list.keys():
            self.opening = StringVar(save_zone)
            self.opening.set("Open")
            choice = Card.monster_list.keys()
            choice.sort()
            #print all_monsters.keys()
            open_wid = OptionMenu(save_zone, self.opening,*choice)
            self.opening.trace('w', self.Open)
            open_wid.pack()
            save_zone.add(open_wid)
        
        if Card.monster_list.keys():
            self.delete = StringVar(save_zone)
            self.delete.set("Delete")
            choice = Card.monster_list.keys()
            choice.sort()
            delete_wid = OptionMenu(save_zone, self.delete,*choice)
            self.delete.trace('w', self.clicDelete)
            delete_wid.pack()
            save_zone.add(delete_wid)
        
        #Create the type button
        self.category = StringVar(save_zone)
        self.category.set(self.monster_type)
        choice = [t[t.index("\\")+1:t.index("_monsters.sav")] for t in glob.glob("CardFiles/*_monsters.sav")]
        if "recup" in choice:
            choice.remove("recup")
        #print all_monsters.keys()
        category_wid = OptionMenu(save_zone, self.category,*choice)
        self.category.trace('w', self.setFile)
        
        
        
        category_wid.pack()
        
        #Add it to save zone
        save_zone.add(save_wid)
        save_zone.add(category_wid)
        
        #Create a new Strength zone for att and pv
        strength_zone=PanedWindow(self.card_win, orient=HORIZONTAL)
        att=StringVar()
        att.set(str(self.att))
        pv=StringVar() ; pv.set(str(self.pv))
        def modifiedAttPv(*args) :
            self.pv=int(pv.get())
            if self.pv<1 and self.is_spell==False :
                if len(self.bonus)==0 :
                    self.is_spell=True
                    self.refreshWidget()
                else :
                    self.pv=1
                    self.refreshWidget()
            if self.pv>0 and self.is_spell==True :
                if len(self.bonus)==0 :
                    self.is_spell=False
                    self.refreshWidget()
                else :
                    self.pv=0
                    self.refreshWidget()            
            self.att=int(att.get())
            self.getCost()
        att_wid = Spinbox(strength_zone, from_=0, to=1000,textvariable=att,command=modifiedAttPv)
        att_wid.pack()
        strength_zone.add(att_wid)
        strength_zone.add(Label(strength_zone, text='       ', background='white', 
             anchor=CENTER))
        pv_wid = Spinbox(strength_zone, from_=0, to=1000,textvariable=pv,command=modifiedAttPv)
        pv_wid.pack()
        strength_zone.add(pv_wid)
        
        #Put it all in window
        self.card_win.add(name_zone)
        self.card_win.add(image_zone)
        self.card_win.add(power_zone)  
        self.card_win.add(strength_zone)
        self.card_win.add(save_zone)
        
        
        self.card_win.pack()                      

    def createImage(self):
        width=189*2; height=277*2
        screen = pygame.display.set_mode((width,height))

        print "Type = ",self.monster_type
        if self.monster_type in all_backgrounds.keys():
            try:
                bg = pygame.image.load(all_backgrounds[self.monster_type])
            except:
                print "error (? when load of bg"
        else:
            bg = pygame.image.load('gameAnimationImages/Card_face_avant.gif')
        #fond = PhotoImage(file =bg,master=fenetre)
        #ligne1 = canvas.create_line(75, 0, 75, 120)
        #ligne2 = canvas.create_line(0, 60, 150, 60)      
        if self.photofile :
            try :
               img=pygame.image.load(self.photofile)
            except :
               decomp=self.photofile.split('/')
               for i in range(1,6) :
                   try :
                       fname="/".join(decomp[-i:])
                       print "try to open",fname
                       img=pygame.image.load(fname)
                       self.photofile=fname
                       break
                   except:
                       pass
            
            img = pygame.image.load(self.photofile)
            w, h = img.get_size()
            factor=max(140.*2./w,90.*2./h)
            img=pygame.transform.scale(img,(int(w*factor),int(h*factor)))
            #fenetre.photo=PhotoImage(file=self.photofile,master=canvas)
            #img=ImageTk.PhotoImage(img,master=fenetre)
            screen.blit(img,(width/2.-w*factor/2.,140.-h*factor/4.))
        else :
            try :
                name=self.name.replace(" ","_")
                img=pygame.image.load("Cards/"+name+".png")
                print "* Found for image ","Cards/"+name+".png"
                screen.blit(img,(0,0))
            except :
                pass
        screen.blit(bg,(0,0))    
        
        pygame.font.init()
        #print  pygame.font.get_fonts()
        if self.monster_type in white_font_types:
            color = (255,255,255)
        else:
            color = (0,0,0)
        centerText(screen,(width/2.+10.,33.*2.),self.name,36-(len(self.name)>11)*(len(self.name)-11)/3,color)
        #txt = canvas.create_text(101, 32, text=self.name, font=("Calibri",12-(len(self.name)>11)*(len(self.name)-11)/5,"bold"), anchor=CENTER)
        if not(self.is_spell):
            centerText(screen,(24*2.,258*2.),str(self.att),40,color)
            centerText(screen,(169*2.,255*2.),str(self.pv),40,color)
        else :
            centerText(screen,(width/2.,265*2.),"SPELL",30,color)
        #elif self.is_spell:
        #    txt = canvas.create_text(100,265, text="SPELL", anchor=CENTER, font=("Calibri",14,'bold'))
        #txt = canvas.create_text(22,35, text=int(floor(self.getCost())), anchor=CENTER, font=("Calibri",18,'bold'))
        centerText(screen,(22*2.,35*2.),str(int(floor(self.getCost()))),50,color)
        #txt1 = canvas.create_text(92,257, text='*'*self.getStars(), anchor=CENTER, font=("Calibri",26,'bold'))
        centerText(screen,(92*2.,257*2.),'*'*self.getStars(),60,color)
        if not(self.monster_type == "unknown"):
            if self.monster_type in all_type_colors:
                Color = all_type_colors[self.monster_type]
            else:
                Color = "black"
        else:
            Color = "black"
        centerText(screen,(95*2.,142*2.),self.monster_type.capitalize(),26,Color)
        
        if len(self.bonus)>0 :
            powers = "e%96".join([b.getDescription() for b in self.bonus])
            powers = [p.split("\n") for p in powers.split("e%96")]
            print "powers are ",powers
        else :
            powers =""
        #print "POWERS = ", powers
        if powers: 
            space=min([80., 160./sum([len(p)*3+2 for p in powers])])
            print "Space: ",space
        line = 0
        for i,b in enumerate(powers):
            size = min([36.,500./max([len(p) for p in b]) * 2.])
            for x,part in enumerate(b):
                centerText(screen,(90*2.,167*2.+line*space),part,int(size),color)
                line += 3
            line += 2
        #canvas.pack()
        #print "toto!"
        pygame.display.flip()
            
        return screen
      
    def init_as_invocation(self,master):
        # monster widget in invocation widget        
        #print "monster init_as_invocation"
        self.content=StringVar()
        self.content.set(self.name)
        self.content.trace("w", self.is_changed_as_invocation)
        l = Card.monster_list.keys()
        """
        if self.parent.name in l:
            l.remove(self.parent.name)
        """
        self.widget=OptionMenu(master,self.content,*l)
        return self.widget
        
    def is_changed_as_invocation(self,*args):
        print "monster is_changed_as_invocation"
        if self.content.get()!= "Troll gris":
            new= Card.monster_list[self.content.get()]
        else:
            new = Card("Troll gris",4,4)

        #print self.content.get()
        if self.parent :
            #parent.spell=new
            #print "self.parent = True"
            self.parent.monster=new
            new.parent = self.parent
            new.card=self.card
        else :
            raise "ce cas existe ?! me dire comment"
            self.bonus[self.bonus.index(self)]=new
        #self.card_win.pack_forget()
        self.card.refreshWidget()
Пример #49
0
    def __init__(self, master, max_num_features, num_frames, mser_image):
        Toplevel.__init__(self, master)

        self.protocol('WM_DELETE_WINDOW', self.withdraw)

        self.notebook = ttk.Notebook(self)
        frame_feats = ttk.Frame(self.notebook)
        frame_forest = ttk.Frame(self.notebook)
        frame_mser = ttk.Frame(self.notebook)
        frame_other = ttk.Frame(self.notebook)
        self.notebook.add(frame_feats, text="Features ")
        self.notebook.add(frame_forest, text=" Forest  ")
        self.notebook.add(frame_mser, text=" MSER  ")
        self.notebook.add(frame_other, text=" Other  ")

        self.max_num_feats = max_num_features
        self.selection = None

        self.mser_image = mser_image

        rand_row = random.randint(1, 512-200)
        rand_col = random.randint(1, 512-110)
        self.mser_area = mser_image[rand_row:rand_row+180, rand_col:rand_col+100]

        # read images from icons folder
        self.hf0_img = PhotoImage(file="./icons/hf0.gif")
        self.hf1_img = PhotoImage(file="./icons/hf1.gif")
        self.hf2_img = PhotoImage(file="./icons/hf2.gif")
        self.hf3_img = PhotoImage(file="./icons/hf3.gif")
        self.hf4_img = PhotoImage(file="./icons/hf4.gif")
        self.hf5_img = PhotoImage(file="./icons/hf5.gif")

        self.features_vars = list()
        for i in range(max_num_features):
            self.features_vars.append(IntVar())

        Label(frame_feats, text="Patch size (" + u"\N{GREEK SMALL LETTER PI}" + "):").grid(row=0, column=0, pady=5)
        self.patch_size_spinbox = Spinbox(frame_feats, from_=3, to=30, width=3)
        self.patch_size_spinbox.delete(0, END)
        self.patch_size_spinbox.insert(END, 10)
        self.patch_size_spinbox.grid(row=0, column=1, padx=5)

        f1 = ttk.Labelframe(frame_feats, text='Mean filter')
        f1.grid(row=1, columnspan=2)

        Label(f1, text=u"\N{GREEK SMALL LETTER PI}").grid(row=0, column=0)
        Checkbutton(f1, text="R", variable=self.features_vars[0]).grid(row=0, column=1)
        Checkbutton(f1, text="G", variable=self.features_vars[1]).grid(row=0, column=2)
        Checkbutton(f1, text="B", variable=self.features_vars[2]).grid(row=0, column=3)

        Label(f1, text=u"\N{GREEK SMALL LETTER PI}" + "/2").grid(row=1, column=0)
        Checkbutton(f1, text="R", variable=self.features_vars[3]).grid(row=1, column=1)
        Checkbutton(f1, text="G", variable=self.features_vars[4]).grid(row=1, column=2)
        Checkbutton(f1, text="B", variable=self.features_vars[5]).grid(row=1, column=3)

        f2 = ttk.Labelframe(frame_feats, text="Gaussian filter")
        f2.grid(row=2, columnspan=2)

        Label(f2, text=str(1.0)).grid(row=0, column=0)
        Checkbutton(f2, text="R", variable=self.features_vars[6]).grid(row=0, column=1)
        Checkbutton(f2, text="G", variable=self.features_vars[7]).grid(row=0, column=2)
        Checkbutton(f2, text="B", variable=self.features_vars[8]).grid(row=0, column=3)

        Label(f2, text=str(3.5)).grid(row=1, column=0)
        Checkbutton(f2, text="R", variable=self.features_vars[9]).grid(row=1, column=1)
        Checkbutton(f2, text="G", variable=self.features_vars[10]).grid(row=1, column=2)
        Checkbutton(f2, text="B", variable=self.features_vars[11]).grid(row=1, column=3)

        f3 = ttk.Labelframe(frame_feats, text="Laplacian of gaussian")
        f3.grid(row=3, columnspan=2)

        Label(f3, text=str(2.0)).grid(row=0, column=0)
        Checkbutton(f3, text="R", variable=self.features_vars[12]).grid(row=0, column=1)
        Checkbutton(f3, text="G", variable=self.features_vars[13]).grid(row=0, column=2)
        Checkbutton(f3, text="B", variable=self.features_vars[14]).grid(row=0, column=3)

        Label(f3, text=str(3.5)).grid(row=1, column=0)
        Checkbutton(f3, text="R", variable=self.features_vars[15]).grid(row=1, column=1)
        Checkbutton(f3, text="G", variable=self.features_vars[16]).grid(row=1, column=2)
        Checkbutton(f3, text="B", variable=self.features_vars[17]).grid(row=1, column=3)

        f4 = ttk.Labelframe(frame_feats, text="Haar-like features")
        f4.grid(row=1, rowspan=2, column=3, padx=5)

        Checkbutton(f4, image=self.hf0_img, variable=self.features_vars[18]).grid(row=0, column=0)
        Checkbutton(f4, image=self.hf1_img, variable=self.features_vars[19]).grid(row=0, column=1)
        Checkbutton(f4, image=self.hf2_img, variable=self.features_vars[20]).grid(row=1, column=0)
        Checkbutton(f4, image=self.hf3_img, variable=self.features_vars[21]).grid(row=1, column=1)
        Checkbutton(f4, image=self.hf4_img, variable=self.features_vars[22]).grid(row=2, column=0)
        Checkbutton(f4, image=self.hf5_img, variable=self.features_vars[23]).grid(row=2, column=1)

        buttons_paned_window = PanedWindow(frame_feats, orient=VERTICAL)
        buttons_paned_window.grid(row=3, column=3)

        self.select_all_button = Button(buttons_paned_window, text="Select all", command=self._select_all)
        buttons_paned_window.add(self.select_all_button)

        self.clear_selection_button = Button(buttons_paned_window, text="Clear selection", command=self._clear_selection)
        buttons_paned_window.add(self.clear_selection_button)

        # default values
        for j in [0, 1, 3, 6, 7, 9, 15, 21, 23]:
            self.features_vars[j].set(1)

        # FOREST FRAMES
        # number of trees
        f5 = ttk.Labelframe(frame_forest, text="Number of trees")
        f5.grid(row=0, columnspan=2, pady=5, padx=5)
        Label(f5, text="N").grid(row=1, column=0)
        self.num_trees_scale = Scale(f5, from_=5, to=500, resolution=5, orient=HORIZONTAL)
        self.num_trees_scale.set(300)
        self.num_trees_scale.grid(row=0, column=1, rowspan=2)

        # depth single tree
        f6 = ttk.Labelframe(frame_forest, text="Depth single tree")
        f6.grid(row=1, columnspan=2, pady=5, padx=5)
        Label(f6, text="d").grid(row=1, column=0)
        self.depth_tree_scale = Scale(f6, from_=2, to=20, orient=HORIZONTAL)
        self.depth_tree_scale.set(3)
        self.depth_tree_scale.grid(row=0, column=1, rowspan=2)

        # percentage number of features
        f7 = ttk.Labelframe(frame_forest, text="% subset of features")
        f7.grid(row=2, columnspan=2, pady=5, padx=5)
        Label(f7, text="m").grid(row=1, column=0)
        self.percentage_feats_scale = Scale(f7, from_=0.0, to=1, resolution=0.05, orient=HORIZONTAL)
        self.percentage_feats_scale.set(0.5)
        self.percentage_feats_scale.grid(row=0, column=1, rowspan=2)

        # mser frame
        # delta
        f8 = ttk.Labelframe(frame_mser, text="Delta")
        f8.grid(row=0, columnspan=2, pady=5, padx=5)
        Label(f8, text=u"\N{GREEK SMALL LETTER DELTA}").grid(row=1, column=0)
        self.delta_scale = Scale(f8, from_=1, to=10, resolution=1, orient=HORIZONTAL)
        self.delta_scale.set(2)
        self.delta_scale.grid(row=0, column=1, rowspan=2)

        # min area
        f9 = ttk.Labelframe(frame_mser, text="Minimum area")
        f9.grid(row=1, columnspan=2, pady=5, padx=5)
        Label(f9, text="m").grid(row=1, column=0)
        self.min_area_scale = Scale(f9, from_=2, to=200, orient=HORIZONTAL)
        self.min_area_scale.set(10)
        self.min_area_scale.grid(row=0, column=1, rowspan=2)

        # percentage number of features
        f10 = ttk.Labelframe(frame_mser, text="Maximum area")
        f10.grid(row=2, columnspan=2, pady=5, padx=5)
        Label(f10, text="M").grid(row=1, column=0)
        self.max_area_scale = Scale(f10, from_=50, to=1000, resolution=5, orient=HORIZONTAL)
        self.max_area_scale.set(350)
        self.max_area_scale.grid(row=0, column=1, rowspan=2)

        # mser image
        f11 = ttk.Labelframe(frame_mser)
        f11.grid(row=0, rowspan=3, column=2, padx=5)

        self.mser_img_array = Image.fromarray(self.mser_area, "RGB")
        self.mser_img = ImageTk.PhotoImage(self.mser_img_array)

        img_label = Label(f11, image=self.mser_img)
        img_label.grid(row=0, column=0)

        buttons_p_w_mser = PanedWindow(f11, orient=HORIZONTAL)
        try_button = Button(f11, text="Try", command=self.try_mser)
        buttons_p_w_mser.add(try_button)
        change_button = Button(f11, text="New img", command=self.change_mser)
        buttons_p_w_mser.add(change_button)
        buttons_p_w_mser.grid(row=1, column=0)

        # other frame
        f12 = ttk.Labelframe(frame_other, text="Refinement")
        f12.grid(row=0, columnspan=2, pady=5, padx=5)
        Label(f12, text=u"\N{GREEK CAPITAL LETTER PHI}_l").grid(row=1, column=0)
        self.low_thresh_scale = Scale(f12, from_=0, to=1, resolution=0.05, orient=HORIZONTAL, length=90)
        self.low_thresh_scale.set(0.45)
        self.low_thresh_scale.grid(row=0, column=1, rowspan=2)
        Label(f12, text=u"\N{GREEK CAPITAL LETTER PHI}_h").grid(row=3, column=0)
        self.high_thresh_scale = Scale(f12, from_=0, to=1, resolution=0.05, orient=HORIZONTAL, length=90)
        self.high_thresh_scale.set(0.65)
        self.high_thresh_scale.grid(row=2, column=1, rowspan=2)

        f13 = ttk.Labelframe(frame_other, text="Dots distance")
        f13.grid(row=1, columnspan=2, pady=5, padx=5)
        Label(f13, text=u"     \N{GREEK SMALL LETTER SIGMA}").grid(row=1, column=0)
        self.dots_distance_scale = Scale(f13, from_=1, to=20, resolution=1, orient=HORIZONTAL, length=90)
        self.dots_distance_scale.set(6)
        self.dots_distance_scale.grid(row=0, column=1, rowspan=2)

        f14 = ttk.Labelframe(frame_other, text="Tracks")
        f14.grid(row=0, column=3, pady=5, padx=5)
        Label(f14, text="N").grid(row=1, column=0)
        self.num_frames_tracks_spinbox = Spinbox(f14, from_=2, to=num_frames, width=10)
        self.num_frames_tracks_spinbox.delete(0, END)
        self.num_frames_tracks_spinbox.insert(END, num_frames)
        self.num_frames_tracks_spinbox.grid(row=0, column=1, rowspan=2)

        Label(f14, text=u"\N{GREEK SMALL LETTER TAU}").grid(row=3, column=0)
        self.gaps_scale = Scale(f14, from_=1, to=10, resolution=1, orient=HORIZONTAL, length=90)
        self.gaps_scale.set(2)
        self.gaps_scale.grid(row=2, column=1, rowspan=2)

        self.notebook.pack(padx=1, pady=1)

        save_button = Button(self, text=" Save and Close window ", command=self.withdraw)
        save_button.pack(pady=2)
Пример #50
0
    def __init__(self, r):
        self.load_img = ImageTk.PhotoImage(file=PATH + '/ico/load.png')
        self.save_img = ImageTk.PhotoImage(file=PATH + '/ico/save.png')
        self.__root = r  # Root of program
        self.__file = ''  # Current file in use
        self.xrange = self.yrange = (0, 1000
                                     )  # X and Y range for scrolling plot
        self.panx = self.pany = 0  # Pan values for shifting map
        self.plot = Plot.baseplot  # Current selected plot
        self.__label_file_dialog = None
        self.new_file_flag = False
        self.option_menu = None
        self.shape_var = StringVar()
        self.__data_block = LoadData('Empty')
        self.plot_type = IntVar()

        self.width = self.__root.winfo_screenwidth()
        self.height = self.__root.winfo_screenheight()

        logger.info('Screen resolution: ' + str(self.width) + 'x' +
                    str(self.height))

        base_pane = PanedWindow()
        base_pane.pack(fill=BOTH, expand=1)
        sectioned_pane = PanedWindow(orient=VERTICAL)
        base_pane.add(sectioned_pane)
        top_paned_window = PanedWindow(sectioned_pane, orient=HORIZONTAL)
        sectioned_pane.add(top_paned_window)

        # Frame to hold dialog for browsing files
        self.__dialog_frame = Frame(top_paned_window)
        self.__dialog_frame.pack(side=LEFT)
        self.__dialog_shape_frame = Frame(top_paned_window)
        self.__dialog_shape_frame.pack(side=RIGHT)

        # Bottom half the screen
        bottom_paned_window = PanedWindow(sectioned_pane)
        sectioned_pane.add(bottom_paned_window)

        # The frame on which we will set out canvas for drawing etc.
        self.__drawplot_frame = Frame(bottom_paned_window,
                                      width=constants.WIDTH,
                                      height=constants.HEIGHT)

        # Matplotlib backend objects
        self.__parent_fig = Figure(figsize=(16, 11))
        self.__fig = self.__parent_fig.add_subplot(1, 1, 1)
        self.__parent_fig.set_tight_layout(True)
        self.__drawplot_canvas = FigureCanvasTkAgg(
            self.__parent_fig, master=self.__drawplot_frame)
        # Create ToolsWindow class and pass itself + the root
        logger.info('Creating ToolsWindow')
        self.__child = ToolsWindow(self.__drawplot_canvas, self, r)
        logger.info('Creating ShapeManager')
        self.__shapemanager = ShapeManager(self.__fig, self.__drawplot_canvas,
                                           self)
        logger.info('Binding matplotlib backend to canvas and frame')
        self.__toolbar = NavigationToolbar2CALIPSO(
            self, self.__drawplot_canvas, self.__child.coordinate_frame)

        # pack and display canvas
        self.__drawplot_canvas.get_tk_widget().pack(side=TOP,
                                                    fill=BOTH,
                                                    expand=1)
        self.__drawplot_frame.pack()
        self.__root.protocol('WM_DELETE_WINDOW', self.close)
Пример #51
0
    def create_menu_bar(self):
        """
        Создаёт линейку для меню программы.
        """

        def create_mnu_file():
            """
            Создаёт меню файл.
            """
            self.btn_file = Menubutton(self.pnl_menu, text=LANG_RU['mnu_file'],
                                       border=3, relief='groove')
            self.mnu_file = Menu(self.btn_file)
            self.btn_file.config(menu=self.mnu_file)
            self.mnu_file.add_command(label=LANG_RU['mnuFile_New'],
                                      accelerator='Ctrl+N')
            self.mnu_file.add_command(label=LANG_RU['mnuFile_Open'],
                                      accelerator='Ctrl+O')
            self.mnu_file.add_separator()
            self.mnu_file.add_command(label=LANG_RU['mnuFile_Save'],
                                      accelerator='Ctrl+S')
            self.mnu_file.add_command(label=LANG_RU['mnuFile_SaveAs'])
            self.mnu_file.add_separator()
            self.mnu_file.add_command(label=LANG_RU['mnuFile_Print'],
                                      accelerator='Ctrl+P')
            self.mnu_file.add_separator()
            self.mnu_file.add_command(label=LANG_RU['mnuFile_Exit'],
                                      accelerator='Ctrl+Q')
            self.btn_file.pack(side='left')

        def create_mnu_edit():
            """
            Создаёт меню "Правка".
            """
            self.btn_edit = Menubutton(self.pnl_menu,
                                       text=LANG_RU['mnu_edit'],
                                       border=3,
                                       relief='groove')
            self.mnu_edit = Menu(self.btn_edit)
            self.btn_edit.config(menu=self.mnu_edit)
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Undo'],
                                      accelerator='Ctrl+Z')
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Redo'])
            self.mnu_edit.add_separator()
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Copy'],
                                      accelerator='Ctrl+C')
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Cut'],
                                      accelerator='Ctrl+X')
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Paste'],
                                      accelerator='Ctrl+V')
            self.mnu_edit.add_separator()
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Find'],
                                      accelerator='Ctrl+F')
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Replace'],
                                      accelerator='Ctrl+R')
            self.btn_edit.pack(side='left')

        def create_mnu_custom():
            """
            Создаёт меню нстроек.
            """
            self.btn_custom = Menubutton(self.pnl_menu, text='mnu_custom',
                                         border=3, relief='groove')
            self.mnu_custom = Menu(self.btn_custom)
            self.btn_custom.config(menu=self.mnu_custom)
            self.mnu_custom.add_command(label='Type files',
                                        accelerator='Ctrl+D')
            self.mnu_custom.add_command(label='--1')
            self.mnu_custom.add_separator()
            self.mnu_custom.add_command(label='--2', accelerator='---')
            self.mnu_custom.add_command(label='--3', accelerator='---')
            self.mnu_custom.add_command(label='--4', accelerator='---')
            self.mnu_custom.add_separator()
            self.btn_custom.pack(side='left')

        def create_mnu_help():
            """
            Создаёт меню "Справка".
            """
            self.btn_help = Menubutton(self.pnl_menu,
                                       text='mnu_help',
                                       border=3,
                                       relief='groove')
            self.mnu_help = Menu(self.btn_help)
            self.btn_help.config(menu=self.mnu_help)
            self.mnu_help.add_command(label='Type files', accelerator='Ctrl+D')
            self.mnu_help.add_command(label='--1')
            self.mnu_custom.add_separator()
            self.btn_help.pack(side='left')

        self.pnl_menu = PanedWindow(self.frm_up, border=2, relief='raised')
        create_mnu_file()
        create_mnu_edit()
        create_mnu_custom()
        create_mnu_help()

        self.pnl_menu.pack(side='left', expand=1, fill='x')
Пример #52
0
 def _update_position_all_handles(self):
     for sash_index, handle in enumerate(self._handle_list):
         x, y = Tk_PanedWindow.sash_coord(self, sash_index)
         handle.place(x=x)
Пример #53
0
    def BuildMainFrame(self): 
        from Tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry
        from Tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED

        menu = Menu(self.master,activeborderwidth=0,bd=0)
        self.master.config(menu=menu)
  
        filemenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="File", underline=0,  menu=filemenu)
        filemenu.add_command(label="New", accelerator='Ctrl+N',command=self.NewCommand)
        filemenu.add_command(label="Open...",accelerator='Ctrl+O', command=self.OpenCommand)
        filemenu.add_command(label="Save as...",accelerator='Ctrl+S', command=self.SaveCommand)
        filemenu.add_separator()
        filemenu.add_command(label="Quit",accelerator='Ctrl+Q', command=self.QuitCommand)

        self.log_on = IntVar()
        self.log_on.set(1)
  
        self.output_to_file = StringVar()
        self.output_to_file.set('n')
 
        scriptmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        modulenames = ['vmtkscripts']
        for modulename in modulenames:
            scriptsubmenu = self.BuildScriptMenu(menu,modulename)
            if scriptsubmenu:
                scriptmenu.add_cascade(label=modulename,menu=scriptsubmenu)
 
        editmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Edit",underline=0,  menu=editmenu)
        editmenu.add_cascade(label="Insert script",menu=scriptmenu)
        editmenu.add_command(label="Insert file name", accelerator='Ctrl+F',command=self.InsertFileName)
        editmenu.add_separator()
        editmenu.add_command(label="Clear input", command=self.ClearInputCommand)
        editmenu.add_command(label="Clear output", command=self.ClearOutputCommand)
        editmenu.add_command(label="Clear all", command=self.ClearAllCommand)
        editmenu.add_separator()
        editmenu.add_checkbutton(label="Log", variable=self.log_on)
        editmenu.add_separator()
        editmenu.add_radiobutton(label="No output to file", variable=self.output_to_file,value='n')
        editmenu.add_radiobutton(label="Write output to file", variable=self.output_to_file,value='w')
        editmenu.add_radiobutton(label="Append output to file", variable=self.output_to_file,value='a')
        editmenu.add_command(label="Output file...", command=self.OutputFileCommand)

        runmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Run", underline=0, menu=runmenu)
        runmenu.add_command(label="Run all", command=self.RunAllCommand)
        runmenu.add_command(label="Run current line", command=self.RunLineCommand)
        runmenu.add_command(label="Run selection", command=self.RunSelectionCommand)
       
        helpmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Help", underline=0, menu=helpmenu)
        helpmenu.add_command(label="Help", underline=0, accelerator='F1',command=self.ShowHelpCommand)
        helpmenu.add_command(label="About", underline=0, command=self.AboutCommand)

        self.master.bind("<Control-KeyPress-q>", self.QuitHandler)
        self.master.bind("<Control-KeyPress-n>", self.NewHandler)
        self.master.bind("<Control-KeyPress-o>", self.OpenHandler)
        self.master.bind("<Control-KeyPress-s>", self.SaveHandler)
        self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler)
        self.master.bind("<KeyPress-F1>", self.ShowHelpHandler)
        self.master.bind("<KeyPress>", self.KeyPressHandler)
        
        self.wordIndex = ['1.0','1.0']
               
        self.suggestionswindow = Toplevel(bg='#ffffff',bd=0,height=50,width=600,highlightthickness=0,takefocus=True)
        self.suggestionswindow.overrideredirect(1)
        self.suggestionslist = Listbox(self.suggestionswindow,bg='#ffffff',bd=1,fg='#336699',activestyle='none',highlightthickness=0,height=9)
        self.suggestionslist.insert(END,"foo")
        self.suggestionslist.pack(side=TOP,fill=X)
        self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler)
        self.suggestionswindow.withdraw()

        self.master.rowconfigure(0,weight=1)
        self.master.columnconfigure(0,weight=1)
        content = Frame(self.master,bd=0,padx=2,pady=2) 
        content.grid(row=0,column=0,sticky=N+S+W+E)
        content.rowconfigure(0,weight=1,minsize=50)
        content.rowconfigure(1,weight=0)
        content.columnconfigure(0,weight=1)

        panes = PanedWindow(content,orient=VERTICAL,bd=1,sashwidth=8,sashpad=0,sashrelief=RAISED,showhandle=True)
        panes.grid(row=0,column=0,sticky=N+S+W+E)

        frame1 = Frame(panes,bd=0) 
        frame1.grid(row=0,column=0,sticky=N+S+W+E)
        frame1.columnconfigure(0,weight=1)
        frame1.columnconfigure(1,weight=0)
        frame1.rowconfigure(0,weight=1)

        panes.add(frame1,height=300,minsize=20)        

        frame2 = Frame(panes,bd=0) 
        frame2.grid(row=1,column=0,sticky=N+S+W+E)
        frame2.columnconfigure(0,weight=1)
        frame2.columnconfigure(1,weight=0)
        frame2.rowconfigure(0,weight=1)
        
        panes.add(frame2,minsize=20) 
 
        self.text_input = Text(frame1, bg='#ffffff',bd=1,highlightthickness=0)

        self.text_input.bind("<KeyPress>", self.KeyPressHandler)
        self.text_input.bind("<Button-3>", self.PopupHandler)
        self.text_input.bind("<Control-Return>", self.RunKeyboardHandler)
 
        self.input_scrollbar = Scrollbar(frame1,orient=VERTICAL,command=self.text_input.yview)
        self.text_input["yscrollcommand"] = self.input_scrollbar.set    

        self.text_output = Text(frame2,state=DISABLED,bd=1,bg='#ffffff',highlightthickness=0)
        
        self.output_scrollbar = Scrollbar(frame2,orient=VERTICAL,command=self.text_output.yview)
        self.text_output["yscrollcommand"] = self.output_scrollbar.set    
      
        self.text_entry = Entry(content,bd=1,bg='#ffffff',state=DISABLED,highlightthickness=0)

        self.text_input.focus_set()

        self.text_input.grid(row=0,column=0,sticky=N+S+W+E)
        self.input_scrollbar.grid(row=0,column=1,sticky=N+S+W+E)
        self.text_output.grid(row=0,column=0,sticky=N+S+W+E)
        self.output_scrollbar.grid(row=0,column=1,sticky=N+S+W+E)
        self.text_entry.grid(row=1,column=0,sticky=N+S+W+E)

        self.popupmenu = Menu(self.text_input, tearoff=1, bd=0)
        self.popupmenu.add_command(label="Context help", command=self.ShowHelpCommand)
        self.popupmenu.add_cascade(label="Insert script",menu=scriptmenu)
        self.popupmenu.add_command(label="Insert file name...", command=self.InsertFileName)
        self.popupmenu.add_separator()
        self.popupmenu.add_command(label="Run all", command=self.RunAllCommand)
        self.popupmenu.add_command(label="Run current line", command=self.RunLineCommand)
        self.popupmenu.add_command(label="Run selection", command=self.RunSelectionCommand)

        self.output_stream = TkPadOutputStream(self.text_output)
        self.input_stream = TkPadInputStream(self.text_entry,self.output_stream)
Пример #54
0
class MainWindow(Frame):
    def __init__(self, **kw):
        Frame.__init__(self, **kw)
        self.winfo_toplevel().minsize(width=800, height=480)
        self.pack(expand=True, fill='both')
        self._init_variables()
        self._init_components()
        self._init_menu()

    def _init_components(self):
        self._panes = PanedWindow(self,
                                  orient='horizontal',
                                  sashrelief="raised")
        self._panes.pack(expand=True, fill='both')

        self._left_pane = Frame(self._panes)
        self._right_pane = PanedWindow(self._panes)
        self._panes.add(self._left_pane, sticky='n')
        self._panes.add(self._right_pane)

        self._group_select = GroupSelect(self._left_pane)
        self._group_select.pack(expand=True, fill='x')

        self._show_graph_checkbutton = CheckBox(self._left_pane,
                                                text='Show graph')
        self._show_graph_checkbutton.select()
        self._show_graph_checkbutton.pack()

        self._go_button = Button(self._left_pane, text='Go', command=self._go)
        self._go_button.pack()

    def _init_variables(self):
        # init default properties
        self.setvar("graphframeview", "onlyone")
        self.setvar("vertexlabelposition", "auto")

    def _init_menu(self):
        toplevel = self.winfo_toplevel()
        self._menu = Menu(toplevel)
        toplevel['menu'] = self._menu

        view = Menu(self._menu, tearoff=0)
        self._menu.add_cascade(label="View", menu=view)

        graph_view = Menu(view, tearoff=0)
        view.add_cascade(label="View graphs", menu=graph_view)

        graph_view.add_radiobutton(label="Only one",
                                   value="onlyone",
                                   variable="graphframeview")
        #        graph_view.add_radiobutton(label="In a row", value="row",
        #            variable=graph_view_var)
        graph_view.add_radiobutton(label="In separate window",
                                   value="window",
                                   variable="graphframeview")

    def _go(self):
        view = self.getvar("graphframeview")

        if view == "onlyone":
            for child in self._right_pane.winfo_children():
                child.destroy()
                #if view in ("onlyone", "row"):
            container = FrameWithCloseButton(self._right_pane)
            self._right_pane.add(container, minsize=600)
        else:
            container = Toplevel()

        facade = Facade(container,
                        self._group_select.selected_group,
                        show_graph=self._show_graph_checkbutton.is_selected())

        facade.pack(expand=True, fill='both')
Пример #55
0
 def _update_position_all_handles(self):
     for sash_index, handle in enumerate(self._handle_list):
         x,y = Tk_PanedWindow.sash_coord(self, sash_index)
         handle.place(x=x)
Пример #56
0
 def _on_configure_pane(self, sash_index):
     x,y = Tk_PanedWindow.sash_coord(self, sash_index)
     self._handle_list[sash_index].place(x=x)
Пример #57
0
    def BuildMainFrame(self):
        from Tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry
        from Tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED

        menu = Menu(self.master, activeborderwidth=0, bd=0)
        self.master.config(menu=menu)

        filemenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="File", underline=0, menu=filemenu)
        filemenu.add_command(label="New",
                             accelerator='Ctrl+N',
                             command=self.NewCommand)
        filemenu.add_command(label="Open...",
                             accelerator='Ctrl+O',
                             command=self.OpenCommand)
        filemenu.add_command(label="Save as...",
                             accelerator='Ctrl+S',
                             command=self.SaveCommand)
        filemenu.add_separator()
        filemenu.add_command(label="Quit",
                             accelerator='Ctrl+Q',
                             command=self.QuitCommand)

        self.log_on = IntVar()
        self.log_on.set(1)

        self.output_to_file = StringVar()
        self.output_to_file.set('n')

        scriptmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        modulenames = ['vmtkscripts']
        for modulename in modulenames:
            scriptsubmenu = self.BuildScriptMenu(menu, modulename)
            if scriptsubmenu:
                scriptmenu.add_cascade(label=modulename, menu=scriptsubmenu)

        editmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Edit", underline=0, menu=editmenu)
        editmenu.add_cascade(label="Insert script", menu=scriptmenu)
        editmenu.add_command(label="Insert file name",
                             accelerator='Ctrl+F',
                             command=self.InsertFileName)
        editmenu.add_separator()
        editmenu.add_command(label="Clear input",
                             command=self.ClearInputCommand)
        editmenu.add_command(label="Clear output",
                             command=self.ClearOutputCommand)
        editmenu.add_command(label="Clear all", command=self.ClearAllCommand)
        editmenu.add_separator()
        editmenu.add_checkbutton(label="Log", variable=self.log_on)
        editmenu.add_separator()
        editmenu.add_radiobutton(label="No output to file",
                                 variable=self.output_to_file,
                                 value='n')
        editmenu.add_radiobutton(label="Write output to file",
                                 variable=self.output_to_file,
                                 value='w')
        editmenu.add_radiobutton(label="Append output to file",
                                 variable=self.output_to_file,
                                 value='a')
        editmenu.add_command(label="Output file...",
                             command=self.OutputFileCommand)

        runmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Run", underline=0, menu=runmenu)
        runmenu.add_command(label="Run all", command=self.RunAllCommand)
        runmenu.add_command(label="Run current line",
                            command=self.RunLineCommand)
        runmenu.add_command(label="Run selection",
                            command=self.RunSelectionCommand)

        helpmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Help", underline=0, menu=helpmenu)
        helpmenu.add_command(label="Help",
                             underline=0,
                             accelerator='F1',
                             command=self.ShowHelpCommand)
        helpmenu.add_command(label="About",
                             underline=0,
                             command=self.AboutCommand)

        self.master.bind("<Control-KeyPress-q>", self.QuitHandler)
        self.master.bind("<Control-KeyPress-n>", self.NewHandler)
        self.master.bind("<Control-KeyPress-o>", self.OpenHandler)
        self.master.bind("<Control-KeyPress-s>", self.SaveHandler)
        self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler)
        self.master.bind("<KeyPress-F1>", self.ShowHelpHandler)
        self.master.bind("<KeyPress>", self.KeyPressHandler)

        self.wordIndex = ['1.0', '1.0']

        self.suggestionswindow = Toplevel(bg='#ffffff',
                                          bd=0,
                                          height=50,
                                          width=600,
                                          highlightthickness=0,
                                          takefocus=True)
        self.suggestionswindow.overrideredirect(1)
        self.suggestionslist = Listbox(self.suggestionswindow,
                                       bg='#ffffff',
                                       bd=1,
                                       fg='#336699',
                                       activestyle='none',
                                       highlightthickness=0,
                                       height=9)
        self.suggestionslist.insert(END, "foo")
        self.suggestionslist.pack(side=TOP, fill=X)
        self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler)
        self.suggestionswindow.withdraw()

        self.master.rowconfigure(0, weight=1)
        self.master.columnconfigure(0, weight=1)
        content = Frame(self.master, bd=0, padx=2, pady=2)
        content.grid(row=0, column=0, sticky=N + S + W + E)
        content.rowconfigure(0, weight=1, minsize=50)
        content.rowconfigure(1, weight=0)
        content.columnconfigure(0, weight=1)

        panes = PanedWindow(content,
                            orient=VERTICAL,
                            bd=1,
                            sashwidth=8,
                            sashpad=0,
                            sashrelief=RAISED,
                            showhandle=True)
        panes.grid(row=0, column=0, sticky=N + S + W + E)

        frame1 = Frame(panes, bd=0)
        frame1.grid(row=0, column=0, sticky=N + S + W + E)
        frame1.columnconfigure(0, weight=1)
        frame1.columnconfigure(1, weight=0)
        frame1.rowconfigure(0, weight=1)

        panes.add(frame1, height=300, minsize=20)

        frame2 = Frame(panes, bd=0)
        frame2.grid(row=1, column=0, sticky=N + S + W + E)
        frame2.columnconfigure(0, weight=1)
        frame2.columnconfigure(1, weight=0)
        frame2.rowconfigure(0, weight=1)

        panes.add(frame2, minsize=20)

        self.text_input = Text(frame1,
                               bg='#ffffff',
                               bd=1,
                               highlightthickness=0)

        self.text_input.bind("<KeyPress>", self.KeyPressHandler)
        self.text_input.bind("<Button-3>", self.PopupHandler)
        self.text_input.bind("<Control-Return>", self.RunKeyboardHandler)

        self.input_scrollbar = Scrollbar(frame1,
                                         orient=VERTICAL,
                                         command=self.text_input.yview)
        self.text_input["yscrollcommand"] = self.input_scrollbar.set

        self.text_output = Text(frame2,
                                state=DISABLED,
                                bd=1,
                                bg='#ffffff',
                                highlightthickness=0)

        self.output_scrollbar = Scrollbar(frame2,
                                          orient=VERTICAL,
                                          command=self.text_output.yview)
        self.text_output["yscrollcommand"] = self.output_scrollbar.set

        self.text_entry = Entry(content,
                                bd=1,
                                bg='#ffffff',
                                state=DISABLED,
                                highlightthickness=0)

        self.text_input.focus_set()

        self.text_input.grid(row=0, column=0, sticky=N + S + W + E)
        self.input_scrollbar.grid(row=0, column=1, sticky=N + S + W + E)
        self.text_output.grid(row=0, column=0, sticky=N + S + W + E)
        self.output_scrollbar.grid(row=0, column=1, sticky=N + S + W + E)
        self.text_entry.grid(row=1, column=0, sticky=N + S + W + E)

        self.popupmenu = Menu(self.text_input, tearoff=1, bd=0)
        self.popupmenu.add_command(label="Context help",
                                   command=self.ShowHelpCommand)
        self.popupmenu.add_cascade(label="Insert script", menu=scriptmenu)
        self.popupmenu.add_command(label="Insert file name...",
                                   command=self.InsertFileName)
        self.popupmenu.add_separator()
        self.popupmenu.add_command(label="Run all", command=self.RunAllCommand)
        self.popupmenu.add_command(label="Run current line",
                                   command=self.RunLineCommand)
        self.popupmenu.add_command(label="Run selection",
                                   command=self.RunSelectionCommand)

        self.output_stream = TkPadOutputStream(self.text_output)
        self.input_stream = TkPadInputStream(self.text_entry,
                                             self.output_stream)
Пример #58
0
    def __init__(self):
        Game.__init__(self)
        import socket
        self.local = self.host = socket.gethostbyname(
            socket.gethostname())  # Get local machine ip
        from Tkinter import Tk, PanedWindow, StringVar, Entry, Button, VERTICAL, HORIZONTAL, Label
        fenetre = Tk()
        fenetre.title('Socket parameters')
        self.netgame_win = PanedWindow(fenetre, orient=VERTICAL)
        host_zone = PanedWindow(self.netgame_win, orient=HORIZONTAL)
        host = StringVar()
        host.set(self.local)

        def modifHost(*args):
            self.host = host.get()
            if self.local == self.host:
                start_button.config(text="Create")
            else:
                start_button.config(text="Join")

        host.trace("w", modifHost)
        host_wid = Entry(host_zone, width=30, textvariable=host)
        host_wid.pack()
        host_label = Label(fenetre, text="Host (you are " + self.local + ") :")
        host_zone.add(host_label)
        host_zone.add(host_wid)
        self.netgame_win.add(host_zone)
        port_zone = PanedWindow(self.netgame_win, orient=HORIZONTAL)
        port = StringVar()
        self.port = 52333
        port.set(str(self.port))

        # adress_wid=Label(None, textvariable=self.cost, background='red',width=5, anchor=W)
        def modifPort(*args):
            self.port = port.get()

        port.trace("w", modifPort)
        port_wid = Entry(port_zone, width=30, textvariable=port)
        port_wid.pack()
        port_label = Label(fenetre, text="Port :")
        port_zone.add(port_label)
        port_zone.add(port_wid)
        self.netgame_win.add(port_zone)

        #Create the open button
        def start():
            fenetre.destroy()

        start_button = Button(self.netgame_win, text="Create", command=start)
        self.netgame_win.add(start_button)
        self.netgame_win.pack()
        fenetre.focus_set()
        start_button.focus()
        fenetre.mainloop()
        # Import socket module
        self.soc = socket.socket()  # Reserve a port for your service.
        if self.local == self.host:
            self.soc.bind((self.host, self.port))  # Bind to the port
            print "socket listening"
            self.soc.listen(5)  # Now wait for client connection.

            self.soc, addr = self.soc.accept(
            )  # Establish connection with client.
            print 'Got connection from', addr
            #self.soc.send('Thank you for connecting')
            #c.close()                # Close the connection
            self.firstplayer = choice([1, 2])
            print "FIRST PLAYER IS", 1
            self.soc.send(str(3 - self.firstplayer))
        else:
            self.soc.connect((self.host, self.port))
            print "connect ok"
            p = self.soc.recv(1024)
            try:
                self.firstplayer = int(p)
            except:
                print "error concerning first player, got ", p