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
Exemplo n.º 3
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)
Exemplo n.º 4
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)
Exemplo n.º 5
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
Exemplo n.º 6
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)
Exemplo n.º 7
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)
Exemplo n.º 8
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()
Exemplo n.º 9
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()
Exemplo n.º 10
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()                      
Exemplo n.º 11
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')
Exemplo n.º 12
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)
Exemplo n.º 13
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
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()
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()
Exemplo n.º 16
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()
Exemplo n.º 17
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
Exemplo n.º 18
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')
Exemplo n.º 19
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')
Exemplo n.º 20
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')
Exemplo n.º 21
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
Exemplo n.º 22
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()
Exemplo n.º 23
0
class NetGame(Game):
    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
            #self.soc.close()                     # Close the socket when done
    def initialize(self):
        if self.firstplayer == 1:  # player1 doit etre le local
            print "first player is local"
            self.player1.sendDeck()
            self.player2.receiveDeck()
        else:
            print "first player is hosted"
            self.player2.receiveDeck()
            self.player1.sendDeck()
        Game.initialize(self)
        if self.player == self.player2:
            self.endturn_button.update(self.player)