示例#1
0
文件: main.py 项目: dan2082/KSPData
 def __init__(self, master=None):
     Frame.__init__(self, master)
     self.pack(expand=1, fill='both')
     self.master.geometry('1440x900')
     paned_window = PanedWindow(self)
     self.treeview_kspelements = TreeviewKSPElements(self)
     self.treeview_kspobjects = TreeviewKSPObjects(self)
     paned_window.pack(expand=1, fill='both')
     paned_window.add(self.treeview_kspelements)
     paned_window.add(self.treeview_kspobjects)
     
     menubar = Menu(self)
     
     filemenu = Menu(self)
     filemenu.add_command(label='Open', command=self._open)
     filemenu.add_command(label='Save', command=self._save)
     filemenu.add_command(label='Save As', command=self._save_as)
     filemenu.add_separator()
     filemenu.add_command(label='Exit', command=self.master.destroy)
     menubar.add_cascade(menu=filemenu, label='File')
     
     insertmenu = Menu(self)
     insertmenu.add_command(label='KSP Element', command=self._insert_element, state='disabled')
     insertmenu.add_command(label='KSP Object', command=self._insert_object)
     menubar.add_cascade(menu=insertmenu, label='Insert')
     self.master.config(menu=menubar)
示例#2
0
    def add(self, pane, **kwargs):
        Tk_PanedWindow.add(self, pane, **kwargs)

        self._list_of_panes.append(pane)
        quantity_of_panes = len(self._list_of_panes)
        if quantity_of_panes >= 2:
            handle_index = quantity_of_panes - 2
            handle = self.HANDLE_CLASS(
                self,
                handle_index,
                bg=self._color,
                height=self._height,
                width=self._width,
                cursor=self._cursor,
                disallow_dragging=self._disallow_dragging,
                on_click=self._on_click,
                image=self._image)
            if self.ORIENT == VERTICAL:
                handle.place(relx=0.5, anchor="c")
            else:
                handle.place(rely=0.5, anchor="c")
            self._handle_list.append(handle)
            callback_id1 = pane.bind("<Configure>",
                                     lambda event, handle_index=handle_index:
                                     self._on_configure_pane(handle_index),
                                     "+")
            callback_id2 = self._list_of_panes[handle_index].bind(
                "<Configure>",
                lambda event, handle_index=handle_index: self.
                _on_configure_pane(handle_index),
                "+")
            self._configure_callbacks.append((callback_id1, callback_id2))
示例#3
0
    def popupInformation(self, title="Info", message="Info"):
        if self.displayPopup:
            #popup
            self.popup = Tk()
            self.popup.wm_title(title)

            frame = Frame(self.popup)
            panedWindow = PanedWindow(frame)

            #icon warning
            labelIconWarning = Label(panedWindow,
                                     image="::tk::icons::information")
            panedWindow.add(labelIconWarning)

            #text
            labelMessage = Label(panedWindow, text=message, font=NORM_FONT)
            panedWindow.add(labelMessage)

            #button
            buttonOk = Button(frame, text="Ok")

            #display
            panedWindow.pack(side="top")
            buttonOk.pack(side="bottom")
            frame.pack(side="top", fill="x", padx=10, expand=True)
        else:
            self.popup.focus_force()
        self.popup.mainloop()
示例#4
0
    def __init__(self, tk: Tk):
        tk.title("Layered Polygons")

        menubar = Menu(tk)

        menu_file = Menu(menubar, tearoff=0)
        menu_file.add_command(label="New...", command=self._new_scene)
        menu_file.add_command(label="Open...", command=self._open_scene)
        menu_file.add_separator()
        menu_file.add_command(label="Save", command=self._save_scene)
        menu_file.add_command(label="Save As...", command=self._save_scene_as)
        menu_file.add_separator()
        menu_export = Menu(menu_file, tearoff=0)
        menu_export.add_command(label="Wavefront (.obj)...",
                                command=self._export_obj)
        menu_file.add_cascade(label="Export As", menu=menu_export)
        menu_file.add_separator()
        menu_file.add_command(label="Quit", command=self._quit_app)
        menubar.add_cascade(label="File", menu=menu_file)

        tk.config(menu=menubar)

        paned = PanedWindow(tk, relief=RAISED)
        paned.pack(fill=BOTH, expand=1)

        frame = Frame(paned)
        paned.add(frame)
        self._canvas = LayPolyCanvas(frame)
        bar_x = Scrollbar(frame, orient=HORIZONTAL)
        bar_x.pack(side=BOTTOM, fill=X)
        bar_x.config(command=self._canvas.xview)
        bar_y = Scrollbar(frame, orient=VERTICAL)
        bar_y.pack(side=RIGHT, fill=Y)
        bar_y.config(command=self._canvas.yview)
        self._canvas.config(xscrollcommand=bar_x.set, yscrollcommand=bar_y.set)
        self._canvas.pack(side=LEFT, expand=True, fill=BOTH)
        # Thanks to the two guys on Stack Overflow for that!
        # ( http://stackoverflow.com/a/7734187 )

        self._layer_list = Listbox(paned, selectmode=SINGLE)
        paned.add(self._layer_list)

        self._scene = None
        self._current_layer = None
        self._is_drawing_polygon = False
        self._tk = tk

        self._canvas.bind("<Button-1>", self._canvas_left_click)
        self._canvas.bind("<Button-3>", self._canvas_right_click)
        self._canvas.bind("<Motion>", self._canvas_mouse_moved)
        self._layer_list.bind("<<ListboxSelect>>", self._layer_change)

        self._current_path = None
示例#5
0
    def __init__(self, tk: Tk):
        tk.title("Layered Polygons")

        menubar = Menu(tk)

        menu_file = Menu(menubar, tearoff=0)
        menu_file.add_command(label="New...", command=self._new_scene)
        menu_file.add_command(label="Open...", command=self._open_scene)
        menu_file.add_separator()
        menu_file.add_command(label="Save", command=self._save_scene)
        menu_file.add_command(label="Save As...", command=self._save_scene_as)
        menu_file.add_separator()
        menu_export = Menu(menu_file, tearoff=0)
        menu_export.add_command(label="Wavefront (.obj)...",
                                command=self._export_obj)
        menu_file.add_cascade(label="Export As", menu=menu_export)
        menu_file.add_separator()
        menu_file.add_command(label="Quit", command=self._quit_app)
        menubar.add_cascade(label="File", menu=menu_file)

        tk.config(menu=menubar)

        paned = PanedWindow(tk, relief=RAISED)
        paned.pack(fill=BOTH, expand=1)

        frame = Frame(paned)
        paned.add(frame)
        self._canvas = LayPolyCanvas(frame)
        bar_x = Scrollbar(frame, orient=HORIZONTAL)
        bar_x.pack(side=BOTTOM, fill=X)
        bar_x.config(command=self._canvas.xview)
        bar_y = Scrollbar(frame, orient=VERTICAL)
        bar_y.pack(side=RIGHT, fill=Y)
        bar_y.config(command=self._canvas.yview)
        self._canvas.config(xscrollcommand=bar_x.set, yscrollcommand=bar_y.set)
        self._canvas.pack(side=LEFT, expand=True, fill=BOTH)
        # Thanks to the two guys on Stack Overflow for that!
        # ( http://stackoverflow.com/a/7734187 )

        self._layer_list = Listbox(paned, selectmode=SINGLE)
        paned.add(self._layer_list)

        self._scene = None
        self._current_layer = None
        self._is_drawing_polygon = False
        self._tk = tk

        self._canvas.bind("<Button-1>", self._canvas_left_click)
        self._canvas.bind("<Button-3>", self._canvas_right_click)
        self._canvas.bind("<Motion>", self._canvas_mouse_moved)
        self._layer_list.bind("<<ListboxSelect>>", self._layer_change)

        self._current_path = None
示例#6
0
def pack_windows(root):
    main_paned_window = PanedWindow(root)
    main_paned_window.pack(fill=BOTH, expand=True)

    tone_paned_window=PanedWindow(relief=tk.GROOVE,bd=3,orient=tk.VERTICAL)
    main_paned_window.add(tone_paned_window)
    
    sub_tone_paned_window=PanedWindow(tone_paned_window)
    tone_paned_window.add(sub_tone_paned_window)
    
    plot_window=PanedWindow()
    main_paned_window.add(plot_window)
    plot_window=ImageViewer(plot_window)
    plot_window.canvas.get_tk_widget().pack(fill=tk.BOTH,expand=True)

    tone_window=ToneCurveViewer(sub_tone_paned_window,plot_window)
    tone_window.canvas.get_tk_widget().pack(fill=tk.BOTH,expand=True)
    space_frame=Frame()
    tone_paned_window.add(space_frame)
    
    button=Button(space_frame,text="something")
    button.pack()

    def quit_app():
        root.quit()
        root.destroy()

    quitbutton=Button(space_frame,text="exit",command=quit_app)
    quitbutton.pack()
示例#7
0
def pack_windows(root):
    main_paned_window = PanedWindow(root)
    main_paned_window.pack(fill=BOTH, expand=True)

    tone_paned_window = PanedWindow(relief=tk.GROOVE, bd=3, orient=tk.VERTICAL)
    main_paned_window.add(tone_paned_window)

    sub_tone_paned_window = PanedWindow(tone_paned_window)
    tone_paned_window.add(sub_tone_paned_window)

    plot_window = PanedWindow()
    main_paned_window.add(plot_window)
    plot_window = ImageViewer(plot_window)
    plot_window.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)

    tone_window = ToneCurveViewer(sub_tone_paned_window, plot_window)
    tone_window.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
    space_frame = Frame()
    tone_paned_window.add(space_frame)

    button = Button(space_frame, text="something")
    button.pack()

    def quit_app():
        root.quit()
        root.destroy()

    quitbutton = Button(space_frame, text="exit", command=quit_app)
    quitbutton.pack()
示例#8
0
    def create_gui(app):

        f1 = PanedWindow(
            app,
            orient='horizontal',
            width=800,
            height=600,
            sashrelief='ridge',
            sashwidth=4,
        )
        f1.grid(
            row=0,
            column=0,
            sticky="nesw",
        )
        f2 = PanedWindow(f1, orient='vertical')
        canvW = Canvas(f2, bg='#113333')
        f2.add(canvW)
        logW = scrolledtext.ScrolledText(f2,
                                         bg='#223399',
                                         fg='#cccc99',
                                         font=font.nametofont('TkDefaultFont'))
        f2.add(logW)
        bodyW = makeBodyW(f1)
        f1.add(f2)
        f1.add(bodyW)
        return f1, f2, bodyW, canvW, logW
示例#9
0
class RootView(Tk):

    __instance = None

    @staticmethod
    def getInstance():
        if RootView.__instance == None:
            RootView()
        return RootView.__instance

    def __init__(self, **kw):
        if RootView.__instance != None:
            raise Exception("Cette classe est un Singleton")
        else:
            RootView.__instance = self

        super(RootView, self).__init__(**kw)
        self.title("Chroma V0.1")
        self.frame = HomeFrame(self)
        self.frame.pack(side="top", fill="both", expand=True)
        #self.wm_attributes("-fullscreen",True)

        #button
        self.panedWindow = PanedWindow()
        self.panedWindow.pack(side="bottom")
        self.buttonStop = Button(self.panedWindow,
                                 text="Stop",
                                 command=self._generateEventStopButton)
        self.panedWindow.add(self.buttonStop)
        self.buttonOk = Button(self.panedWindow,
                               text="Ok",
                               command=self._generateEventOkButton)
        self.panedWindow.add(self.buttonOk)
        buttonPlus = Button(
            self.panedWindow,
            text="Plus",
            command=lambda: self.event_generate('<<BUTTON_PLUS>>'))
        self.panedWindow.add(buttonPlus)
        buttonMoins = Button(
            self.panedWindow,
            text="Moins",
            command=lambda: self.event_generate('<<BUTTON_MOINS>>'))
        self.panedWindow.add(buttonMoins)

    def _generateEventOkButton(self):
        self.event_generate('<<BUTTON_OK>>')

    def _generateEventStopButton(self):
        self.event_generate('<<BUTTON_STOP>>')

    def setFrame(self, frame):
        self.frame.pack_forget()
        self.frame.destroy()
        self.frame = frame
        self.frame.pack(side="top", fill="both", expand=True)

    def getFrame(self):
        return self.frame
示例#10
0
 def resize_paned_window(self, tk_paned_window: tkinter.PanedWindow):
     column, row = tk_paned_window.grid_info()['column'], tk_paned_window.grid_info()['row']
     tk_paned_window.grid_forget()
     p_pane_list = []
     for pane_index in range(len(tk_paned_window.panes())):
         p_pane_list.append(self.widgets.find_pyte_widget_from_tk(str(tk_paned_window.panes()[0])))
         tk_paned_window.forget(p_pane_list[-1].tk_name)
         tk_widget_list = []
         tk_widget_row = []
         # tk_widget_column = []
         for tk_widget in p_pane_list[-1].tk_name.winfo_children():
             tk_widget_list.append(tk_widget)
             # print(tk_widget)
             tk_widget_row.append(tk_widget.grid_info()['row'])
         # print(p_pane_list[-1])
     for p_pane in p_pane_list:
         tk_paned_window.add(p_pane.tk_name)
     tk_paned_window.grid(row=row, column=column)
示例#11
0
 def __init__(self, modelProc, tick):
     self.modelProc = modelProc
     self.tick = tick
     self.queue = modelProc.getQueue()
     # ----------------- Model parameters -----------------
     # Waiting time between two events
     self.refreshRate = DEFAULT_REFRESH_RATE
     # Elapsed time (in number of ticks)
     self.count = 0
     # ------------------------ GUI -----------------------
     # Main window
     self.window = Tk()
     self.window.title("Model Rendering")
     self.window.configure(bg=BG_COLOR)
     self.window.protocol("WM_DELETE_WINDOW", self.onClosing)
     # Main pane
     mainPane = PanedWindow(self.window, orient=HORIZONTAL, bg=BG_COLOR)
     mainPane.pack(side=TOP, expand=Y, fill=BOTH, pady=5, padx=5)
     # Canvas frame
     canvasFrame = LabelFrame(mainPane, text="Rendering", padx=10, pady=10, bg=BG_COLOR)
     mainPane.add(canvasFrame)
     self.canvas = Canvas(canvasFrame, width=CANVAS_X, height=CANVAS_Y, background="white")
     self.canvas.pack()
     # Parameters frame
     paramFrame = LabelFrame(mainPane, text="Simulation parameters",\
     padx=20, pady=20, bg=BG_COLOR)
     mainPane.add(paramFrame)
     # ===> Refresh rate slider
     self.stepVar = DoubleVar(paramFrame, value=DEFAULT_REFRESH_RATE)
     slider = Scale(paramFrame, from_=0, to_=0.5, resolution=0.001, length=350, orient=VERTICAL,\
     variable=self.stepVar, label="# Refresh rate", bg=BG_COLOR, bd=1)
     slider.bind("<ButtonRelease-1>", self.updateRate)
     slider.grid(row=1, column=1)
     # ===> Elapsed time
     self.timeLabel = Label(paramFrame, text="# Elapsed time (hours) :\n0", bg=BG_COLOR)
     self.timeLabel.grid(row=3, column=1)
     # Rows and columns configuration
     paramFrame.grid_columnconfigure(0, weight=1)
     paramFrame.grid_columnconfigure(1, weight=2)
     paramFrame.grid_columnconfigure(2, weight=1)
     paramFrame.grid_rowconfigure(0, weight=1)
     paramFrame.grid_rowconfigure(2, weight=2)
     paramFrame.grid_rowconfigure(4, weight=2)
def launch_details():

    global root
    root = Toplevel()

    root.geometry("1336x720")

    m = PanedWindow(root, bd=4, bg="black")
    m.pack(fill=X, expand=1)

    try:
        img_attendance = PhotoImage(Image.open("MyAttendance.png"))
        panel_one = Label(m, image=img_attendance)

        img_bunks = PhotoImage(Image.open("MyBunks.png"))
        panel_two = Label(m, image=img_bunks)

        img_att = PhotoImage(Image.open("AttendanceDetails.png"))
        panel_three = Label(m, image=img_att)

    except:
        refresh()

        img_attendance = PhotoImage(Image.open("MyAttendance.png"))
        panel_one = Label(m, image=img_attendance)

        img_bunks = PhotoImage(Image.open("MyBunks.png"))
        panel_two = Label(m, image=img_bunks)

        img_att = PhotoImage(Image.open("AttendanceDetails.png"))
        panel_three = Label(m, image=img_att)

    # m_h = tk.PanedWindow(root, bd=4, bg="black")
    rf = Button(root, text="Refresh", command=refresh)
    rf.pack(expand=True, fill=BOTH)

    m.add(panel_one)
    m.add(panel_two)
    m.add(panel_three)

    root.mainloop()
示例#13
0
    def __init__(self):
        self.root = Tk()
        VARIABLES.set_master(self.root)
        self.root.wm_title('asterios')
        self._init_menu()

        paned_window = PanedWindow(self.root, orient='vertical')

        nb = Notebook(paned_window)

        self.tips_text = Text(nb)
        nb.add(self.tips_text, text='tips')

        self.puzzle_text = PuzzleViewer(nb)
        nb.add(self.puzzle_text, text='puzzle')

        self.solver_text = CodeEditor(nb)
        nb.add(self.solver_text, text='solver')
        self.solver_text.insert(
            'end',
            textwrap.dedent('''\
                def solve(puzzle):
                    """
                    Complete cette fonction
                    """
                    puzzle_solved = '...'

                    return puzzle_solved
            ''')
        )

        self.notif_text = NotificationViewer(paned_window, relief='ridge', border=3)

        paned_window.add(nb, sticky='nsew')
        paned_window.add(self.notif_text, sticky='nsew', minsize=80)
        paned_window.pack(fill='both', expand=1)
        self.show_configuration_window()
示例#14
0
文件: App.py 项目: Smacket/Desktop
    def __init__(self, master, appWidth, appHeight):
        self.master = master
        geo = "%dx%d" % (appWidth, appHeight)
        master.geometry(geo)
        master.title("Smacket")
        self.videoPath = ""

        bcg = "#0A8049"
        topLeft = PanedWindow(master, orient=tk.VERTICAL)
        topLeft.config(bg = bcg)
        topLeft.grid(row = 0, column = 0)
        topLeftTitle = tk.Message(master, text = "Timestamps")
        topLeftTitle.config(anchor = "center", aspect = 500, font = ("consolas", 20, "bold"), bg = bcg, relief = "sunken")
        timeStamps = TextScrollCombo(master)
        timeStamps.config(width=appWidth // 10, height= appHeight // 2)
        timeStamps.txt.config(font=("consolas", 12), undo=True, wrap='word', borderwidth=3, relief="sunken")
        topLeft.add(topLeftTitle)
        topLeft.add(timeStamps)

        bottomLeft = PanedWindow(master, orient=tk.VERTICAL)
        bottomLeft.config(bg = bcg)
        bottomLeft.grid(row = 1, column = 0)
        bottomLeftTitle = tk.Message(master, text = "Matches")
        bottomLeftTitle.config(anchor = "center", aspect = 500, font = ("consolas", 20, "bold"), bg = bcg, relief = "sunken")
        matches = TextScrollCombo(master)
        matches.config(width= appWidth// 10 , height=appHeight // 2)
        matches.txt.config(font=("consolas", 12), undo=True, wrap='word', borderwidth=3, relief="sunken")
        bottomLeft.add(bottomLeftTitle)
        bottomLeft.add(matches)

        videoPlayer = Label(master, 
                            height = 20,
                            width = appWidth - (appWidth // 10),
                            bg = 'red',
                            text = "VideoPlayer",)
        videoPlayer.grid(row=0, column=1)

        videoSkimmer = Label(master, 
                            height = 20,
                            width = appWidth - (appWidth // 10),
                            bg = 'yellow',
                            text = "VideoSkimmer",)
        videoSkimmer.grid(row=1, column=1)
示例#15
0
def main():
    root=tk.Tk()

    main_paned_window = PanedWindow(root)
    main_paned_window.pack(fill=BOTH, expand=1)

    tone_curve_paned_window=PanedWindow(main_paned_window)
    main_paned_window.add(tone_curve_paned_window)
    
    tone_curve_window=PanedWindow(tone_curve_paned_window,relief=tk.GROOVE,bd=3,orient=tk.VERTICAL)
    mlp_tone_curve_window=MatplotlibWindow2(tone_curve_window)
    mlp_tone_curve_window.canvas.get_tk_widget().pack(fill=tk.BOTH,expand=True)

    #text_panel_left = Text(main_paned_window, height=6, width =15,relief=tk.GROOVE,bd=2)
    #main_paned_window.add(text_panel_left)

    sub_paned_window = PanedWindow(main_paned_window, orient=tk.VERTICAL)

    #plot sin curve
    plot_paned_window=PanedWindow(sub_paned_window,relief=tk.GROOVE,bd=3,orient=tk.VERTICAL)
    mlp_window=MatplotlibWindow(plot_paned_window)
    mlp_window.canvas.get_tk_widget().pack(fill=tk.BOTH,expand=True)


    main_paned_window.add(sub_paned_window)
    bottom_pane_text = Text(sub_paned_window, height=3, width =3, relief=tk.SUNKEN,bd=2)
    
    sub_paned_window.add(plot_paned_window)
    sub_paned_window.add(bottom_pane_text)




    button=Button(root,text="Hello")
    button.pack()

    root.mainloop()
示例#16
0
class DatabaseView:
    def __init__(self, root, config_save, rest_client_factory):
        self.config = config_save.get_configuration()
        self.root = root
        application_folder = BrowserConfiguration.get_application_directory_and_create_if_necessary()
        self.database = XnatDatabase(rest_client_factory.create_rest_client(self.config), self.config, application_folder)
        self.database_models = XnatModelFactory(self.database)
        self.config_save = config_save

        self.master_paned_window = PanedWindow(root)
        self.master_paned_window.pack(fill=BOTH, expand=1)

        self._project_listbox = LabeledListBox(self.master_paned_window, self.database_models.project_list_model, 'Project:')
        self.master_paned_window.add(self._project_listbox)

        self._subject_listbox = LabeledListBox(self.master_paned_window, self.database_models.subject_list_model, 'Subject:')
        self.master_paned_window.add(self._subject_listbox)

        self._scan_listbox = LabeledProgressListBox(self.master_paned_window, self.database_models.scan_list_model, "Scans:")
        self.master_paned_window.add(self._scan_listbox)

    def close(self):
        self.master_paned_window.destroy()
示例#17
0
文件: panes.py 项目: limboaz/Nonogram
    def __init__(self, master):
        self.master = PanedWindow()
        master.title("Nonogram")
        m1 = PanedWindow()
        m1.pack(fill=BOTH, expand=1)

        left = Label(m1, text="left pane")

        m1.add(left)

        m2 = PanedWindow(m1, orient=VERTICAL)
        m1.add(m2)

        self.new_button = Button(m2,
                                 text="New puzzle",
                                 command=self.new_puzzle)
        self.new_button.pack()
        self.save_button = Button(m2,
                                  text="Save puzzle",
                                  command=self.save_puzzle)
        self.save_button.pack()

        bottom = Label(m2, text="bottom pane")
        m2.add(bottom)
示例#18
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(" ","_")
        self.content=self
#        try :
#            self.image = image.load(os.path.join("Card",name+".png"))
#        except :
#            self.image=None
    def equivalentto(self,other) :
        return self==other
    def show(self) :
        pass
    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 **"
            S = 0
            for p in self.bonus:
                if p.is_cost_alterator:
                    S += p.getCost(self)
                else:
                    S += p.getCost()
            cost=S# +0.5*(len(self.bonus)-1): why?
        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 stars<0 : stars=0
        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" or self.name=="change name" or self.name in Card.blocked_creature :
            self.name="change name"
            self.refreshWidget()
            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"),("Errant","Incarnation"),
                      ("Camouflage","Provocation"),("Camouflage","ChaqueTour"),("NePeutPasAttaquer","ALaPlaceDeLAttaque"),
                      ("NePeutPasAttaquer","NePeutPasAttaquerLesHeros"),("NePeutPasAttaquerLesHeros","ALaPlaceDeLAttaque"),
                    ("GardienDeVie","QuandIlEstBlesse"),("Charge","NePeutPasRisposter"),("Furie","ALaPlaceDeLAttaque"),
                    ("NePeutPasRiposter","NePeutPasAttaquer"),("NePeutPasRiposter","CoutReduit"),("CriDeGuerre","Incarnation"),
                    ("Charge","CriDeGuerrre"),("Insaisissable","InsensibleALaMagie"),("Charge","Errant"),("CriDeGuerre","Errant"),
                    ("Errant","RaleDAgonie"),("AttaqueADistance","AvecAttaque"),("Errant","AuDebutDuProchainTour"),
                    ("BonusParEnnemi","Determine"),("QuandIlEstBlesse","Incassable"),("Souffrant","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
        total=self.constructor()
        if "QuandUnAllieEstTue" in nb and (("Spell.Invocation" in total) or ("CopieMain"  in total) or ("PlaceCarteDansMain" in total)):
            showinfo("Not Allowed","You can't have anything to do with Invocation or card creation if you have QuandUnAllieEstTue")
            return False
        return True
 
    def save(self,*args):
        if (self.name in Card.blocked_creature) :
            return
        for b in self.bonus : # on veut que la plainte maudite soit en dernier
            if b.__class__.__name__=="PlainteMaudite" :
                self.bonus.remove(b)
                self.bonus.append(b)
                break
        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(bytes("\n".join([m.constructor() for k,m in sorted(loaded_monsters.items())]),'UTF-8'))
#        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(bytes("\n".join([m.constructor() for m in all_monsters.values()]),'UTF-8'))
        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(bytes("\n".join([m.constructor() for k,m in sorted(all_monsters.items())]),'UTF-8'))
            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())
        creature = Card.monster_list[self.opening.get()]
        if not ( creature.name in Card.blocked_creature) :
            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)
        else:
            showinfo("Sorry","You can't open this monsters because he comes from the campaign.")
         
    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 creature in Card.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(bytes("\n".join([m.constructor() for m in all_monsters.values()]), 'UTF-8'))            
            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 :
                print('dmv',dm.values())
                savefile.write(bytes("\n".join([m.constructor() for m in dm.values()]), 'UTF-8'))
            print ("deletion of monster ",  creature, " in ",fm," done" )
        else :
            print (creature," not found in dedicated file")
            
            
        
    def choosePhoto(self,*args) :
        from tkinter.filedialog import askopenfilename
        #Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
        filename = askopenfilename(defaultextension=".gif",filetypes=[ ("image",("*.jpg", "*.gif","*.png")),('PNG file','*.png'),('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 :
                pilImage = Image.open(filename)
                PhotoImage(pilImage,master=None)
                #ImageTk.PhotoImage(monimage)
                self.photofile=filename
                print ("photo choosen !")
            except Exception :
                print ("echec ouverture image")
                raise
        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()
        import unicodedata
        #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) :
            try :
                assert('"' not in name.get())
                name.get().encode('ascii')
            except Exception as e:
                print ("error on name")
                name.set(self.name)
                return
            old = self.name in Card.blocked_creature
            self.name=name.get()
            if old or self.name in Card.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 :
                pilImage=Image.open(self.photofile)
                img=PhotoImage(pilImage,master=image_zone)
            except :
               decomp=self.photofile.split('/')
               for i in range(1,6) :
                   try :
                       fname="/".join(decomp[-i:])
                       print ("try to open",fname)
                       pilImage = Image.open(fname)
                       img=PhotoImage(pilImage,master=image_zone)
                       self.photofile=fname
                       break
                   except :
                       self.photofile=None
        if self.photofile :
            w, h = img.width(), img.height()
            print('wh',w,h)
            if h>400 :
                print("reduction")
                img=PhotoImage(pilImage.resize((w//2,h//2), Image.ANTIALIAS),master=image_zone)
            image_zone=Button(self.card_win,image=img,  command=self.choosePhoto)
            image_zone.image=img
            #image_zone.configure(image=image_zone.image,width=50,height=50,compound=RIGHT)
            #image_zone.pack()
            #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) :
            if addBonus.get()!= "add bonus":
                name=addBonus.get()
            else:
                name=add_cost_alteration.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 = Spell.getSpellMenu(power_zone, addBonus)
        else: addBonus_wid = getBonusMenu(power_zone, addBonus) 
        addBonus.trace('w', addPower)
        if self.pv>0 or len(self.bonus)==0 or all([b.is_cost_alterator for b in self.bonus]):
            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" and not(self.name in Card.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 = [na for na in Card.monster_list.keys() if na not in Card.blocked_creature]
            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 = [na for na in Card.monster_list.keys() if na not in Card.blocked_creature]
            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) pilImage = Image.open(
        #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(150.*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 if b.getDescription()])
            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):
            if b!=[''] :
                print ("power",b)
                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,spells=False):
        # 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 = [ m for m in Card.monster_list.keys() if (spells or all_monsters[m].pv>0) and not(m in Card.blocked_creature) 
                  and (spells or not "PlainteMaudite" in all_monsters[m].constructor())
                   and not any([b.__class__.__name__=="Charge" for b in all_monsters[m].bonus])
                   and not any([b.__class__.__name__=="Errant" for b in all_monsters[m].bonus])
                   and not any([b.__class__.__name__=="Essentiel" for b in all_monsters[m].bonus])
                   and not any([b.__class__.__name__=="Incarnation" for b in all_monsters[m].bonus])
                   #and not any([b.__class__.__name__=="AuDebutDuProchainTour" for b in all_monsters[m].bonus])
                   ]
        self.widget=OptionMenu(master,self.content,*l)
        return self.widget
 
    def init_as_card(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 = [ m for m in Card.monster_list.keys() if  not(m in Card.blocked_creature)  ]
        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()
示例#19
0
    def refreshWidget(self) :
        #print "refresh"
        self.card_win.pack_forget()
        import unicodedata
        #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) :
            try :
                assert('"' not in name.get())
                name.get().encode('ascii')
            except Exception as e:
                print ("error on name")
                name.set(self.name)
                return
            old = self.name in Card.blocked_creature
            self.name=name.get()
            if old or self.name in Card.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 :
                pilImage=Image.open(self.photofile)
                img=PhotoImage(pilImage,master=image_zone)
            except :
               decomp=self.photofile.split('/')
               for i in range(1,6) :
                   try :
                       fname="/".join(decomp[-i:])
                       print ("try to open",fname)
                       pilImage = Image.open(fname)
                       img=PhotoImage(pilImage,master=image_zone)
                       self.photofile=fname
                       break
                   except :
                       self.photofile=None
        if self.photofile :
            w, h = img.width(), img.height()
            print('wh',w,h)
            if h>400 :
                print("reduction")
                img=PhotoImage(pilImage.resize((w//2,h//2), Image.ANTIALIAS),master=image_zone)
            image_zone=Button(self.card_win,image=img,  command=self.choosePhoto)
            image_zone.image=img
            #image_zone.configure(image=image_zone.image,width=50,height=50,compound=RIGHT)
            #image_zone.pack()
            #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) :
            if addBonus.get()!= "add bonus":
                name=addBonus.get()
            else:
                name=add_cost_alteration.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 = Spell.getSpellMenu(power_zone, addBonus)
        else: addBonus_wid = getBonusMenu(power_zone, addBonus) 
        addBonus.trace('w', addPower)
        if self.pv>0 or len(self.bonus)==0 or all([b.is_cost_alterator for b in self.bonus]):
            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" and not(self.name in Card.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 = [na for na in Card.monster_list.keys() if na not in Card.blocked_creature]
            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 = [na for na in Card.monster_list.keys() if na not in Card.blocked_creature]
            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()                      
示例#20
0
class PyLatency:
    """Ping tool visualization with tkinter"""
    def __init__(self, root):
        """Setup window geometry & widgets + layout, init counters"""

        self.master = root
        self.master.title("pyLatency")
        self.appdata_dir = getenv("APPDATA") + "/pyLatency"
        self.options_path = self.appdata_dir + "/options.json"
        self.log_dir = self.appdata_dir + "/logs"
        self.logfile = None

        self.options_logging = BooleanVar()
        self.options_geometry = ""

        self.options = self.init_options()
        if self.options:
            self.options_geometry = self.options["geometry"]
            self.options_logging.set(self.options["logging"])

        if self.options_geometry:
            self.master.geometry(self.options_geometry)
        else:
            self.master.geometry("400x200")

        self.master.minsize(width=400, height=200)
        self.master.update()

        self.running = False
        self.hostname = None
        self.RECT_SCALE_FACTOR = 2
        self.TIMEOUT = 5000
        self.minimum = self.TIMEOUT
        self.maximum = 0
        self.average = 0
        self.SAMPLE_SIZE = 1000
        self.sample = deque(maxlen=self.SAMPLE_SIZE)
        self.pcount = 0
        self.max_bar = None
        self.min_bar = None

        # Widgets:
        self.frame = Frame(self.master)

        self.lbl_entry = Label(self.frame, text="Host:")
        self.lbl_status_1 = Label(self.frame, text="Ready")
        self.lbl_status_2 = Label(self.frame, fg="red")
        self.entry = Entry(self.frame)

        self.btn_start = Button(self.frame, text="Start", command=self.start)

        self.btn_stop = Button(self.frame, text="Stop", command=self.stop)

        self.chk_log = Checkbutton(self.frame,
                                   text="Enable log",
                                   variable=self.options_logging)

        self.delay_scale = Scale(
            self.frame,
            label="Interval (ms)",
            orient="horizontal",
            from_=100,
            to=self.TIMEOUT,
            resolution=100,
        )
        self.delay_scale.set(1000)

        self.paneview = PanedWindow(self.master, sashwidth=5, bg="#cccccc")
        self.left_pane = PanedWindow(self.paneview)
        self.right_pane = PanedWindow(self.paneview)
        self.paneview.add(self.left_pane)
        self.paneview.add(self.right_pane)

        self.canvas_scroll_y = Scrollbar(self.left_pane)
        self.canvas = Canvas(self.left_pane,
                             bg="#FFFFFF",
                             yscrollcommand=self.canvas_scroll_y.set)
        self.canvas_scroll_y.config(command=self.canvas.yview)
        self.left_pane.add(self.canvas_scroll_y)

        self.ping_list_scroll = Scrollbar(self.master)
        self.ping_list = Listbox(self.right_pane,
                                 highlightthickness=0,
                                 font=14,
                                 selectmode="disabled",
                                 yscrollcommand=self.ping_list_scroll.set)
        self.ping_list_scroll.config(command=self.ping_list.yview)
        self.right_pane.add(self.ping_list_scroll)

        self.left_pane.add(self.canvas)
        self.right_pane.add(self.ping_list)

        # Layout:
        self.master.columnconfigure(0, weight=1)
        self.master.rowconfigure(1, weight=1)

        self.frame.columnconfigure(1, weight=1)

        self.frame.grid(row=0, column=0, sticky="nsew")

        self.lbl_entry.grid(row=0, column=0)
        self.lbl_status_1.grid(row=1, column=0, columnspan=4)
        self.lbl_status_2.grid(row=2, column=0, columnspan=4)
        self.entry.grid(row=0, column=1, sticky="ew")
        self.btn_start.grid(row=0, column=2)
        self.btn_stop.grid(row=0, column=3)
        self.chk_log.grid(row=1, column=2, columnspan=2)
        self.delay_scale.grid(row=0, column=4, rowspan=2)

        # self.canvas_scroll_y.grid(row=1, column=2, sticky="ns")
        self.paneview.grid(row=1, column=0, sticky="nsew")
        # self.ping_list_scroll.grid(row=1, column=1, sticky="ns")

        self.paneview.paneconfigure(
            self.left_pane,
            width=(self.master.winfo_width() -
                   self.delay_scale.winfo_reqwidth()),
        )

        #Bindings:
        self.canvas.bind("<MouseWheel>", self.scroll_canvas)

        self.master.bind("<Return>", self.start)
        self.master.bind("<Escape>", self.stop)
        self.master.bind("<Control-w>", lambda event: self.master.destroy())
        self.master.bind(
            "<Up>",
            lambda event: self.delay_scale.set(self.delay_scale.get() + 100))
        self.master.bind(
            "<Down>",
            lambda event: self.delay_scale.set(self.delay_scale.get() - 100))

        self.master.protocol("WM_DELETE_WINDOW", self.master_close)

    def __str__(self):
        """Return own address"""

        return f"pyLatency GUI @ {hex(id(self))}"

    def start(self, event=None):
        """
            Reset the GUI, create & start a thread so we don't block
            the mainloop during each poll. 
        """

        if not self.running:
            self.hostname = self.entry.get()
            if self.hostname:
                self.ping_list.delete(0, "end")
                self.canvas.delete("all")
                self.lbl_status_1.config(text="Running", fg="green")
                self.lbl_status_2.config(text="")

                self.sample.clear()

                (self.minimum, self.maximum, self.average,
                 self.pcount) = self.TIMEOUT, 0, 0, 0

                self.running = True
                self.thread = Thread(target=self.run, daemon=True)
                self.thread.start()
            else:
                self.lbl_status_2.config(text="Missing Hostname")

    def logged(fn):
        """
            decorates self.run(), create a log directory if one doesn't
            exist, create a filename with a date & timestamp, call self.run()
            with logging enabled or disabled
        """
        @wraps(fn)
        def inner(self):
            if self.options_logging.get():
                if not exists(self.log_dir):
                    mkdir(self.log_dir)

                timestamp = datetime.now()
                fname = timestamp.strftime("%a %b %d @ %H-%M-%S")

                with open(self.log_dir + f"/{fname}.txt",
                          "w+") as self.logfile:
                    self.logfile.write(f"pyLatency {fname}\n")
                    self.logfile.write(f"Host: {self.hostname}\n")
                    self.logfile.write("-" * 40 + "\n")
                    start = default_timer()
                    fn(self)
                    end = default_timer()
                    elapsed = end - start
                    self.logfile.write("-" * 40 + "\n")
                    self.logfile.write(
                        f"Logged {self.pcount} pings over {int(elapsed)} seconds"
                    )
            else:
                fn(self)

        return inner

    @logged
    def run(self):
        """
            Continuously shell out to ping, get an integer result, 
            update the GUI, and wait. 
        """

        while self.running:
            latency = self.ping(self.hostname)
            self.pcount += 1

            if latency is None:
                self.stop()
                self.lbl_status_2.config(text="Unable to ping host")
                return
            if latency > self.maximum:
                self.maximum = latency
            if latency < self.minimum:
                self.minimum = latency

            self.sample.append(latency)
            self.average = sum(self.sample) / len(self.sample)

            if self.logfile:
                self.logfile.write(str(latency) + "\n")

            self.update_gui(latency)
            sleep(self.delay_scale.get() / 1000)

    def update_gui(self, latency):
        """
            Update the listbox, shift all existing rectangles, draw the latest
            result from self.ping(), cleanup unused rectangles, update the mainloop
        """

        if self.ping_list.size() >= self.SAMPLE_SIZE:
            self.ping_list.delete(self.SAMPLE_SIZE - 1, "end")

        self.ping_list.insert(0, str(latency) + "ms")

        self.canvas.move("rect", 10, 0)
        self.canvas.create_rectangle(0,
                                     0,
                                     10,
                                     int(latency * self.RECT_SCALE_FACTOR),
                                     fill="#333333",
                                     tags="rect",
                                     width=0)

        self.canvas.delete(self.max_bar)
        self.max_bar = self.canvas.create_line(
            0,
            self.maximum * self.RECT_SCALE_FACTOR,
            self.canvas.winfo_width(),
            self.maximum * self.RECT_SCALE_FACTOR,
            fill="red",
        )
        self.canvas.delete(self.min_bar)
        self.min_bar = self.canvas.create_line(
            0,
            self.minimum * self.RECT_SCALE_FACTOR,
            self.canvas.winfo_width(),
            self.minimum * self.RECT_SCALE_FACTOR,
            fill="green",
        )

        # canvas scrollable region is not updated automatically
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

        self.lbl_status_2.config(fg="#000000",
                                 text=f"Min: {self.minimum} "
                                 f"Max: {self.maximum} "
                                 f"Avg: {round(self.average,2):.2f}")

        self.cleanup_rects()
        self.master.update()

    def scroll_canvas(self, event):
        """
            Bound to <MouseWheel> tkinter event on self.canvas.
            Respond to Linux or Windows mousewheel event, and scroll
            the canvas accordingly
        """

        count = None
        if event.num == 5 or event.delta == -120:
            count = 1
        if event.num == 4 or event.delta == 120:
            count = -1
        self.canvas.yview_scroll(count, "units")

    def cleanup_rects(self):
        """Delete rectangles that are outside the bbox of the canvas"""

        for rect in self.canvas.find_withtag("rect"):
            if self.canvas.coords(rect)[0] > self.canvas.winfo_width():
                self.canvas.delete(rect)

    def stop(self, event=None):
        """Satisfy the condition in which self.thread exits"""

        if self.running:
            self.running = False
            self.lbl_status_1.config(text="Stopped", fg="red")

    def master_close(self, event=None):
        """Writes window geometry/options to the disk."""

        options = dumps({
            "geometry": self.master.geometry(),
            "logging": self.options_logging.get()
        })

        if not exists(self.appdata_dir):
            mkdir(self.appdata_dir)

        with open(self.options_path, "w+") as options_file:
            options_file.write(options)

        self.master.destroy()

    def init_options(self):
        """Called on startup, loads, parses, and returns options from json."""

        if exists(self.options_path):
            with open(self.options_path, "r") as options_file:
                options_json = options_file.read()

            return loads(options_json)
        else:
            return None

    @staticmethod
    def ping(url):
        """
            Shell out to ping and return an integer result.
            Returns None if ping fails for any reason: timeout, bad hostname, etc.
        """

        flag = "-n" if platform == "win32" else "-c"
        result = run(["ping", flag, "1", "-w", "5000", url],
                     capture_output=True,
                     creationflags=DETACHED_PROCESS)
        output = result.stdout.decode("utf-8")
        try:
            duration = findall("\\d+ms", output)[0]
            return int(duration[:-2])
        except IndexError:
            return None
示例#21
0
    def __init__(self, *args, **kwargs):
        '''
node_name:   The name of this node. Usually set by ModelNode.__setattr__ automatically.
figure_meta: Meta information of figure.
The rest parameters are passed to PanedWindow.__init__.
'''
        node_name    = kwargs.pop('node_name', '')
        super().__init__(node_name=node_name)

        figure_meta = None if 'figure_meta' not in kwargs \
            else kwargs.pop('figure_meta')
        kwargs['orient'] = 'horizontal'
        
        paned_window = PanedWindow(*args, **kwargs)

        paned_window.config(sashwidth=4, sashrelief='groove', bg='forestgreen')        
       
#        figureTabsStyle = Style()
#        figureTabsStyle.configure('Figure.TNotebook', tabposition='sw')       
#        figureTabs    = Notebook(paned_window, style='Figure.TNotebook')
        figureTabs  = Notebook(paned_window)
        
        self.figureTabs   = figureTabs
        figureTabs.bind('<<NotebookTabChanged>>', self._on_tab_change)
        self.lock_attribute('figureTabs')
        
        if figure_meta:
            self.make_figures(figure_meta)
            
        self.lock_elements()    
        
        paned_window.add(figureTabs, stretch='always')
        

        listPan     = PanedWindow(paned_window, orient='vertical')
        listPan.config(sashwidth=4, sashrelief='groove', bg='forestgreen')        
        paned_window.add(listPan, stretch='never')

        
        listFrm     = Frame(listPan)
        listPan.add(listFrm, stretch='always')        
        Label(listFrm, text='Curves', bg='#b5d6b0').pack(side='top', fill='x')
        self.__list = ScrolledList(listFrm, relief='groove')
        self.__list.list_config(width=20)
        self.__list.list_click_callback = self._on_list_click
        self.__list.pack(fill='both', expand='yes')

        listFrm     = Frame(listPan)        
        listPan.add(listFrm, stretch='never')
        Label(listFrm, text='Indicators', bg='#b5d6b0').pack(side='top', fill='x')
        self.__indicator_listbox = ScrolledList(listFrm, relief='groove')
        self.__indicator_listbox.list_config(width=20)
        self.__indicator_listbox.pack(fill='both', expand='yes')
                      
        with self.attribute_lock:
            set_attributes(self,
                paned_window = paned_window,
                grid_group_observer = self.GridGroupObserver(self), 
                axis_group_observer = self.AxisGroupObserver(self),
                clear_group_observer = self.ClearGroupObserver(self),
                label_group_observer = self.LabelGroupObserver(self),
                indicator_group_observer = self.IndicatorGroupObserver(self),
                data_figure_observer = self.DataFigureObserver(self),
                data_pool    = []
            )
示例#22
0
class PyEd(Frame):
    def __init__(self, file=None, parent=None):
        Frame.__init__(self, parent, name="base")
        self.file = file
        self.make_menu()

        self.pw = PanedWindow(self, orient=VERTICAL)
        self.pw.pack(side=TOP, expand=YES)
        self.text = Text(self.pw)
        self.pw.add(self.text)
        self.output = Text(self.pw)
        self.pw.add(self.output)

        if self.file:
            self.master.title(self.file)
            self.settext()
        else:
            self.master.title("Untitled")
        self.text.focus()

        self.makestatus()
        self.update_status_msg("Welcome")

        self.bind_all("<Control-n>", self.new)
        self.bind_all("<Control-s>", self.save)
        self.bind_all("<Control-q>", self.quit)
        self.text.bind("<KeyPress>", self.update_pos)

    def make_menu(self):
        self.menubar = Frame(self)
        self.menubar.pack(side=TOP)

        filebtn = Menubutton(self.menubar, text='File')
        filebtn.pack(side=LEFT)
        file = Menu(filebtn, tearoff=0)
        file.add_command(label='New', command=self.new, accelerator="Ctrl+N")
        file.add_command(label='Save', command=self.save, accelerator="Ctrl+S")
        file.add_command(label='Quit', command=self.quit, accelerator="Ctrl+Q")
        filebtn.config(menu=file)

        editbtn = Menubutton(self.menubar, text='Edit')
        editbtn.pack(side=LEFT)
        edit = Menu(editbtn, tearoff=0)
        edit.add_command(label='Cut', command=self.cut)
        edit.add_command(label='Copy', command=self.copy)
        edit.add_command(label='Paste', command=self.paste)
        editbtn.config(menu=edit)

        if self.file:
            self.make_file_type_menu(self.menubar)

    def make_file_type_menu(self, menubar):
        _, e = os.path.splitext(self.file)
        ext = e[1:]
        if ext == "py":
            pybtn = Menubutton(menubar, text='Python', name=ext)
            pybtn.pack(side=LEFT)
            py = Menu(pybtn, tearoff=0)
            py.add_command(label='Compile',
                           command=self.compile_python,
                           accelerator="Ctrl+F5")
            py.add_command(label='Run',
                           command=self.run_python,
                           accelerator="F5")
            pybtn.config(menu=py)
            self.bind_all("<Control-F5>", self.compile_python)
            self.bind_all("<F5>", self.run_python)
        elif ext == "tcl":
            tclbtn = Menubutton(menubar, text='TCL', name=ext)
            tclbtn.pack(side=LEFT)
            tcl = Menu(tclbtn, tearoff=0)
            tcl.add_command(label='Run',
                            command=self.run_tcl,
                            accelerator="F5")
            tclbtn.config(menu=tcl)
            self.bind_all("<F5>", self.run_tcl)

    def makestatus(self):
        statusbar = Frame(self, name="status")
        statusbar.pack(side=BOTTOM)
        msg = Label(statusbar, name="msg")
        msg.pack(side=LEFT)
        pos = Label(statusbar, name="pos")
        pos.pack(side=RIGHT)

    def update_pos(self, event):
        index = self.text.index(INSERT)
        l = self.nametowidget("status.pos")
        l.config(text=index)

    def update_status_msg(self, message):
        l = self.nametowidget("status.msg")
        l.config(text=message)
        self.after(5000, self.clear_status_msg)

    def clear_status_msg(self):
        l = self.nametowidget("status.msg")
        l.config(text="")

    def settext(self):
        if os.path.exists(self.file):
            txt = self.read_file(self.file)
            self.text.insert('1.0', txt)

    def quit(self, event=None):
        Frame.quit(self)

    def save(self, event=None):
        txt = self.text.get('1.0', END + '-1c')
        if not self.file:
            self.file = asksaveasfilename()
            self.master.title(self.file)
            self.make_file_type_menu(self.menubar)
        self.write_to_file(self.file, txt)
        self.update_status_msg("Saved")

    def new(self, event=None):
        _, e = os.path.splitext(self.file)
        ext = e[1:]
        b = self.menubar.children.get(ext)
        if b:
            b.destroy()
        self.file = None
        self.master.title("Untitled")
        self.text.delete('1.0', END)

    def write_to_file(self, file, txt):
        with open(file, 'w') as f:
            f.write(txt)

    def read_file(self, file):
        with open(file, 'r+') as f:
            txt = f.read()
            return txt

    def cut(self):
        txt = self.text.get(SEL_FIRST, SEL_LAST)
        self.text.delete(SEL_FIRST, SEL_LAST)
        self.clipboard_clear()
        self.clipboard_append(txt)

    def copy(self):
        txt = self.text.get(SEL_FIRST, SEL_LAST)
        self.clipboard_clear()
        self.clipboard_append(txt)

    def paste(self):
        txt = self.selection_get(selection='CLIPBOARD')
        self.text.insert(INSERT, txt)

    def run_python(self, event=None):
        p = subprocess.run([sys.executable, self.file],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
        self.output.insert('end', p.stdout)
        self.output.insert('end', p.stderr)
        self.output.see(END)

    def compile_python(self, event=None):
        try:
            py_compile.compile(self.file, doraise=True)
            self.output.insert('end', "%s compiled successfully\n" % self.file)
        except py_compile.PyCompileError as pyce:
            lere = re.compile('\s*File \".*\", line(\d*)')
            r = lere.match(pyce.msg)
            lineno = r.group(1)
            print(lineno)

    def run_tcl(self, event=None):
        p = subprocess.run(["tclsh8.7", self.file],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
        self.output.insert('end', p.stdout)
        self.output.insert('end', p.stderr)
        self.output.see(END)
示例#23
0
    def __init__(self, *args, **kwargs):
        '''
node_name:   The name of this node. Usually set by ModelNode.__setattr__ automatically.
figure_meta: Meta information of figure.
The rest parameters are passed to PanedWindow.__init__.
'''
        node_name = kwargs.pop('node_name', '')
        super().__init__(node_name=node_name)

        self.__selected_curve = (None, None)

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

        paned_window = PanedWindow(*args, **kwargs)

        paned_window.config(sashwidth=4, sashrelief='groove', bg='forestgreen')

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

        self.figureTabs = figureTabs
        figureTabs.bind('<<NotebookTabChanged>>', self._on_tab_change)
        self.lock_attribute('figureTabs')

        if figure_meta:
            self.make_figures(figure_meta)

        self.lock_elements()

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

        listPan = PanedWindow(paned_window, orient='vertical')
        listPan.config(sashwidth=4, sashrelief='groove', bg='forestgreen')
        paned_window.add(listPan, stretch='never')

        listFrm = Frame(listPan)
        listPan.add(listFrm, stretch='always')
        Label(listFrm, text='Curves', bg='#b5d6b0').pack(side='top', fill='x')
        self.__list = ScrolledList(listFrm, relief='groove')
        self.__list.list_config(width=20)
        self.__list.list_click_callback = self._on_list_click
        self.__list.pack(fill='both', expand='yes')

        listFrm = Frame(listPan)
        listPan.add(listFrm, stretch='never')
        Label(listFrm, text='Indicators', bg='#b5d6b0').pack(side='top',
                                                             fill='x')
        self.__indicator_listbox = ScrolledList(listFrm, relief='groove')
        self.__indicator_listbox.list_config(width=20)
        self.__indicator_listbox.pack(fill='both', expand='yes')

        with self.attribute_lock:
            set_attributes(
                self,
                paned_window=paned_window,
                grid_group_observer=self.GridGroupObserver(self),
                axis_group_observer=self.AxisGroupObserver(self),
                clear_group_observer=self.ClearGroupObserver(self),
                label_group_observer=self.LabelGroupObserver(self),
                indicator_group_observer=self.IndicatorGroupObserver(self),
                data_figure_observer=self.DataFigureObserver(self),
                data_pool=[])
示例#24
0
class UserInterface(UIfunctions):
    def __init__(self, filehandler, databasehandler, path=None):
        self.title = "OpenKeynote (BETA)"
        self._filehandler = filehandler
        self._databasehandler = databasehandler
        self.path = path
        self.itemlist = []
        self.root = Tk()
        self.previeweditem = ""
        self.editeditem = ""
        self.case_selected = IntVar()
        self.parentname = ""
        self.autosave = IntVar()
        self._html_path = None

        self._default_title = self.title
        self.main_window()
        self.tree_view()
        self.frame_vertical_bar()
        self.bindings_and_menu()
        self.frame_setup()

        self.update_status()
        self.root.mainloop()

    def main_window(self, *args):
        self.mainframe = Frame(self.root)
        self.mainframe.grid(column=0, row=0, sticky=E+W+N+S)
        self.bottomframe = Frame(self.root)
        self.bottomframe.grid(column=0, row=1, sticky=E+W)
        self.statusbar = Label(
            self.bottomframe, text=self._filehandler.statustext, anchor=W)
        self.statusbar.pack(fill=BOTH, padx=0, pady=0)
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        self.root.rowconfigure(1, pad=10)
        self.pw = PanedWindow(self.mainframe, orient=HORIZONTAL)
        self.pw.pack(fill=BOTH, expand=1)
        self.pane_left = Frame(self.root)
        self.pw.add(self.pane_left)
        self.pane_right = Frame(self.root)
        self.pw.add(self.pane_right)

        self.frame_left = Frame(self.pane_left)
        self.frame_left.pack(fill=BOTH, expand=1, padx=3, pady=3)
        self.frame_center = Frame(self.pane_right)
        self.frame_center.grid(row=0, column=0, sticky=W+N, rowspan=4)
        self.frame_right = Frame(self.pane_right)
        self.frame_right.grid(row=0, column=1, sticky=W+E+N+S, padx=3, pady=3)
        self.pane_right.columnconfigure(1, weight=1)
        self.pane_right.rowconfigure(0, weight=1)
        self.sf1 = Text(self.frame_left, height=1, width=25, borderwidth=1,
                        relief="solid", highlightthickness=0)
        self.sf1.insert(1.0, "TODO: Searchbar")
        self.sf1.grid(row=0, column=0, sticky=W+E+N+S, pady=5)
        self.sf1.config(state=DISABLED)
        self.cs = Button(self.frame_left, text="X", width=1)
        self.cs.grid(row=0, column=1)
        self.frame_left.columnconfigure(0, weight=1)

    def tree_view(self, *args):
        """
        Tree view
        """
        self.l1 = ttk.Treeview(self.frame_left, columns=["stuff"], show="tree")
        self.yscroll = Scrollbar(self.frame_left, orient=VERTICAL)
        self.yscroll.config(width=10)
        self.l1['yscrollcommand'] = self.yscroll.set
        self.yscroll['command'] = self.l1.yview
        self.l1.grid(row=1, column=0, columnspan=3,  padx=30,
                     pady=10, sticky=N+S+E+W)
        self.yscroll.grid(row=1, column=0, columnspan=3, sticky=N+S+E)
        self.l1.bind("<ButtonRelease-1>", self.change_selection)

        self.frame_left.rowconfigure(1, weight=1)

    def frame_vertical_bar(self, *args):
        self.vbs = []
        middlebuttons = ("New Item", "New Subitem", "Delete",
                         "Rename", "Change Parent","- Descriptions (BETA) -")
        middlefunctions = (
            lambda: self.add_item(parent=self.parentname),
            lambda: self.add_item(parent=self.previeweditem),
            lambda: self.delete_item_dialog(),
            self.rename_item_dialog,
            self.change_parent_dialog,
            lambda: self.description_window(database_rows=self._databasehandler.view())
            #lambda: self.save_keynote_to_database(title="title",keynote="KN10", entreprise="min entreprise", category="")
            #self.save_all_keynotes_to_database
            )

        for a, button_text in enumerate(middlebuttons):
            self.vbs.append(ttk.Button(self.frame_center, text=button_text))
            self.vbs[a].pack(fill=BOTH)
            self.vbs[a].config(command=middlefunctions[a], width=10)
        for x in [2, 3, 4]:
            self.vbs[x].config(state=DISABLED)
        self.tx1 = Label(self.frame_right, text="Preview", anchor=W)
        self.tx1.grid(row=0, column=0, columnspan=3, sticky=W+E)
        self.tx2 = Label(self.frame_right, text="Editing", anchor=W)
        self.tx2.grid(row=2, column=0, sticky=W+E)

        self.e1 = scrolledtext.ScrolledText(self.frame_right,
                                            fg="#555", font=("Courier", 13),
                                            padx=10, pady=10,
                                            highlightthickness=0,
                                            borderwidth=1, relief="solid")
        self.e1.grid(row=1, column=0, columnspan=3, sticky=N+S+E+W)
        # was Text before

        self.e2 = scrolledtext.ScrolledText(self.frame_right,
                                            font=("Courier", 13), borderwidth=1,
                                            relief="solid", padx=10, pady=10,
                                            highlightthickness=0)
        self.e2.grid(row=3, column=0, columnspan=3, sticky=E+W+S+N)
        # AUTOSAVE
        self.autosaveFrame = LabelFrame(self.frame_center, text=' Autosave ')
        self.autosaveFrame.pack(fill=BOTH)
        self.autosave.trace(
            'w', lambda *args: print(f"Autosave: {self.autosave.get()}"))
        self.autosaveCheck = Checkbutton(
            self.autosaveFrame, text="Enabled", variable=self.autosave, anchor=W)
        self.autosaveCheck.select()
        self.autosaveCheck.pack(fill=BOTH)
        self.labelsFrame = LabelFrame(self.frame_center, text=' Change Case ')
        self.labelsFrame.pack(fill=BOTH)

        # CASE BUTTONS
        self.case_radiobuttons = []
        self.case_selected.set(99)
        rbtns = ['No change', 'UPPERCASE', 'lowercase', 'First Letter']
        for a, button_text in enumerate(rbtns):
            self.case_radiobuttons.append(
                Radiobutton(self.labelsFrame, text=button_text,
                            variable=self.case_selected,
                            value=a, command=self.change_case, width=10, anchor=W))
            self.case_radiobuttons[a].grid(sticky="W", row=a)

    def change_case(self, *args):
        pass

    def bindings_and_menu(self, *args):
        """
        Main key bindings
        """
        if os.name == "nt":
            self.CTRL = "Control"
            self.MBTN = "3"
        else:
            self.CTRL = "Command"
            self.MBTN = "2"

        def bindings_key(event):
            if event.state == 8 or event.state == 12:
                return
            else:
                return("break")

        self.sf1.bind("<Tab>", lambda a: self.focus_on(target=self.l1))
        self.sf1.bind("<Shift-Tab>", lambda a: self.focus_on(target=self.vb2))
        self.e1.bind("<Key>", bindings_key)
        self.e1.bind("<Tab>", lambda a: self.focus_on(target=self.e2))
        self.e1.bind(
            "<Shift-Tab>", lambda a: self.focus_on(target=self.vbs[-1]))

        self.e2.bind("<Tab>", lambda a: self.focus_on(target=self.vb1))
        self.e2.bind("<Shift-Tab>", lambda a: self.focus_on(target=self.e1))

        self.vb1 = ttk.Button(self.frame_right, text="Edit")
        self.vb1.grid(row=2, column=1)
        self.vb1.config(command=self.edit_item)
        self.vb2 = ttk.Button(self.frame_right, text="Save")
        self.vb2.grid(row=2, column=2)
        self.vb2.config(command=self.saveitem)

        self.frame_right.rowconfigure(1, weight=1)
        self.frame_right.rowconfigure(3, weight=1)
        self.frame_right.columnconfigure(0, weight=1)

        self.menu = Menu(self.root)
        self.root.config(menu=self.menu)
        file = Menu(self.menu, tearoff=0)  # TODO is it a win thing?
        file.add_command(label='New File*', command=self.close_file)
        file.add_command(
            label='Open File...', accelerator=f"{self.CTRL}-o",
            command=self.open_file_dialog)
        file.add_command(label='Save File',
                         accelerator=f"{self.CTRL}-s", command=self.save_file)
        file.add_command(label='Save File As...',
                         command=self.save_file_dialog)
        file.add_command(label='Close file', command=self.close_file)
        file.add_command(
            label='Exit', accelerator=f"{self.CTRL}-q", command=self.client_exit)
        self.menu.add_cascade(label='File', menu=file)

        self.clickmenu = Menu(self.root, tearoff=0)
        self.clickmenu.add_command(label="Cut")
        self.clickmenu.add_command(label="Copy")
        self.clickmenu.add_command(label="Paste")
        self.root.bind_class(
            "Text", f"<Button-{self.MBTN}><ButtonRelease-{self.MBTN}>",
            lambda event=None: self.right_click_menu())

        menu_edit = Menu(self.menu, tearoff=0)
        menu_edit.add_command(label='Select All', accelerator=f"{self.CTRL}-a",
                              command=self.select_all)
        self.root.bind(f"<{self.CTRL}-a>", self.select_all)
        self.e1.bind(f"<{self.CTRL}-a>", self.select_all)

        self.e1.bind(f"<{self.CTRL}-c>", self.e1.event_generate("<<Copy>>"))
        self.e2.bind(f"<{self.CTRL}-a>", self.select_all)
        menu_edit.add_command(label='Cut', accelerator=f"{self.CTRL}-x",
                              command=lambda: self.root.event_generate("<<Cut>>"))
        menu_edit.add_command(label='Copy', accelerator=f"{self.CTRL}-c",
                              command=lambda: self.copy_text())
        menu_edit.add_command(label='Paste', accelerator=f"{self.CTRL}-v",
                              command=lambda: self.root.event_generate("<<Paste>>"))
        self.menu.add_cascade(label='Edit', menu=menu_edit)

        menu_help = Menu(self.menu, tearoff=0)
        menu_help.add_command(label='About', command=self.about)
        self.menu.add_cascade(label='Help', menu=menu_help)

        for i in "Up,Down,Right,Return,Left".split(","):
            self.root.bind("<"+i+">", self.change_selection)

        self.e1.bind("<F2>", self.rename_item_dialog)
        self.e1.bind(f"<{self.CTRL}-s>", None)
        self.e1.bind(f"<{self.CTRL}-o>", None)
        self.root.bind("<F2>", self.rename_item_dialog)
        self.root.bind(f"<{self.CTRL}-s>", self.save_file)
        self.root.bind(f"<{self.CTRL}-o>", self.open_file_dialog)

    def copy_text(self, event=None):
        w = self.root.focus_get()
        w.event_generate("<<Copy>>")

    def update_title(self, title=""):
        self.root.title(title)

    def frame_setup(self, *args):
        """
        Misc UI functions
        """

        # sharp fonts in high res (https://stackoverflow.com/questions/41315873/
        # attempting-to-resolve-blurred-tkinter-text-scaling-on-windows-10-high-dpi-disp)
        if os.name == "nt":
            # TODO
            # self.root.protocol("WM_DELETE_WINDOW", self.client_exit)
            from ctypes import windll, pointer, wintypes
            try:
                windll.shcore.SetProcessDpiAwareness(1)
            except Exception:
                pass  # this will fail on Windows Server and maybe early Windows
            # TODO: Put link to ico file on windows.
            try:
                iconpath = Path("icon.ico")
                self.root.iconbitmap(Path())
            except:
                print("error with icon")
            else:  # mac?
                self.root.createcommand('exit', self.client_exit)

        self.root.title(self.title)
        if self.path:
            self.open_file(path=self.path)

        """ TODO: ICON /Windows

        self.root.iconbitmap("/Users/msn/Dropbox/py/Git/OpenKeynote/images/ico.icns")

        img = Image(
            "photo", file="/Users/msn/Dropbox/py/Git/OpenKeynote/images/large.gif")
        self.root.iconphoto(True, img) # you may also want to try this.
        self.root.call('wm','iconphoto', self.root._w, img)
        """
        self.width = min(int(self.root.winfo_screenwidth()-500), 1500)
        self.height = int(self.root.winfo_screenheight()-500)
        self.root.winfo_width()
        self.root.winfo_height()
        self.x = (self.root.winfo_screenwidth() // 2) - (self.width // 2)
        # self.x = 0
        self.y = (self.root.winfo_screenheight() // 2) - (self.height // 2)
        # self.y = 50
        self.root.geometry(f"{self.width}x{self.height}+{self.x}+{self.y}")
        self.root.update()
        self.root.after(0, self.fixUI)

    def right_click_menu(self, event=None):
        x, y = self.root.winfo_pointerxy()
        w = self.root.winfo_containing(x, y)
        # https://stackoverflow.com/a/8476726/11514850
        # w = self.root
        self.clickmenu.entryconfigure("Cut",
                                      command=lambda: w.event_generate("<<Cut>>"))
        self.clickmenu.entryconfigure("Copy",
                                      command=lambda: w.event_generate("<<Copy>>"))
        self.clickmenu.entryconfigure("Paste",
                                      command=lambda: w.event_generate("<<Paste>>"))
        self.clickmenu.tk.call("tk_popup", self.clickmenu,
                               w.winfo_pointerx(), w.winfo_pointery())

    def update_status(self, event=None):
        """
        Set statusbar in bottom of the window
        """
        self.statusbar.config(text=self._filehandler.refresh_status())
        self.root.after(100, self.update_status)

    def client_exit(self, *args):
        answer = messagebox.askyesnocancel('quit?', 'Save file first?')
        if answer == True:
            self.save_file()
            sys.exit()
        if answer == None:
            return
        if answer == False:
            exit()
示例#25
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.title("i.MX Smart-Boot Tool")
        self.wm_minsize(600, 450)

        # Top separator
        ttk.Frame(self).pack(fill='x', pady=4)

        # --------------------------------------------------------------------------------------------------------------
        # Device selection drop-box with scan button
        # --------------------------------------------------------------------------------------------------------------
        frame = ttk.Frame(self)
        frame.pack(fill='x', padx=5)

        self.devices_box = ttk.Combobox(frame, state='readonly')
        self.devices_box.pack(side='left', fill='x', expand=True, padx=2, pady=3)

        self.scan_button = ttk.Button(frame, text="Scan", command=self.on_scan_button_clicked)
        self.scan_button.pack(side='right', padx=2, pady=2)

        # --------------------------------------------------------------------------------------------------------------
        # SMX File inbox with open button
        # --------------------------------------------------------------------------------------------------------------
        frame = ttk.Frame(self)
        frame.pack(fill='x', padx=5)

        self.smx_path = ttk.Entry(frame)
        self.smx_path.pack(side='left', fill='x', expand=True, padx=2, pady=0)

        self.open_button = ttk.Button(frame, text="Open", command=self.on_open_button_clicked)
        self.open_button.pack(side='right', padx=2, pady=2)

        # --------------------------------------------------------------------------------------------------------------
        # Body
        # --------------------------------------------------------------------------------------------------------------
        pw = PanedWindow(self, orient='vertical')
        pw.pack(fill='both', expand=True, padx=6, pady=2)

        frame = ttk.Frame()
        frame.pack(fill='x', padx=4)

        self.script_view = ttk.Treeview(frame, height=5, columns=('num', 'name', 'desc'), show="headings")
        self.script_view.heading('num', text='-')
        self.script_view.heading('name', text='Name')
        self.script_view.heading('desc', text='Description')
        self.script_view.column('num', minwidth=25, width=25, anchor='center', stretch='no')
        self.script_view.column('name', minwidth=160, width=160, anchor='center', stretch='no')
        self.script_view.column('desc', width=100, anchor='w')
        self.script_view.pack(side='left', fill='both', expand=True)

        vsb1 = ttk.Scrollbar(frame, orient="vertical", command=self.script_view.yview)
        vsb1.pack(side='right', fill='y')
        self.script_view.configure(yscrollcommand=vsb1.set)

        pw.add(frame)
        pw.paneconfig(frame, minsize=95, height=95)

        frame = ttk.Frame()
        frame.pack(fill='both', padx=4)

        self.log_view = ttk.Treeview(frame, height=5, columns=('desc',), show='', selectmode='none')
        self.log_view.column('desc', anchor='w')
        self.log_view.pack(side='left', fill='both', expand=True)

        vsb2 = ttk.Scrollbar(frame, orient="vertical", command=self.log_view.yview)
        vsb2.pack(side='right', fill='y')
        self.log_view.configure(yscrollcommand=vsb2.set)

        pw.add(frame)
        pw.paneconfig(frame, minsize=85)

        self.progressbar = ttk.Progressbar(self, orient="horizontal", mode="determinate")
        self.progressbar["maximum"] = PGRANGE
        self.progressbar.pack(fill='x', padx=6, pady=2)

        # --------------------------------------------------------------------------------------------------------------
        # Buttons
        # --------------------------------------------------------------------------------------------------------------
        frame = ttk.Frame(self)
        frame.pack(fill='x', side='bottom', padx=4, pady=5)

        self.about_button = ttk.Button(frame, text="About", command=self.on_about_button_clicked)
        self.about_button.pack(side='left', padx=2, pady=2)
        self.info_button = ttk.Button(frame, text="DevInfo", command=self.on_info_button_clicked, state='disabled')
        self.info_button.pack(side='left', padx=2, pady=2)
        self.exit_button = ttk.Button(frame, text="Exit", command=self.on_exit_button_clicked)
        self.exit_button.pack(side='right', padx=2, pady=2)
        self.start_button = ttk.Button(frame, text="Start", command=self.on_start_button_clicked, state='disabled')
        self.start_button.pack(side='right', padx=2, pady=2)

        self.queue = queue.Queue()

        # USB hotplug (Linux only)
        # self.hotplug.attach(self.scan_usb)
        # self.hotplug.start()
        # TODO: Fix USB hot-plug
        self.scan_usb()
示例#26
0
class PreferencesFrame(FrameTemplate):
    """Used to set decision maker's preferences for use in prioritization."""

    # Label used for button to select frame in the main program.
    buttonLabel = 'Prioritization'
    # Image used on button to select frame, when frame is active.
    activeIcon = 'icons/Prioritization_ON.gif'
    # Image used on button to select frame, when frame is inactive.
    inactiveIcon = 'icons/Prioritization_OFF.gif'
    # Help text to be displayed when screen is active.
    helpText = ("Select a decision maker from the column at left by clicking "
                "its 'Edit' button.  Enter preferred conditions using the "
                "inputs to the right.  Preferred conditions for the selected "
                "decision maker are shown at the far right, from most "
                "important at the top, to least important at the bottom.")

    # ########################     INITIALIZATION  ################################
    def __init__(self, master, conflict, *args):
        """Initialize the Frame. Does not build widgets."""
        FrameTemplate.__init__(self, master, conflict, self.buttonLabel,
                               self.activeIcon, self.inactiveIcon,
                               self.helpText)

        self.lastBuildDMs = None
        self.lastBuildOptions = None
        self.lastBuildInfeasibles = None
        self.lastBuildRanking = None

# ############################     METHODS  ###################################

    def hasRequiredData(self):
        """Check that minimum data required to render the frame exists."""
        if len(self.conflict.decisionMakers) < 1:
            return False
        if len(self.conflict.options) < 1:
            return False
        if len(self.conflict.feasibles) < 1:
            self.conflict.recalculateFeasibleStates()
            if len(self.conflict.feasibles) < 1:
                return False
        else:
            return True

    def dataChanged(self):
        """Check if data has changed since the last build of the Frame."""
        if self.lastBuildDMs != self.conflict.decisionMakers.export_rep():
            return True
        if self.lastBuildOptions != self.conflict.options.export_rep():
            return True
        if self.lastBuildInfeasibles != self.conflict.infeasibles.export_rep():
            return True
        if self.lastBuildRanking != self.conflict.useManualPreferenceRanking:
            return True
        else:
            return False

    def buildFrame(self):
        """Contruct frame widgets and initialize data."""
        if self.built:
            return

        # Ensure all required parts of the conflict model are properly set-up.
        self.conflict.reorderOptionsByDM()
        self.conflict.options.set_indexes()
        self.conflict.infeasibles.validate()
        self.conflict.recalculateFeasibleStates()

        for dm in self.conflict.decisionMakers:
            dm.calculatePerceived()
            dm.calculatePreferences()

        self.lastBuildDMs = self.conflict.decisionMakers.export_rep()
        self.lastBuildOptions = self.conflict.options.export_rep()
        self.lastBuildInfeasibles = self.conflict.infeasibles.export_rep()
        self.lastBuildRanking = self.conflict.useManualPreferenceRanking

        # Define variables that will display in the infoFrame
        numD = len(self.conflict.decisionMakers)
        self.infoText = StringVar(
            value='Valid Preferences set for {0}/{0} DMs.'.format(numD))

        # Define frame-specific variables
        self.dm = None

        # infoFrame: frame and label definitions (with master 'self.infoFrame')
        self.infoLabel = ttk.Label(self.infoFrame, textvariable=self.infoText)

        # helpFrame: frame and label definitions (with master 'self.helpFrame')
        self.helpLabel = ttk.Label(self.helpFrame,
                                   textvariable=self.helpVar,
                                   wraplength=150)

        # Define frame-specific input widgets (with 'self' as master)
        self.paneMaster = PanedWindow(self,
                                      orient=VERTICAL,
                                      sashwidth=5,
                                      sashrelief="raised",
                                      sashpad=2,
                                      relief="sunken")

        self.paneTop = ttk.Frame(self.paneMaster)
        self.rankings = PreferenceRankingMaster(self.paneTop, self.conflict)
        self.editor = RadiobuttonEntry(self.paneTop, self.conflict)
        self.paneTopRightMaster = PanedWindow(self.paneTop,
                                              orient=HORIZONTAL,
                                              sashwidth=5,
                                              sashrelief="raised",
                                              sashpad=2,
                                              relief="sunken")
        self.staging = PreferenceStaging(self.paneTopRightMaster,
                                         self.conflict)
        self.preferenceDisp = PreferenceListDisplay(self.paneTopRightMaster,
                                                    self.conflict)

        self.paneBottom = ttk.Frame(self.paneMaster)
        self.optionTable = OptionFormTable(self.paneBottom, self.conflict)

        self.usePrioritizationButton = ttk.Button(
            self,
            text=("Use preference prioritization. Any manually set "
                  "preference rankings will be lost."),
            command=self.usePrioritization)

        # ########  preliminary gridding and option configuration

        # configuring the input frame
        self.grid(column=0, row=0, rowspan=5, sticky=NSEW)
        self.columnconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)
        self.grid_remove()

        # configuring infoFrame & infoFrame widgets
        self.infoFrame.grid(column=2, row=0, sticky=NSEW, padx=3, pady=3)
        self.infoFrame.grid_remove()
        self.infoLabel.grid(column=0, row=1, sticky=NSEW)

        # configuring helpFrame & helpFrame widgets
        self.helpFrame.grid(column=2, row=1, sticky=NSEW, padx=3, pady=3)
        self.helpFrame.grid_remove()
        self.helpLabel.grid(column=0, row=0, sticky=NSEW)

        # configuring frame-specific options
        self.paneMaster.grid(column=0, row=1, sticky=NSEW)
        self.paneMaster.add(self.paneTop, minsize=200)
        self.rankings.grid(column=0, row=1, sticky=NSEW)
        ttk.Separator(self.paneTop, orient=VERTICAL).grid(column=1,
                                                          row=1,
                                                          sticky=NSEW,
                                                          padx=3)
        self.editor.grid(column=2, row=1, sticky=NSEW)
        ttk.Separator(self.paneTop, orient=VERTICAL).grid(column=3,
                                                          row=1,
                                                          sticky=NSEW,
                                                          padx=3)
        self.paneTopRightMaster.grid(column=4, row=1, sticky=NSEW)
        self.paneTop.columnconfigure(0, weight=0)
        self.paneTop.columnconfigure(2, weight=0)
        self.paneTop.columnconfigure(4, weight=1)
        self.paneTop.rowconfigure(1, weight=1)

        self.usePrioritizationButton.grid(column=0,
                                          row=0,
                                          columnspan=5,
                                          sticky=NSEW)

        self.paneTopRightMaster.add(self.staging)
        self.paneTopRightMaster.add(self.preferenceDisp)

        self.paneMaster.add(self.paneBottom)
        self.optionTable.grid(column=0, row=0, sticky=NSEW)
        self.paneBottom.columnconfigure(0, weight=1)
        self.paneBottom.rowconfigure(0, weight=1)

        # bindings
        self.rankings.bind('<<DMchg>>', self.dmChgHandler)
        self.editor.bind('<<AddPref>>', self.addPref)
        self.editor.bind('<<StagePref>>', self.stagePref)
        self.staging.bind('<<SelCond>>', self.selCondChg)
        self.staging.bind('<<PullFromStage>>', self.pullFromStage)
        self.preferenceDisp.bind('<<SelPref>>', self.selPrefChg)
        self.preferenceDisp.bind('<<ValueChange>>', self.refresh)

        self.dmChgHandler()

        self.built = True

    def enter(self, *args):
        """Re-grid the screen into the master. Perform required updates."""
        if self.dataChanged():
            self.clearFrame()

        FrameTemplate.enter(self)

    def refresh(self, *args):
        """Refresh data in all active display widgets."""
        for dm in self.conflict.decisionMakers:
            dm.calculatePreferences()
        self.editor.reloadOpts()
        self.rankings.refresh()
        self.preferenceDisp.refresh()
        self.optionTable.buildTable(self.dm)

        self.checkIfUsingRankings()

    def checkIfUsingRankings(self, event=None):
        """Disable screen if Manual Ranking has been assigned."""
        if self.conflict.useManualPreferenceRanking:
            self.usePrioritizationButton.grid()
            self.rankings.disable()
            self.editor.disable()
            self.staging.disable()
            self.preferenceDisp.disable()
        else:
            self.usePrioritizationButton.grid_remove()

    def usePrioritization(self):
        """Reactivate the screen if user decides to use prioritization."""
        self.conflict.useManualPreferenceRanking = False
        self.conflict.preferenceErrors = None
        self.refresh()

    def dmChgHandler(self, event=None):
        """Bound to <<DMchg>>."""
        self.dm = self.rankings.dm
        self.preferenceDisp.changeDM(self.dm)
        self.optionTable.buildTable(self.dm)
        self.staging.clear()
        self.editor.setStates('clear')
        if self.dm is None:
            self.preferenceDisp.disable()
            self.editor.disable()
            self.staging.disable()
        else:
            self.preferenceDisp.enable()
            self.editor.enable()

    def addPref(self, event=None):
        """Add a preference for the active decision maker."""
        pref = self.editor.getStates()
        self.dm.preferences.append(pref)
        self.refresh()

    def stagePref(self, event=None):
        """Send a condition to the staging area."""
        if self.editor.hasValidIf:
            for cond in self.editor.ifCond:
                self.staging.addCondition(cond)
        else:
            condData = self.editor.getStates()
            newCond = self.conflict.newCondition(condData)
            self.staging.addCondition(newCond)

        self.editor.setStates('clear')

    def pullFromStage(self, event=None):
        """Move a compound condition from Staging to Preferences."""
        newPref = self.staging.conditionList
        self.staging.clear()
        self.dm.preferences.append(newPref)
        self.refresh()

    def selCondChg(self, event=None):
        """Triggered when a condition is selected in staging."""
        condition = self.staging.conditionList[event.x]
        self.editor.setStates(condition.ynd())

    def selPrefChg(self, event=None):
        """Triggered when a preference is select from preferences."""
        condition = self.dm.preferences[event.x]
        self.staging.setList(condition)
示例#27
0
class NetGame(Game) :
    def __init__(self) :
        Game.__init__(self)
        import socket
        import tkinter
        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) :
            #print "modify port to",port.get()
            try :
                self.port=int(port.get())
            except :
                port.set("")
        port.trace("w", modifPort)
        port_wid=Entry(fenetre, width=30,textvariable=port)
        #port_wid.grid(column=0, row=1)
        host_wid.focus() 
        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(socket.AF_INET, socket.SOCK_STREAM)    # 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",self.firstplayer)
            self.soc.send(str(3-self.firstplayer).encode('utf-8'))
        else :
            self.soc.connect((self.host, self.port))
            print( "connect ok")
            p=self.soc.recv(1024).decode('utf-8')
            try :
                self.firstplayer=int(p)
            except :
                print( "error concerning first player, got ",p)
        self.remains=""
            #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)
    def send(self,str):
        print("send :"+str)
        self.soc.send(str.encode('utf-8'))
    def random(self,n,intrange) :
        if self.local==self.host :
            jet=sample(list(range(intrange)),n)
            print( "send",jet)
            self.soc.send((" ".join(map(str,jet))+"\n" ).encode('utf-8'))
        else :
            print( "waiting ",n," random number in range",intrange)
            if self.remains  :
                p=self.remains
                self.remains=""
            else :
                p=self.soc.recv(1024).decode('utf-8')
                print( "recv ",p)
            p=p.strip()
            if "\n" in p :
                self.remains,p = p.split("\n",1)
            jet=list(map(int,p.strip().split()))
            print( "got",jet)
        return jet
示例#28
0
    def BuildMainFrame(self): 
        from tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry
        from tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED

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

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

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

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

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

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

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

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

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

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

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

        self.text_input.focus_set()

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

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

        self.output_stream = TkPadOutputStream(self.text_output)
        self.input_stream = TkPadInputStream(self.text_entry,self.output_stream)
示例#29
0
topFrame = Frame(win)
topFrame.pack(side='top')
topFrame.config(width=800, height=100, background="#eee")

panedwindow=PanedWindow(relief="raised", bd=0)
panedwindow.pack(expand=True)

leftFrame = Frame(win)
leftFrame.pack(side='left')
leftFrame.config(width=200, height=400, background="#eee")

rightFrame = Frame(win)
rightFrame.pack(side='right')
rightFrame.config(width=600, height=470, background="green")

panedwindow.add(leftFrame)
panedwindow.add(rightFrame)

bottomFrame = Frame(win)
bottomFrame.pack(side='bottom')
bottomFrame.config(width=800, height=30, background="blue")


# leftFrame에 Entry 위젯 추가
label_frame = Labelframe(leftFrame, text='기본 정보 입력')
label_frame.pack()

lbl_name = Label(label_frame, text="성명:")
lbl_phone = Label(label_frame, text="전화번호:")
lbl_email = Label(label_frame, text="이메일:")
示例#30
0
class StabilityFrame(FrameTemplate):
    """Frame used to for Stability Analysis."""

    # Label used for button to select frame in the main program.
    buttonLabel = 'Post Analysis'
    # Image used on button to select frame, when frame is active.
    activeIcon = 'icons/Post_Analysis_ON.gif'
    # Image used on button to select frame, when frame is inactive.
    inactiveIcon = 'icons/Post_Analysis_OFF.gif'
    # Help text to be displayed when screen is active.
    helpText = ("Selecting coalitions, status quo and goals at the top left"
                "will generate a reachability tree below the status quo, and "
                "detail the patterns that preferences must match for the goal "
                "state to be reached.")

# ########################     INITIALIZATION  ################################
    def __init__(self, master, conflict, *args):
        """Initialize the Frame. Does not build widgets."""
        FrameTemplate.__init__(self, master, conflict, self.buttonLabel,
                               self.activeIcon, self.inactiveIcon,
                               self.helpText)

        self.lastBuildConflict = None


# ############################     METHODS  ###################################

    def hasRequiredData(self):
        """Check that minimum data required to render the frame exists."""
        if len(self.conflict.decisionMakers) < 1:
            return False
        if len(self.conflict.options) < 1:
            return False
        if len(self.conflict.feasibles) < 1:
            return False
        if self.conflict.preferenceErrors:
            return False
        else:
            return True

    def dataChanged(self):
        """Check if data has changed since the last build of the Frame."""
        if self.lastBuildConflict != self.conflict.export_rep():
            return True
        else:
            return False

    def buildFrame(self):
        """Contruct frame widgets and initialize data."""
        if self.built:
            return

        # Ensure all required parts of the conflict model are properly set-up.
        self.conflict.reorderOptionsByDM()
        self.conflict.options.set_indexes()
        self.conflict.infeasibles.validate()
        self.conflict.recalculateFeasibleStates()

        for dm in self.conflict.decisionMakers:
            dm.calculatePerceived()
            dm.calculatePreferences()

        self.lastBuildConflict = self.conflict.export_rep()

        # Define frame-specific variables
        self.sol = GoalSeeker(self.conflict)

        # infoFrame: frame and label definitions (with master 'self.infoFrame')
        self.infoLabel = ttk.Label(self.infoFrame, text="")

        # helpFrame: frame and label definitions (with master 'self.helpFrame')
        self.helpLabel = ttk.Label(self.helpFrame, textvariable=self.helpVar,
                                   wraplength=150)

        # Define frame-specific input widgets (with 'self' as master)
        self.paneMaster = PanedWindow(self, orient=HORIZONTAL, sashwidth=10,
                                      sashrelief="raised", sashpad=3,
                                      relief="sunken")

        self.paneLeft = PanedWindow(self.paneMaster, orient=VERTICAL,
                                    sashwidth=10, sashrelief="raised",
                                    sashpad=3, relief="sunken")

        self.paneLeftTop = ttk.Frame(self.paneLeft)
        self.coalitionSelector = CoalitionSelector(self.paneLeftTop,
                                                   self.conflict, self)
        self.statusQuoAndGoals = StatusQuoAndGoals(self.paneLeftTop,
                                                   self.conflict)
        self.reachableTree = ReachableTreeViewer(self.paneLeftTop,
                                                 self.conflict, self)

        self.paneLeftBottom = ttk.Frame(self.paneLeft)
        self.optionFormTable = OptionFormTable(self.paneLeftBottom,
                                               self.conflict)

        self.paneRight = ttk.Frame(self.paneMaster)
        self.patternNarrator = PatternNarrator(self.paneRight, self.conflict,
                                               self)

        # ########  preliminary gridding and option configuration

        # configuring the input frame
        self.grid(column=0, row=0, rowspan=5, sticky=NSEW)
        self.grid_remove()
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        # configuring infoFrame & infoFrame widgets
        self.infoFrame.grid(column=2, row=0, sticky=NSEW, padx=3, pady=3)
        self.infoFrame.grid_remove()
        self.infoLabel.grid(column=0, row=1, sticky=NSEW)

        # configuring helpFrame & helpFrame widgets
        self.helpFrame.grid(column=2, row=1, sticky=NSEW, padx=3, pady=3)
        self.helpFrame.grid_remove()
        self.helpLabel.grid(column=0, row=0, sticky=NSEW)

        # configuring frame-specific options
        self.paneMaster.grid(row=0, column=0, sticky=NSEW)

        self.paneMaster.add(self.paneLeft)

        self.paneLeft.add(self.paneLeftTop)
        self.paneLeftTop.columnconfigure(1, weight=1)
        self.paneLeftTop.rowconfigure(2, weight=1)
        self.coalitionSelector.grid(row=0, column=0, sticky=NSEW)
        ttk.Separator(self, orient=HORIZONTAL).grid(row=1, column=0,
                                                    sticky=NSEW, pady=3)
        self.statusQuoAndGoals.grid(row=2, column=0, sticky=NSEW)
        self.reachableTree.grid(row=0, column=1, rowspan=3, sticky=NSEW)

        self.paneLeft.add(self.paneLeftBottom)
        self.paneLeftBottom.rowconfigure(0, weight=1)
        self.paneLeftBottom.columnconfigure(0, weight=1)
        self.optionFormTable.grid(row=0, column=0, sticky=NSEW)

        self.paneMaster.add(self.paneRight)
        self.paneRight.rowconfigure(0, weight=1)
        self.paneRight.columnconfigure(0, weight=1)
        self.patternNarrator.grid(row=0, column=0, sticky=NSEW)

        # bindings
        self.statusQuoAndGoals.bind("<<StatusQuoChanged>>",
                                    self.refresh)
        self.statusQuoAndGoals.bind("<<GoalChanged>>",
                                    self.refresh)
        self.coalitionSelector.bind("<<CoalitionsChanged>>",
                                    self.refresh)

        self.built = True

    def refresh(self, *args):
        """Refresh data in all active display widgets."""
        sq = self.statusQuoAndGoals.statusQuoSelector.current()
        goals = self.statusQuoAndGoals.getGoals()
        if len(goals) > 0:
            self.sol = GoalSeeker(self.conflict, goals)
        else:
            self.sol = GoalSeeker(self.conflict)
        self.reachableTree.buildTree(sq, watchFor=[x[0] for x in goals])
        self.patternNarrator.updateNarration(
            goalInfo=self.reachableTree.goalInfo())
示例#31
0
class PhotoboothUi(Frame):
    def create_widgets(self):
        # COLLAGE SCREEN
        self.collage_screen = Frame(self, bg=self['bg'])

        self.collage_label = Label(self.collage_screen,
                                   image=None,
                                   bg=self['bg'])
        self.collage_label.pack(side="top", expand=True, fill="both")

        self.btns_panel = Frame(self.collage_screen, bg=self['bg'])
        self.btns_panel.pack(
            side="bottom",
            expand=True,
            fill='x',
            anchor="s",
        )

        self.print_btn = Button(self.btns_panel,
                                text=self.translation['fr']['print'],
                                height=3,
                                fg="blue")
        self.print_btn.config(command=self.actions['print'])
        self.print_btn.pack(side="left", fill="x", expand=True, padx=(0, 10))

        self.cancel_btn = Button(self.btns_panel,
                                 text=self.translation['fr']['not_print'],
                                 height=3,
                                 fg="red",
                                 font=('Sans', '10', 'bold'))
        self.cancel_btn.config(command=self.actions['not_print'])
        self.cancel_btn.pack(side="left", fill="x", expand=True, padx=(10, 0))

        # LOADING SCREEN
        self.loading_screen = Frame(self, bg="black")
        self.loading_label = Label(self.loading_screen,
                                   text=self.translation['fr']['loading'],
                                   fg="white",
                                   bg="black",
                                   font=('Sans', '30', 'bold'))
        self.loading_label.place(relx=0.5, rely=0.5, anchor="center")
        self.loading_screen.lift()

        # HOME SCREEN
        self.home_screen = PanedWindow(self, orient="vertical", bg=self['bg'])

        self.pictures_btn = Button(self.home_screen,
                                   height=31,
                                   text=self.translation['fr']['take_pict'],
                                   command=self.actions['take_pictures'])
        self.home_screen.add(self.pictures_btn, pady=10, padx=10)

        qrc_frame = Frame(self, bg=self['bg'])
        self.home_screen.add(qrc_frame, sticky="s", pady=10)

        qrc_title_label = Label(qrc_frame,
                                text=self.translation['fr']['access_gallery'],
                                fg="black",
                                bg=self['bg'],
                                font=('Sans', '15', 'bold'))
        qrc_title_label.pack()

        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=3,
            border=2,
        )
        qr.add_data('http://raspberrypi.local/')
        qr.make(fit=True)

        img_tmp = qr.make_image(fill_color="black", back_color="white")
        img = ImageTk.PhotoImage(img_tmp)

        qrc_label = Label(qrc_frame, image=img, bg=self['bg'])
        qrc_label.image = img
        qrc_label.pack()

        qrc_txt_label = Label(qrc_frame,
                              text=self.translation['fr']['link_to_gallery'],
                              fg="black",
                              bg=self['bg'],
                              font=('Sans', '10'))
        qrc_txt_label.pack()

        self.gallery_bg = Gallery(self.home_screen)
        self.gallery_bg.place(relx=0.5,
                              rely=0.5,
                              anchor="center",
                              relheight=1.0,
                              relwidth=1.0)
        self.gallery_bg.lower()

        #PRINTING SCREEN
        self.print_screen = Frame(self, bg="#F0F8FF")
        self.printing_label = Label(self.print_screen,
                                    text=self.translation['fr']['printing'],
                                    fg="black",
                                    bg="blue",
                                    font=('Sans', '30', 'bold'))
        self.printing_label.place(relx=0.5, rely=0.5, anchor="center")
        self.print_screen.lift()

    def __init__(self, actions, master=None):
        bgc = 'white'
        Frame.__init__(self, master, image=None, bg=bgc, cursor="none")
        self['bg'] = bgc

        self.actions = actions
        self.translation = {
            'fr': {
                'take_pict': "Prendre des photos !",
                'print': 'Imprimer',
                'cancel': "Annuler",
                'not_print': "Ne pas imprimer",
                'last_collage': "Dernier collage",
                'ready': 'Prêt ?',
                'take_another_one': "Prendre une autre photo",
                'loading': "Chargement",
                'printing': "Impression lancée",
                'access_gallery': "Accéder à la galerie",
                'link_to_gallery': "ou \nraspberrypi.local",
            }
        }

        self.pack(expand=True, fill="both")
        self.create_widgets()
class Program:
    def __init__(self):
        self.root = Tk()
        self.frame = Frame()
        self.frame.pack(side="top")
        self.title = Label(self.frame, text=TITLE)
        self.canvas = Canvas(self.root,
                             width=WIDTH,
                             height=HEIGHT,
                             borderwidth=0,
                             highlightthickness=0,
                             bg="black")
        self.painel = PanedWindow(orient="horizontal")
        self.list_money = []
        self.ents = []
        self.num_itens = 0
        self.wallet = 0
        self.loss = 0
        self.typ = ""

    def create_form(self):
        entries = []
        fields = ["Wallet", "Loss", "Coin"]
        for field in fields:
            row = Frame(self.painel)
            lab = Label(self.painel, width=15, text=field, anchor='w')
            ent = Entry(self.painel)
            entries.append((row, lab, ent))
        return entries

    def create_money(self):
        values_list = [
            100.0, 50.0, 20.0, 10.0, 5.0, 2.0, 1.0, 0.5, 0.25, 0.1, 0.05, 0.01
        ]

        change = self.wallet - self.loss
        count = 0
        while change > 0.0:
            if change - values_list[count] >= 0.0:
                change -= values_list[count]
                change = round(change, 2)
                print(change)
                money = Money(values_list[count], self.typ)
                self.list_money.append(money)
            else:
                count += 1

    def render_notes(self):
        print(self.list_money)
        place = [0, 0]
        for each in self.list_money:
            img = each.render_money()
            imge = Label(self.canvas, image=img)
            imge.image = img
            imge.place(x=place[0], y=place[1])
            if place[0] >= 1000:
                place[1] += 150
                place[0] = 0
                continue
            place[0] += 150

    def fetch(self):
        count = 0
        self.list_money = []
        self.canvas.delete("all")
        self.canvas.update()
        for entry in self.ents:
            count += 1
            text = entry.get()
            if count == 1:
                self.wallet = float(text)
            if count == 2:
                self.loss = float(text)
            if count == 3:
                self.typ = str(text)

        print("WALLET: {}\nLOSS: {}\nTyp: {}".format(self.wallet, self.loss,
                                                     self.typ))
        self.create_money()
        self.render_notes()
        self.canvas.update()

    def create_painel(self):
        ents = self.create_form()
        for row, lab, ent in ents:
            self.painel.add(row)
            self.painel.add(lab)
            self.painel.add(ent)
            self.ents.append(ent)

        self.painel.add(Button(self.painel, text="submit", command=self.fetch))

    def main(self):
        self.canvas.pack()
        self.painel.pack()
        self.title.pack(side="top")
        self.create_painel()
        self.root.mainloop()
示例#33
0
from tkinter import Tk, Label, PanedWindow, BOTH, VERTICAL

master = Tk()
m1 = PanedWindow(master)
m1.pack(fill=BOTH, expand=1)

left = Label(m1, text="left pane")
m1.add(left)

m2 = PanedWindow(m1, orient=VERTICAL)
m1.add(m2)

top = Label(m2, text="top pane")
m2.add(top)

bottom = Label(m2, text="bottom pane")
m2.add(bottom)

master.mainloop()
示例#34
0
from tkinter import Tk, PanedWindow
from tkinter.ttk import Label, Entry, Button

win = Tk()

lbl = Label(win, text="성명: ")
entry = Entry(win)

lbl.pack()
entry.pack()

penedwindow = PanedWindow(relief="raised", bd=0)
penedwindow.pack()

btn_ok = Button(penedwindow, text="확인")
btn_cancel = Button(penedwindow, text="취소")
penedwindow.add(btn_ok)
penedwindow.add(btn_cancel)

if __name__ == '__main__':
    win.mainloop()
示例#35
0
 def createfilelistpanel(self, parent):
     panel = PanedWindow(parent, orient=VERTICAL)
     for file in self.files:
         panel.add(self.createfilepanel(panel, file))
     return panel
class PreferencesFrame(FrameTemplate):
    """Used to set decision maker's preferences for use in prioritization."""

    # Label used for button to select frame in the main program.
    buttonLabel = 'Prioritization'
    # Image used on button to select frame, when frame is active.
    activeIcon = 'icons/Prioritization_ON.gif'
    # Image used on button to select frame, when frame is inactive.
    inactiveIcon = 'icons/Prioritization_OFF.gif'
    # Help text to be displayed when screen is active.
    helpText = ("Select a decision maker from the column at left by clicking "
                "its 'Edit' button.  Enter preferred conditions using the "
                "inputs to the right.  Preferred conditions for the selected "
                "decision maker are shown at the far right, from most "
                "important at the top, to least important at the bottom.")

# ########################     INITIALIZATION  ################################
    def __init__(self, master, conflict, *args):
        """Initialize the Frame. Does not build widgets."""
        FrameTemplate.__init__(self, master, conflict, self.buttonLabel,
                               self.activeIcon, self.inactiveIcon,
                               self.helpText)

        self.lastBuildDMs = None
        self.lastBuildOptions = None
        self.lastBuildInfeasibles = None
        self.lastBuildRanking = None


# ############################     METHODS  ###################################

    def hasRequiredData(self):
        """Check that minimum data required to render the frame exists."""
        if len(self.conflict.decisionMakers) < 1:
            return False
        if len(self.conflict.options) < 1:
            return False
        if len(self.conflict.feasibles) < 1:
            self.conflict.recalculateFeasibleStates()
            if len(self.conflict.feasibles) < 1:
                return False
        else:
            return True

    def dataChanged(self):
        """Check if data has changed since the last build of the Frame."""
        if self.lastBuildDMs != self.conflict.decisionMakers.export_rep():
            return True
        if self.lastBuildOptions != self.conflict.options.export_rep():
            return True
        if self.lastBuildInfeasibles != self.conflict.infeasibles.export_rep():
            return True
        if self.lastBuildRanking != self.conflict.useManualPreferenceRanking:
            return True
        else:
            return False

    def buildFrame(self):
        """Contruct frame widgets and initialize data."""
        if self.built:
            return

        # Ensure all required parts of the conflict model are properly set-up.
        self.conflict.reorderOptionsByDM()
        self.conflict.options.set_indexes()
        self.conflict.infeasibles.validate()
        self.conflict.recalculateFeasibleStates()

        for dm in self.conflict.decisionMakers:
            dm.calculatePerceived()
            dm.calculatePreferences()

        self.lastBuildDMs = self.conflict.decisionMakers.export_rep()
        self.lastBuildOptions = self.conflict.options.export_rep()
        self.lastBuildInfeasibles = self.conflict.infeasibles.export_rep()
        self.lastBuildRanking = self.conflict.useManualPreferenceRanking

        # Define variables that will display in the infoFrame
        numD = len(self.conflict.decisionMakers)
        self.infoText = StringVar(
            value='Valid Preferences set for {0}/{0} DMs.'.format(numD))

        # Define frame-specific variables
        self.dm = None

        # infoFrame: frame and label definitions (with master 'self.infoFrame')
        self.infoLabel = ttk.Label(self.infoFrame, textvariable=self.infoText)

        # helpFrame: frame and label definitions (with master 'self.helpFrame')
        self.helpLabel = ttk.Label(self.helpFrame, textvariable=self.helpVar,
                                   wraplength=150)

        # Define frame-specific input widgets (with 'self' as master)
        self.paneMaster = PanedWindow(self, orient=VERTICAL, sashwidth=5,
                                      sashrelief="raised", sashpad=2,
                                      relief="sunken")

        self.paneTop = ttk.Frame(self.paneMaster)
        self.rankings = PreferenceRankingMaster(self.paneTop, self.conflict)
        self.editor = RadiobuttonEntry(self.paneTop, self.conflict)
        self.paneTopRightMaster = PanedWindow(self.paneTop, orient=HORIZONTAL,
                                              sashwidth=5, sashrelief="raised",
                                              sashpad=2, relief="sunken")
        self.staging = PreferenceStaging(self.paneTopRightMaster,
                                         self.conflict)
        self.preferenceDisp = PreferenceListDisplay(self.paneTopRightMaster,
                                                    self.conflict)

        self.paneBottom = ttk.Frame(self.paneMaster)
        self.optionTable = OptionFormTable(self.paneBottom, self.conflict)

        self.usePrioritizationButton = ttk.Button(
            self,
            text=("Use preference prioritization. Any manually set "
                  "preference rankings will be lost."),
            command=self.usePrioritization)

        # ########  preliminary gridding and option configuration

        # configuring the input frame
        self.grid(column=0, row=0, rowspan=5, sticky=NSEW)
        self.columnconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)
        self.grid_remove()

        # configuring infoFrame & infoFrame widgets
        self.infoFrame.grid(column=2, row=0, sticky=NSEW, padx=3, pady=3)
        self.infoFrame.grid_remove()
        self.infoLabel.grid(column=0, row=1, sticky=NSEW)

        # configuring helpFrame & helpFrame widgets
        self.helpFrame.grid(column=2, row=1, sticky=NSEW, padx=3, pady=3)
        self.helpFrame.grid_remove()
        self.helpLabel.grid(column=0, row=0, sticky=NSEW)

        # configuring frame-specific options
        self.paneMaster.grid(column=0, row=1, sticky=NSEW)
        self.paneMaster.add(self.paneTop, minsize=200)
        self.rankings.grid(column=0, row=1, sticky=NSEW)
        ttk.Separator(self.paneTop, orient=VERTICAL).grid(
            column=1, row=1, sticky=NSEW, padx=3)
        self.editor.grid(column=2, row=1, sticky=NSEW)
        ttk.Separator(self.paneTop, orient=VERTICAL).grid(
            column=3, row=1, sticky=NSEW, padx=3)
        self.paneTopRightMaster.grid(column=4, row=1, sticky=NSEW)
        self.paneTop.columnconfigure(0, weight=0)
        self.paneTop.columnconfigure(2, weight=0)
        self.paneTop.columnconfigure(4, weight=1)
        self.paneTop.rowconfigure(1, weight=1)

        self.usePrioritizationButton.grid(column=0, row=0, columnspan=5,
                                          sticky=NSEW)

        self.paneTopRightMaster.add(self.staging)
        self.paneTopRightMaster.add(self.preferenceDisp)

        self.paneMaster.add(self.paneBottom)
        self.optionTable.grid(column=0, row=0, sticky=NSEW)
        self.paneBottom.columnconfigure(0, weight=1)
        self.paneBottom.rowconfigure(0, weight=1)

        # bindings
        self.rankings.bind('<<DMchg>>', self.dmChgHandler)
        self.editor.bind('<<AddPref>>', self.addPref)
        self.editor.bind('<<StagePref>>', self.stagePref)
        self.staging.bind('<<SelCond>>', self.selCondChg)
        self.staging.bind('<<PullFromStage>>', self.pullFromStage)
        self.preferenceDisp.bind('<<SelPref>>', self.selPrefChg)
        self.preferenceDisp.bind('<<ValueChange>>', self.refresh)

        self.dmChgHandler()

        self.built = True

    def enter(self, *args):
        """Re-grid the screen into the master. Perform required updates."""
        if self.dataChanged():
            self.clearFrame()

        FrameTemplate.enter(self)

    def refresh(self, *args):
        """Refresh data in all active display widgets."""
        for dm in self.conflict.decisionMakers:
            dm.calculatePreferences()
        self.editor.reloadOpts()
        self.rankings.refresh()
        self.preferenceDisp.refresh()
        self.optionTable.buildTable(self.dm)

        self.checkIfUsingRankings()

    def checkIfUsingRankings(self, event=None):
        """Disable screen if Manual Ranking has been assigned."""
        if self.conflict.useManualPreferenceRanking:
            self.usePrioritizationButton.grid()
            self.rankings.disable()
            self.editor.disable()
            self.staging.disable()
            self.preferenceDisp.disable()
        else:
            self.usePrioritizationButton.grid_remove()

    def usePrioritization(self):
        """Reactivate the screen if user decides to use prioritization."""
        self.conflict.useManualPreferenceRanking = False
        self.conflict.preferenceErrors = None
        self.refresh()

    def dmChgHandler(self, event=None):
        """Bound to <<DMchg>>."""
        self.dm = self.rankings.dm
        self.preferenceDisp.changeDM(self.dm)
        self.optionTable.buildTable(self.dm)
        self.staging.clear()
        self.editor.setStates('clear')
        if self.dm is None:
            self.preferenceDisp.disable()
            self.editor.disable()
            self.staging.disable()
        else:
            self.preferenceDisp.enable()
            self.editor.enable()

    def addPref(self, event=None):
        """Add a preference for the active decision maker."""
        pref = self.editor.getStates()
        self.dm.preferences.append(pref)
        self.refresh()

    def stagePref(self, event=None):
        """Send a condition to the staging area."""
        if self.editor.hasValidIf:
            for cond in self.editor.ifCond:
                self.staging.addCondition(cond)
        else:
            condData = self.editor.getStates()
            newCond = self.conflict.newCondition(condData)
            self.staging.addCondition(newCond)

        self.editor.setStates('clear')

    def pullFromStage(self, event=None):
        """Move a compound condition from Staging to Preferences."""
        newPref = self.staging.conditionList
        self.staging.clear()
        self.dm.preferences.append(newPref)
        self.refresh()

    def selCondChg(self, event=None):
        """Triggered when a condition is selected in staging."""
        condition = self.staging.conditionList[event.x]
        self.editor.setStates(condition.ynd())

    def selPrefChg(self, event=None):
        """Triggered when a preference is select from preferences."""
        condition = self.dm.preferences[event.x]
        self.staging.setList(condition)
示例#37
0
class Facade(Frame):
    """This is a Frame that contains group info, group order, apex and prime
    graph.
    """
    def __init__(self, parent, group, show_graph=True, 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()  # TODO: fix vertex label automatic positioning
        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(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("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 = filedialog.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
示例#38
0
    def __init__(self) :
        Game.__init__(self)
        import socket
        import tkinter
        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) :
            #print "modify port to",port.get()
            try :
                self.port=int(port.get())
            except :
                port.set("")
        port.trace("w", modifPort)
        port_wid=Entry(fenetre, width=30,textvariable=port)
        #port_wid.grid(column=0, row=1)
        host_wid.focus() 
        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(socket.AF_INET, socket.SOCK_STREAM)    # 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",self.firstplayer)
            self.soc.send(str(3-self.firstplayer).encode('utf-8'))
        else :
            self.soc.connect((self.host, self.port))
            print( "connect ok")
            p=self.soc.recv(1024).decode('utf-8')
            try :
                self.firstplayer=int(p)
            except :
                print( "error concerning first player, got ",p)
        self.remains=""
示例#39
0
class Grapfics():
    def __init__(self):
        self.aut = ''
        self.root = Tk()
        self.root.state('zoomed')
        self.root.geometry(
            str(self.root.winfo_screenwidth() - 200) + 'x' +
            str(self.root.winfo_screenheight() - 200))

        self.pb = ttk.Progressbar(self.root,
                                  orient=HORIZONTAL,
                                  length=200,
                                  mode='determinate')

        self.menu = Menu(self.root)
        self.menu.add_command(label="О программе", command=self.prog_menu)

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

        self.l_1 = Label(self.root, text="Авторизация в vk")
        self.l_2 = Label(self.root, text="Формат списка")
        self.l_3 = Label(self.root, text="Отчет")
        self.l_4 = Label(self.root, text="Вы не авторизованы")
        self.l_5 = Label(self.root, text="")

        self.en_1 = Entry(self.root)
        self.en_2 = Entry(self.root)

        self.pos_1 = IntVar()
        self.pos_1.set(0)
        self.rb_1 = Radiobutton(
            self.root,
            text="1. http://vk.com/groupID http://vk.com/userID",
            variable=self.pos_1,
            value=0)
        self.rb_2 = Radiobutton(
            self.root,
            text="1. http://vk.com/userID http://vk.com/groupID",
            variable=self.pos_1,
            value=1)

        pos_2 = IntVar()
        pos_2.set(0)
        self.rb_3 = Radiobutton(self.root,
                                text="По участникам",
                                variable=pos_2,
                                value=0)
        self.rb_4 = Radiobutton(self.root,
                                text="По группам",
                                variable=pos_2,
                                value=1)

        self.frame_1 = Frame(self.root)
        self.tex = Text(self.frame_1,
                        width=60,
                        height=35,
                        font="Verdana 6",
                        wrap=WORD)
        self.scr = Scrollbar(self.frame_1, command=self.tex.yview)
        self.tex.configure(yscrollcommand=self.scr.set)

        self.splitter = PanedWindow(self.root,
                                    orient=HORIZONTAL,
                                    height=500,
                                    width=800)
        self.frame_2 = Frame(self.splitter, width='20')
        self.table = Table(self.frame_2)
        self.table.pack(expand=YES, fill=BOTH)

        self.splitter.add(self.frame_2)

        self.scr.pack(side='right', fill='y')
        self.frame_1.place(x='20', y='205')
        self.tex.pack(fill='both')

        if os.path.exists('vk_config.v2.json'):
            with open('vk_config.v2.json', 'r') as t:
                q = json.load(t)
            for i in q.keys():
                log = i
                tok = str(q).split("'access_token': '")[1].split("'")[0]
            self.vk = vk_api.VkApi(login=log, token=tok)
            self.vk.auth(token_only=True)
            self.l_4['text'] = self.vk.method(
                'users.get')[0]['first_name'] + '\n' + self.vk.method(
                    'users.get')[0]['last_name']

        self.b_1 = Button(self.root, text="Войти", command=self.au)
        self.b_2 = Button(self.root,
                          text="Проверить вступления",
                          width=20,
                          command=self.k)
        self.b_3 = Button(self.root,
                          text="Отчет",
                          width=20,
                          command=lambda: Otch().start())
        self.b_4 = Button(self.root, text="Выход", command=self.ex)

        self.splitter.place(x='450', y='205')
        self.en_1.place(x='20', y='55')
        self.en_2.place(x='20', y='80')

        self.b_1.place(x='170', y='50')
        self.b_2.place(x='350', y='140')
        self.b_3.place(x='350', y='170')
        self.b_4.place(x='170', y='80')

        self.l_1.place(x='20', y='30')
        self.l_2.place(x='20', y='120')
        #self.l_3.place(x = '550', y = '120')
        self.l_4.place(x='220', y='55')

        self.rb_1.place(x='20', y='140')
        self.rb_2.place(x='20', y='160')

        #self.rb_3.place(x = '550', y = '140')
        #self.rb_4.place(x = '550', y = '160')

        self.pb.place(x='20', y='650')
        self.l_5.place(x='225', y='650')

        self.root.mainloop()

    def k(self):
        self.l_5['text'] = ""
        self.table.destroy()
        self.table = Table(self.frame_2)
        self.table.pack(expand=YES, fill=BOTH)
        if os.path.exists('vk_config.v2.json'):
            if requests.get(
                    'http://3.12.164.15/table/%s' %
                    str(self.vk.method('users.get')[0]['id'])).text == 'True':
                x = threading.Thread(target=st,
                                     args=(self.pos_1.get(),
                                           self.tex.get('1.0', 'end'), self.vk,
                                           self.table, self.l_5, self.pb))
                x.start()
            else:
                messagebox.showinfo(
                    "Ошибка!",
                    "К вашему аккаунту не привязан ключ для работы программы\nОбратитесь по ссылке: https://vk.com/id124569304"
                )
        else:
            if requests.get(
                    'http://3.12.164.15/table/%s' %
                    str(self.aut.vk_session.method('users.get')[0]['id'])
            ).text == 'True':
                x = threading.Thread(target=st,
                                     args=(self.pos_1.get(),
                                           self.tex.get('1.0', 'end'),
                                           self.aut.vk_session, self.table,
                                           self.l_5, self.pb))
                x.start()
            else:
                messagebox.showinfo(
                    "Ошибка!",
                    "К вашему аккаунту не привязан ключ для работы программы\nОбратитесь по ссылке: https://vk.com/id124569304"
                )

    def ex(self):
        if os.path.exists('vk_config.v2.json'):
            os.remove(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'vk_config.v2.json'))
        self.l_4['text'] = "Вы не аторизованы"

    def au(self):
        if not os.path.exists('vk_config.v2.json'):
            self.aut = Authentication()
            self.aut.main(self.en_1.get(), self.en_2.get(), self.l_4)
        else:
            messagebox.showinfo(
                "Ошибка!",
                "Для повторной авторизации нужно выйти из нынешнего аккаунта")

    def prog_menu(self):
        self.pr = Tk()
        self.pr.geometry('500x150')

        self.l1_1 = Label(
            self.pr,
            text=
            "Программа сделана для осуществление проверки подписки пользователей\n\n    Разработчик программы:\nvk - https://vk.com/id310539944\nПочта - [email protected]"
        )

        self.l1_1.place(x='20', y='20')

        self.pr.mainloop()
示例#40
0
	def __init__(self, controller, width, height, *args, **kwargs):
		BaseWindow.__init__(self, controller, *args, **kwargs)
		self.controller = controller
		self.controller.configure_toplevel(self)
		self.resizable(True, True)
		self.attributes('-topmost', False) #Remove the toplevel priority
		self.set_exit_function(self.exit)
		self.set_title("Canvas")
		self.file = None
		self.width = int(width)
		self.height = int(height)
		self.geometry(f"{WIDTH}x{HEIGHT}")
		self.bind("<Escape>", self.exit)
		self.top_bar.pack(side = "top", fill = "x", pady = (2,0))
		self.magnifying_glass_image = load_tk_image_from_bytes_array(magnifying_glass_bytes)
		self.floppy_image = load_tk_image_from_bytes_array(floppy_bytes)
		self.bytes_image=  load_tk_image_from_bytes_array(export_to_bytes_bytes)
		self.horizontal_flip_image =  load_tk_image_from_bytes_array(flip_horizontal_bytes)
		self.vertical_flip_image = load_tk_image_from_bytes_array(flip_vertical_bytes)
		self.rotate_left_image = load_tk_image_from_bytes_array(rotate_left_bytes)
		self.rotate_right_image = load_tk_image_from_bytes_array(rotate_right_bytes)
		self.to_grayscale_image = load_tk_image_from_bytes_array(to_grayscale_bytes)
		self.selection_options_image = load_tk_image_from_bytes_array(selection_options_bytes)
		self.layers_symbol_image = load_tk_image_from_bytes_array(layers_symbol_bytes)
		self.folder_options_symbol = load_tk_image_from_bytes_array(folder_options_symbol_bytes)
		self.effects_wand_symbol = load_tk_image_from_bytes_array(effects_wand_symbol_bytes)
		self.copy_options_symbol = load_tk_image_from_bytes_array(copy_options_symbol_bytes)
		self.undo_symbol = load_tk_image_from_bytes_array(undo_symbol_bytes)
		self.redo_symbol = load_tk_image_from_bytes_array(redo_symbol_bytes)

		self.drawtips_references = []
		self.project = PixelProject(self.width, self.height)

		panes = PanedWindow(self, orient = "horizontal", sashpad=3, sashrelief ="sunken")
		panes.pack(fill = "both", expand = True)
		panes.config(borderwidth = 0)

		self.left_side_frame = Frame(panes)
		self.left_side_frame.pack(fill = "both", expand = False, side = "left")
		panes.add(self.left_side_frame)

		tool_buttons = []
		self.gif_tool_bar = ToolBar(tool_buttons, self.left_side_frame)
		self.gif_tool_bar.pack(side = "top", fill = "x", pady = (0,2))

		save_options_button = Label(self.gif_tool_bar, image = self.floppy_image, font = "bold")
		save_options_button.pack(side = "left")
		save_menu = Menu(self, tearoff=0)
		save_menu.add_command(label="Export Gif", command=self.export_gif)
		save_menu.add_command(label="Export Selected Frame", command=self.export_selected_layer)
		save_menu.add_command(label="Export Selected Layer", command=self.export_selected_frame)
		# gif_menu.add_command(label="Export Project as Zip", command=self.export_zip)
		# gif_menu.add_command(label="Export Project as .lpixel", command=self.flip_selection_horizontal)
		# gif_menu.add_command(label="Load Folder as Layers in Current Frame", command=self.load_folder_as_layers)
		bind_popup("<Button-1>", save_options_button, save_menu)

		load_options_button = Label(self.gif_tool_bar, image = self.folder_options_symbol, font = "bold")
		load_options_button.pack(side = "left")
		load_options_menu = Menu(self, tearoff=0)
		load_options_menu.add_command(label="Import Gif as Frames", command=self.import_gif)
		load_options_menu.add_command(label="Load Folder as Frames", command=self.load_folder_as_frames)
		load_options_menu.add_command(label="Load Folder as Layers in Selected Frame", command=self.load_folder_as_layers)
		bind_popup("<Button-1>", load_options_button, load_options_menu)

		preview_options_button = Label(self.gif_tool_bar, image = self.magnifying_glass_image, font = "bold")
		preview_options_button.pack(side = "left")
		preview_options_menu = Menu(self, tearoff=0)
		preview_options_menu.add_command(label="Inspect Selected Frame", command=self.inspect_frame)
		preview_options_menu.add_command(label="Inspect Selected Layer", command=self.inspect_layer)
		bind_popup("<Button-1>", preview_options_button, preview_options_menu)

		panes2 = PanedWindow(self.left_side_frame, orient = "vertical", sashpad=3, sashrelief ="sunken")
		panes2.pack(fill = "both", expand = True, padx = 4, pady = (0,4))
		panes2.config(borderwidth = 0)

		self.gif_view = LayerViewer(self.project, self.width, self.height, panes2)
		self.gif_view.pack(fill = "both", expand = True)
		panes2.add(self.gif_view)
		
		self.frame_manager = LayerManager(self, self.project, panes2)
		self.frame_manager.pack(side = "left", fill = "both", expand = True, pady = 0)
		panes2.add(self.frame_manager)

		self.right_side_frame = Frame(panes)
		self.right_side_frame.pack(fill = "both", expand = True, side = "right")
		panes.add(self.right_side_frame)

		tool_buttons = [
			(self.vertical_flip_image, self.flip_vertical),
			(self.horizontal_flip_image, self.flip_horizontal),
			(self.rotate_left_image, self.rotate_left),
			(self.rotate_right_image, self.rotate_right),
		]
		self.tool_bar = ToolBar(tool_buttons, self.right_side_frame)
		self.tool_bar.pack(side = "top", fill = "x")


		layer_menu = Menu(self, tearoff = 0)
		layer_menu.add_command(label = "Rename Current Layer", command = self.rename_selected_layer)
		layer_menu.add_command(label = "Export Current Layer", command = self.save)
		layer_menu.add_command(label = "Export Current Layer as Bytes (Console)", command = self.export_selected_layer_as_bytes)
		layer_menu.add_command(label = "Delete Current Layer", command = self.delete_selected_layer)
		layer_menu.add_command(label = "Duplicate Current Layer", command = self.copy_selected_layer)
		layer_menu.add_command(label = "Promote Current Layer", command = self.promote_selected_layer)
		layer_menu.add_command(label = "Demote Current Layer", command = self.demote_selected_layer)
		layer_menu.add_command(label = "Merge Layer Down", command = self.merge_selected_layer_down)
		layer_menu.add_separator()
		layer_menu.add_command(label = "Rename Current Frame", command = self.rename_selected_frame)
		layer_menu.add_command(label = "Export Current Frame", command = self.save_selected_frame)
		layer_menu.add_command(label = "Export Current Frame as Bytes (Console)", command = self.export_selected_frame_as_bytes)
		layer_menu.add_command(label = "Delete Current Frame", command = self.delete_selected_frame)
		layer_menu.add_command(label = "Duplicate Current Frame", command = self.copy_selected_frame)
		layer_menu.add_command(label = "Promote Current Frame", command = self.promote_selected_frame)
		layer_menu.add_command(label = "Demote Current Frame", command = self.demote_selected_frame)
		layer_menu.add_command(label = "New Layer in Current Frame", command = self.new_layer_in_selected_frame)
		layer_menu.add_command(label = "New Layer from Image in Current Frame", command = self.new_layer_from_image_in_selected_frame)
		self.layer_options_menu_button = Label(self.tool_bar, image = self.layers_symbol_image, font = "bold")
		self.layer_options_menu_button.pack(side = "left")
		bind_popup("<Button-1>", self.layer_options_menu_button, layer_menu)

		selection_menu = Menu(self, tearoff=0)
		selection_menu.add_command(label = "Flood Fill Selection", command = self.fill_selection)
		selection_menu.add_command(label = "Flip Selection Vertical", command = self.flip_selection_vertical)
		selection_menu.add_command(label = "Flip Selection Horizontal", command = self.flip_selection_horizontal)
		selection_menu.add_command(label = "Rotate Selection Right", command = self.rotate_selection_right)
		selection_menu.add_command(label = "Rotate Selection Left", command = self.rotate_seletion_left)
		selection_menu.add_command(label = "Export Selection", command = self.export_selection)
		selection_menu.add_command(label = "Export Selection as Bytes (Console)", command = self.export_selection_as_bytes)
		selection_menu.add_separator()
		selection_menu.add_command(label = "Copy Selection to Clipboard", command = self.copy_selection_to_clipboard)
		selection_menu.add_command(label = "New Layer from Selection", command = self.new_layer_image_from_selection)
		selection_menu.add_separator()
		selection_menu.add_command(label = "Apply Blur Filter to Selection", command = self.effect_blur_selection)
		selection_menu.add_command(label = "Apply Contour Filter to Selection", command = self.effect_contour_selection)
		selection_menu.add_command(label = "Apply Detail Filter to Selection", command = self.effect_detail_selection)
		selection_menu.add_command(label = "Apply Edge Enhance Filter to Selection", command = self.effect_edge_enhance_selection)
		selection_menu.add_command(label = "Apply Edge Enhance More Filter to Selection", command = self.effect_edge_enhance_more_selection)
		selection_menu.add_command(label = "Apply Emboss Filter to Selection", command = self.effect_emboss_selection)
		selection_menu.add_command(label = "Apply Find Edges Filter to Selection", command = self.effect_find_edges_selection)
		selection_menu.add_command(label = "Apply Sharpen Filter to Selection", command = self.effect_sharpen_selection)
		selection_menu.add_command(label = "Apply Smooth Filter to Selection", command = self.effect_smooth_selection)
		selection_menu.add_command(label = "Apply Smooth More Filter to Selection", command = self.effect_smooth_more_selection)
		selection_menu.add_command(label = "Apply Gaussian Filter to Selection", command = self.effect_gaussian_selection)
		selection_menu.add_command(label = "Apply Box Blur Filter to Selection", command = self.effect_box_blur_selection)
		selection_menu.add_command(label = "Apply Median Filter to Selection", command = self.effect_median_filter_selection)
		selection_menu.add_command(label = "Apply Min Filter to Selection", command = self.effect_min_filter_selection)
		selection_menu.add_command(label = "Apply Max Filter to Selection", command = self.effect_max_filter_selection)
		selection_menu.add_command(label = "Apply Mode Filter to Selection", command = self.effect_mode_filter_selection)
		self.selections_options_menu_button = Label(self.tool_bar, image = self.selection_options_image, font = "bold")
		self.selections_options_menu_button.pack(side = "left")
		bind_popup("<Button-1>", self.selections_options_menu_button, selection_menu)

		effects_menu = Menu(self, tearoff=0)
		effects_menu.add_command(label = "Apply Blur Filter", command = self.effect_blur_layer)
		effects_menu.add_command(label = "Apply Contour Filter", command = self.effect_contour_layer)
		effects_menu.add_command(label = "Apply Detail Filter", command = self.effect_detail_layer)
		effects_menu.add_command(label = "Apply Edge Enhance Filter", command = self.effect_edge_enhance_layer)
		effects_menu.add_command(label = "Apply Edge Enhance More Filter", command = self.effect_edge_enhance_more_layer)
		effects_menu.add_command(label = "Apply Emboss Filter", command = self.effect_emboss_layer)
		effects_menu.add_command(label = "Apply Find Edges Filter", command = self.effect_find_edges_layer)
		effects_menu.add_command(label = "Apply Sharpen Filter", command = self.effect_sharpen_layer)
		effects_menu.add_command(label = "Apply Smooth Filter", command = self.effect_smooth_layer)
		effects_menu.add_command(label = "Apply Smooth More Filter", command = self.effect_smooth_more_layer)
		effects_menu.add_command(label = "Apply Gaussian Filter", command = self.effect_gaussian_layer)
		effects_menu.add_command(label = "Apply Box Blur Filter", command = self.effect_box_blur_layer)
		effects_menu.add_command(label = "Apply Median Filter", command = self.effect_median_filter_layer)
		effects_menu.add_command(label = "Apply Min Filter", command = self.effect_min_filter_layer)
		effects_menu.add_command(label = "Apply Max Filter", command = self.effect_max_filter_layer)
		effects_menu.add_command(label = "Apply Mode Filter", command = self.effect_mode_filter_layer)
		self.effects_options_menu_button = Label(self.tool_bar, image = self.effects_wand_symbol, font = "bold")
		self.effects_options_menu_button.pack(side = "left")
		bind_popup("<Button-1>", self.effects_options_menu_button, effects_menu)

		copy_options_menu = Menu(self, tearoff=0)
		copy_options_menu.add_command(label = "Copy Current Layer to Clipboard", command = self.copy_selected_layer_to_clipboard)
		copy_options_menu.add_command(label = "Copy Current Frame to Clipboard", command = self.copy_selected_frame_to_clipboard)
		copy_options_menu.add_command(label = "Copy Selection to Clipboard", command = self.copy_selection_to_clipboard)
		copy_options_menu.add_separator()
		copy_options_menu.add_command(label = "Paste As New Layer in Current Frame", command = self.paste_as_new_layer_in_current_frame)
		copy_options_menu.add_command(label = "Paste As New Layer in New Frame", command = self.paste_as_new_layer_in_new_frame)
		copy_options_button = Label(self.tool_bar, image = self.copy_options_symbol, font = "bold")
		copy_options_button.pack(side = "left")
		bind_popup("<Button-1>", copy_options_button, copy_options_menu)

		undo_button =  Label(self.tool_bar, image = self.undo_symbol)
		undo_button.pack(side = "left")
		undo_button.bind("<Button-1>", self.undo)

		redo_button =  Label(self.tool_bar, image = self.redo_symbol)
		redo_button.pack(side = "left")
		redo_button.bind("<Button-1>", self.redo)

		self.canvas_frame = ttk.LabelFrame(self.right_side_frame, text = "")
		self.canvas_frame.pack(fill = "both", expand = True, anchor = "n", padx = 3)
		inner_frame = Frame(self.canvas_frame)
		inner_frame.pack(fill = "both", expand = True, side = "top", anchor = "n", padx = 4, pady = 4)
		self.canvas = LyfeCanvas(self.project, inner_frame)
		force_aspect(self.canvas, inner_frame, float(self.width)/float(self.height))

		self.footer = Frame(self.right_side_frame)
		self.footer.pack(side = "bottom", fill = "x", expand = False, padx = 3)
		self.footer_var = StringVar()
		self.footer_label = Label(self.footer, textvariable = self.footer_var)
		self.footer_label.pack(side = "left", expand = False, fill = "x")

		self.grip = ttk.Sizegrip(self)
		self.grip.place(relx=1.0, rely=1.0, anchor="se")
		self.grip.bind("<ButtonPress-1>", self.on_press)
		self.grip.bind("<B1-Motion>", self.on_resize)
		self.grip.bind("<ButtonRelease-1>", self.on_release)

		self.canvas.bind_middle(self.eyedrop)
		self.canvas.bind_movement(self.on_mouse_move)
		self.canvas.canvas.bind("<ButtonPress-1>", self.on_canvas_click)
		self.canvas.canvas.bind("<B1-Motion>", self.on_canvas_drag)
		self.canvas.canvas.bind("<ButtonRelease-1>", self.on_canvas_release)
		self.canvas.canvas.bind("<ButtonPress-3>", self.on_erase_start)
		self.canvas.bind_right_drag(self.on_erase)
		self.canvas.canvas.bind("<ButtonRelease-3>", self.on_erase_end)

		self.canvas.after_idle(self.refresh)
示例#41
0
    def __init__(self, controller):
        ttk.Frame.__init__(self)
        self.controller = controller
        self.window = self._nametowidget(self.winfo_parent())
        self.window.bind("<Escape>", self.exit)
        self.window.title("LyfePixel")
        self.window.protocol("WM_DELETE_WINDOW", self.exit)

        self.controller.configure_toplevel(self.window)
        self.window.overrideredirect(0)
        self.place(relwidth=1, relheight=1)
        self.state = TOOLCONST.DRAW
        self.window.resizable(True, True)
        self.project = PixelProject(8, 8)
        self.pallet = self.project.selected_frame.selected_layer
        self.pallet.selection = [
            f"{self.pallet.width - 1}x{self.pallet.height - 1}"
        ]
        self.alpha = 255

        menubar = Menu(self.window)
        menubar.add_command(label="New", command=self.open_start_window)
        menubar.add_separator()
        menubar.add_command(label="Help",
                            command=lambda: HelpWindow(self.controller))
        menubar.add_separator()
        # display the menu
        self.window.config(menu=menubar)

        panes = PanedWindow(self,
                            orient="vertical",
                            sashpad=3,
                            sashrelief="sunken")
        panes.pack(fill="both", expand=True)
        panes.config(borderwidth=0)

        canvas_frame = Frame(panes)
        canvas_frame.pack(fill="both", expand=True, side="top", anchor="n")
        panes.add(canvas_frame)
        panes.paneconfigure(canvas_frame, height=150)
        self.pallet_box = LyfeCanvas(self.project, canvas_frame)
        force_aspect(self.pallet_box, canvas_frame, 1.0)
        colors = get_gradient(8)
        colors.extend(get_rainbow(56))
        for id in self.pallet_box.itterate_canvas():
            self.pallet.set_pixel_color(id, hex_to_rgba(colors.pop()))
        self.pallet_box.bind_left(self.select_color)
        self.pallet_box.bind_double_left(self.change_color)
        self.pallet_box.bind("<Configure>", self.on_configure)
        self.pallet_box.configure()

        outer_frame = Frame(panes)
        outer_frame.pack(fill="both", expand=True, padx=4)
        panes.add(outer_frame)
        panes.paneconfigure(outer_frame, height=250)

        color_label_frame = Frame(outer_frame)
        self.color_label_text_var = StringVar()
        self.color_label_text_var.set(ToolController.get_color())
        color_label = Label(color_label_frame,
                            textvariable=self.color_label_text_var)
        color_label.pack(side="bottom", fill="x", expand=True)
        color_label_frame.pack(fill="x", expand=True)

        self.alpha_scale = Scale(outer_frame,
                                 orient="horizontal",
                                 from_=0,
                                 to=255,
                                 command=self.set_alpha)
        self.alpha_scale.set(self.alpha)
        self.alpha_scale.pack(fill="x", expand=True, pady=2)

        div_1 = ttk.Separator(outer_frame)
        div_1.pack(fill="x", expand=True, pady=2)

        self.toolbox = ToolBox(outer_frame)
        self.toolbox.pack(fill="both", expand=True, pady=2)

        self.grip = ttk.Sizegrip(self)
        self.grip.place(relx=1.0, rely=1.0, anchor="se")
        self.grip.bind("<ButtonPress-1>", self.on_press)
        self.grip.bind("<B1-Motion>", self.on_resize)
        self.grip.bind("<ButtonRelease-1>", self.on_release)

        self.clipboard_box = ClipBoardBox(self.controller, panes)
        self.clipboard_box.pack(fill="both", expand=True)
        panes.add(self.clipboard_box)

        self.window.minsize(250, 400)
        self.window.geometry(f"250x720")
        self.pallet_box.after_idle(self.refresh)

        color = self.pallet.array[self.pallet.width - 1][self.pallet.height -
                                                         1]
        ToolController.set_color(color)
        self.alpha = color[3]
        self.alpha_scale.set(self.alpha)
        self.pallet.start_selection = id
        self.pallet.end_selection = id
        self.update()
示例#42
0
class Ufd:
    """
        Universal File Dialog - "UFD"
        
        Unopinionated, minimalist, reusable, slightly configurable,
        general-purpose file-dialog.
    """
    def __init__(self,
                 title: str = "Universal File Dialog",
                 icon: str = "",
                 show_hidden: bool = False,
                 include_files: bool = True,
                 multiselect: bool = True,
                 select_dirs: bool = True,
                 select_files: bool = True,
                 unix_delimiter: bool = True,
                 stdout: bool = False):
        """
            Init kwargs as object attributes, save references to 
            Tk PhotoImages, & define the widgets + layout
        """

        if not isinstance(title, str):
            raise TypeError("Argument title must be type string.")

        self.title = title

        if icon:
            if not isinstance(icon, str):
                raise TypeError("Argument icon must be type string.")

            if not isfile(icon):
                raise FileNotFoundError(f"File not found: {icon}")

            self.icon = icon

        else:
            self.icon = ""

        if show_hidden:
            self.show_hidden = True
        else:
            self.show_hidden = False

        if include_files:
            self.include_files = True
        else:
            self.include_files = False

        if multiselect:
            self.multiselect = True
        else:
            self.multiselect = False

        if select_dirs:
            self.select_dirs = True
        else:
            self.select_dirs = False

        if select_files:
            self.select_files = True
        else:
            self.select_files = False

        if unix_delimiter:
            self.unix_delimiter = True
        else:
            self.unix_delimiter = False

        if stdout:
            self.stdout = True
        else:
            self.stdout = False

        # Tkinter:
        self.dialog = Tk()
        self.dialog.withdraw()
        self.dialog.title(self.title)
        self.dialog.minsize(width=300, height=200)
        self.dialog.geometry("500x300")
        self.dialog.update_idletasks()

        self.file_icon = PhotoImage(file=f"{dirname(__file__)}/file.gif",
                                    master=self.dialog).subsample(50)

        self.folder_icon = PhotoImage(file=f"{dirname(__file__)}/folder.gif",
                                      master=self.dialog).subsample(15)

        self.disk_icon = PhotoImage(file=f"{dirname(__file__)}/disk.gif",
                                    master=self.dialog).subsample(15)

        if self.icon:
            self.dialog.iconbitmap(self.icon)
        else:
            self.dialog.iconbitmap(f"{dirname(__file__)}/icon.ico")

        # Widgets:
        self.paneview = PanedWindow(
            self.dialog,
            sashwidth=7,
            bg="#cccccc",
            bd=0,
        )

        self.left_pane = PanedWindow(self.paneview)
        self.right_pane = PanedWindow(self.paneview)
        self.paneview.add(self.left_pane)
        self.paneview.add(self.right_pane)

        self.treeview_x_scrollbar = Scrollbar(self.left_pane,
                                              orient="horizontal")
        self.treeview_y_scrollbar = Scrollbar(self.left_pane,
                                              orient="vertical")
        self.list_box_x_scrollbar = Scrollbar(self.right_pane,
                                              orient="horizontal")
        self.list_box_y_scrollbar = Scrollbar(self.right_pane,
                                              orient="vertical")

        # tstyle = Style().configure(".", )

        self.treeview = Treeview(
            self.left_pane,
            xscrollcommand=self.treeview_x_scrollbar.set,
            yscrollcommand=self.treeview_y_scrollbar.set,
            show="tree",
            selectmode="browse",
            # style=tstyle
        )

        self.list_box = Listbox(self.right_pane,
                                xscrollcommand=self.list_box_x_scrollbar.set,
                                yscrollcommand=self.list_box_y_scrollbar.set,
                                width=34,
                                highlightthickness=0,
                                bd=2,
                                relief="ridge")

        if self.multiselect:
            self.list_box.config(selectmode="extended")
        else:
            self.list_box.config(selectmode="browse")

        self.cancel_button = Button(self.left_pane,
                                    text="Cancel",
                                    command=self.cancel)

        self.submit_button = Button(self.right_pane,
                                    text="Submit",
                                    command=self.submit)

        self.treeview_x_scrollbar.config(command=self.treeview.xview)
        self.treeview_y_scrollbar.config(command=self.treeview.yview)
        self.list_box_x_scrollbar.config(command=self.list_box.xview)
        self.list_box_y_scrollbar.config(command=self.list_box.yview)

        #Layout:
        self.dialog.rowconfigure(0, weight=1)
        self.dialog.columnconfigure(0, weight=1)

        self.left_pane.grid_rowconfigure(0, weight=1)
        self.left_pane.grid_columnconfigure(0, weight=1)
        self.right_pane.grid_rowconfigure(0, weight=1)
        self.right_pane.grid_columnconfigure(0, weight=1)

        self.paneview.paneconfigure(
            self.left_pane,
            minsize=100,
            #Start off w/ the sash centered in the GUI:
            width=(self.dialog.winfo_width() / 2) - ceil(
                (self.paneview.cget("sashwidth") * 1.5)),
        )
        self.paneview.paneconfigure(self.right_pane, minsize=100)

        self.paneview.grid(row=0, column=0, sticky="nsew")

        self.treeview.grid(row=0, column=0, sticky="nsew")
        self.treeview_y_scrollbar.grid(row=0, column=1, sticky="ns")
        self.treeview_x_scrollbar.grid(row=1,
                                       column=0,
                                       columnspan=2,
                                       sticky="ew")

        self.list_box.grid(row=0, column=0, sticky="nsew")
        self.list_box_y_scrollbar.grid(row=0, column=1, sticky="ns")
        self.list_box_x_scrollbar.grid(row=1,
                                       column=0,
                                       columnspan=2,
                                       sticky="ew")

        self.cancel_button.grid(row=2, column=0, sticky="w", padx=10, pady=10)
        self.submit_button.grid(row=2,
                                column=0,
                                columnspan=2,
                                sticky="e",
                                padx=10,
                                pady=10)

        #Bindings, Protocols, & Misc:
        self.dialog.bind("<Control-w>", self.cancel)
        self.treeview.bind("<<TreeviewSelect>>", self.treeview_select)
        self.treeview.bind("<Double-Button-1>", self.dialog_populate)
        self.treeview.bind("<Return>", self.dialog_populate)
        self.treeview.bind("<Right>", self.dialog_populate)
        self.list_box.bind("<<ListboxSelect>>", self.list_box_select)
        self.list_box.bind("<Return>", self.submit)
        self.dialog.protocol("WM_DELETE_WINDOW", self.cancel)

        self.dialog_selection = deque()
        self.selection_paths = deque()

        for disk in self.get_disks():
            self.treeview.insert(
                "",
                index="end",
                text=disk,
                image=self.disk_icon,
            )

        self.dialog.focus()

    def __call__(self):
        """
            Display dialog & return selection
        """

        (width_offset, height_offset) = self.get_offset(self.dialog)
        self.dialog.geometry(f"+{width_offset}+{height_offset}")
        self.dialog.update_idletasks()
        self.dialog.deiconify()

        self.dialog.wait_window()

        for i, path in enumerate(self.dialog_selection):
            if self.unix_delimiter:
                self.dialog_selection[i] = sub("\\\\", "/", path)
            else:
                self.dialog_selection[i] = sub("/", "\\\\", path)

        if self.stdout:
            [print(item) for item in self.dialog_selection]

        return list(self.dialog_selection)

    def __str__(self):
        """
            Return own address
        """

        return "Universal File Dialog"\
        f" @ {hex(id(self))}"

    def __repr__(self):
        """
            Return full string representation of constructor signature
        """

        return f"Ufd("\
        f"title=\"{self.title}\","\
        f" icon=\"{self.icon}\","\
        f" show_hidden={self.show_hidden},"\
        f" include_files={self.include_files},"\
        f" multiselect={self.multiselect},"\
        f" select_dirs={self.select_dirs},"\
        f" select_files={self.select_files},"\
        f" unix_delimiter={self.unix_delimiter})"\
        f" stdout={self.stdout})"\
        f" @ {hex(id(self))}"

    @staticmethod
    def get_offset(tk_window):
        """
            Returns an appropriate offset for a given tkinter toplevel,
            such that it always is created center screen on the primary display.
        """

        width_offset = int((tk_window.winfo_screenwidth() / 2) -
                           (tk_window.winfo_width() / 2))

        height_offset = int((tk_window.winfo_screenheight() / 2) -
                            (tk_window.winfo_height() / 2))

        return (width_offset, height_offset)

    @staticmethod
    def get_disks():
        """
            Returns all mounted disks (for Windows)

            >> ["A:", "B:", "C:"]
        """

        if system() != "Windows":
            raise OSError("For use with Windows platforms.")

        logicaldisks = run(["wmic", "logicaldisk", "get", "name"],
                           capture_output=True)

        return findall("[A-Z]:", str(logicaldisks.stdout))

    @staticmethod
    def list_dir(path, force=False):
        """
            Reads a directory with a shell call to dir.
            Truthiness of bool force determines whether 
            hidden items are returned or not. (For Windows)
        """

        path = sub("/", "\\\\", path)

        if force:
            dir_listing = run(["dir", path, "/b", "/a"],
                              shell=True,
                              capture_output=True)

        else:
            dir_listing = run(["dir", path, "/b"],
                              shell=True,
                              capture_output=True)

        output = dir_listing.stdout
        err = dir_listing.stderr

        if not output:
            return []

        if err:
            err = err.decode("utf-8")
            raise Exception(err)

        str_output = output.decode("utf-8")
        list_output = re_split("\r\n", str_output)

        return sorted([item for item in list_output if item])

    def climb(self, item):
        """
            Builds & returns a complete path to root directory,
            including the item name itself as the path tail.
            An extra delimiter is appeneded for the subsequent
            child node, which is normalized in dialog_populate()
        """

        item_text = self.treeview.item(item)["text"]
        parent = self.treeview.parent(item)
        path = ""
        parents = deque()

        while parent:
            parents.append(self.treeview.item(parent)["text"] + "/")
            parent = self.treeview.parent(parent)

        for parent in reversed(parents):
            path += parent

        path += item_text + "/"
        return path

    def dialog_populate(self, event=None):
        """
            Dynamically populates & updates the treeview, listbox,
            and keeps track of the full paths corresponding to each
            item in the listbox
        """
        if not self.treeview.focus():
            return

        self.treeview.column("#0", width=1000)

        existing_children = self.treeview.get_children(self.treeview.focus())
        [self.treeview.delete(child) for child in existing_children]

        self.list_box.delete(0, "end")
        self.selection_paths.clear()

        focus_item = self.treeview.focus()
        path = self.climb(focus_item)

        if self.show_hidden:
            children = self.list_dir(path, force=True)
        else:
            children = self.list_dir(path)

        for child in children:
            if isdir(path + child):

                self.treeview.insert(focus_item,
                                     index="end",
                                     text=child,
                                     image=self.folder_icon)

                if self.select_dirs:
                    self.list_box.insert("end", child)
                    self.selection_paths.append(path + child)

            elif isfile(path + child):

                if self.include_files:
                    self.treeview.insert(focus_item,
                                         index="end",
                                         text=child,
                                         image=self.file_icon)

                if self.select_files:
                    self.list_box.insert("end", child)
                    self.list_box.itemconfig("end", {"bg": "#EAEAEA"})
                    self.selection_paths.append(path + child)

        if isfile(normpath(path)):
            (head, tail) = path_split(normpath(path))
            head = sub("\\\\", "/", head)

            self.list_box.insert("end", tail)
            self.selection_paths.append(head + "/" + tail)
            self.list_box.itemconfig("end", {"bg": "#EAEAEA"})

    def list_box_select(self, event=None):
        """
            Dynamically refresh the dialog selection with
            what's selected in the listbox
            (Callback for <<ListboxSelect>>).
        """

        self.dialog_selection.clear()

        for i in self.list_box.curselection():
            self.dialog_selection.append(self.selection_paths[i])

    def treeview_select(self, event=None):
        """
            Dynamically refresh the dialog selection with
            what's selected in the treeview
            (Callback for <<TreeviewSelect>>).
        """

        for i in self.list_box.curselection():
            self.list_box.selection_clear(i)

        self.dialog_selection.clear()

        item = normpath(self.climb(self.treeview.focus()))
        self.dialog_selection.append(item)

    def submit(self, event=None):
        """
            Satisfies wait_window() in self.__call__() and validates selection

            (Callback for <Return>, <Button-1> on file_list, submit_button)
        """

        if self.select_dirs == False:
            for item in self.dialog_selection:
                if isdir(item):
                    messagebox.showwarning(
                        "Error - Invalid Selection",
                        "Unable to select directory. Please select a file(s).")
                    return

        if self.select_files == False:
            for item in self.dialog_selection:
                if isfile(item):
                    messagebox.showwarning(
                        "Error - Invalid Selection",
                        "Unable to select file. Please select a folder(s)")
                    return

        self.dialog.destroy()

    def cancel(self, event=None):
        """
            Satisfies wait_window() in self.__call__() 

            (Callback for <Button-1> on cancel_button)
            (Callback for protocol "WM_DELETE_WINDOW" on self.dialog)
        """

        self.dialog_selection.clear()
        self.dialog.destroy()
示例#43
0
class ResultFrame(FrameTemplate):
    """Frame for display of equilibria in the conflict."""

    # Label used for button to select frame in the main program.
    buttonLabel = 'Equilibria Results'
    # Image used on button to select frame, when frame is active.
    activeIcon = 'icons/Equilibria_Results_ON.gif'
    # Image used on button to select frame, when frame is inactive.
    inactiveIcon = 'icons/Equilibria_Results_OFF.gif'
    # Help text to be displayed when screen is active.
    helpText = ("The stability of each state in the conflict is shown in the "
                "table on the left, giving results under a number of different"
                " stability criterion. The display on the right allows the "
                "logic which defines the stability or instability of each "
                "option to be examined.")

# ########################     INITIALIZATION  ################################
    def __init__(self, master, conflict, *args):
        """Initialize the Frame. Does not build widgets."""
        FrameTemplate.__init__(self, master, conflict, self.buttonLabel,
                               self.activeIcon, self.inactiveIcon,
                               self.helpText)

        self.lastBuildConflict = None

# ############################     METHODS  ###################################

    def hasRequiredData(self):
        """Check that minimum data required to render the frame exists."""
        if len(self.conflict.decisionMakers) < 1:
            return False
        if len(self.conflict.options) < 1:
            return False
        if len(self.conflict.feasibles) < 1:
            return False
        if self.conflict.preferenceErrors:
            return False
        else:
            return True

    def dataChanged(self):
        """Check if data has changed since the last build of the Frame."""
        if self.lastBuildConflict != self.conflict.export_rep():
            return True
        else:
            return False

    def buildFrame(self):
        """Contruct frame widgets and initialize data."""
        if self.built:
            return

        # Ensure all required parts of the conflict model are properly set-up.
        self.conflict.reorderOptionsByDM()
        self.conflict.options.set_indexes()
        self.conflict.infeasibles.validate()
        self.conflict.recalculateFeasibleStates()
        self.conflict.coalitions.validate()

        for dm in self.conflict.decisionMakers:
            dm.calculatePerceived()
            dm.calculatePreferences()

        self.lastBuildConflict = self.conflict.export_rep()

        # Define variables that will display in the infoFrame
        self.infoText = StringVar(value='')

        # Define frame-specific variables
        self.sol = LogicalSolver(self.conflict)
        self.sol.findEquilibria()

        # infoFrame: frame and label definitions (with master 'self.infoFrame')
        self.infoLabel = ttk.Label(self.infoFrame, textvariable=self.infoText)

        # helpFrame: frame and label definitions (with master 'self.helpFrame')
        self.helpLabel = ttk.Label(self.helpFrame, textvariable=self.helpVar,
                                   wraplength=150)

        # Define frame-specific input widgets (with 'self' as master)
        self.paneMaster = PanedWindow(self, orient=HORIZONTAL, sashwidth=10,
                                      sashrelief="raised", sashpad=3,
                                      relief="sunken")

        self.pane1 = ttk.Frame(self.paneMaster)
        self.coalitionSelector = CoalitionSelector(self.pane1, self.conflict,
                                                   self)
        self.solutionTable = OptionFormSolutionTable(self.pane1, self.conflict,
                                                     self)
        self.exporter = Exporter(self.pane1, self.conflict, self)

        self.pane2 = ttk.Frame(self.paneMaster)
        self.narrator = LogNarrator(self.pane2, self.conflict, self)

        # ########  preliminary gridding and option configuration

        # configuring the input frame
        self.grid(column=0, row=0, rowspan=5, sticky=NSEW)
        self.grid_remove()
        self.columnconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)

        # configuring infoFrame & infoFrame widgets
        self.infoFrame.grid(column=2, row=0, sticky=NSEW, padx=3, pady=3)
        self.infoFrame.grid_remove()
        self.infoLabel.grid(column=0, row=1, sticky=NSEW)

        # configuring helpFrame & helpFrame widgets
        self.helpFrame.grid(column=2, row=1, sticky=NSEW, padx=3, pady=3)
        self.helpFrame.grid_remove()
        self.helpLabel.grid(column=0, row=0, sticky=NSEW)

        # configuring frame-specific options
        self.paneMaster.grid(column=0, row=1, sticky=NSEW)
        self.paneMaster.add(self.pane1, width=600, stretch='always')
        self.pane1.rowconfigure(1, weight=1)
        self.pane1.columnconfigure(0, weight=1)
        self.coalitionSelector.grid(row=0, column=0, sticky=NSEW)
        self.solutionTable.grid(row=1, column=0, sticky=NSEW)
        self.exporter.grid(row=2, column=0, sticky=NSEW)

        self.paneMaster.add(self.pane2, width=250, stretch='always')
        self.pane2.rowconfigure(0, weight=1)
        self.pane2.columnconfigure(0, weight=1)
        self.narrator.grid(row=0, column=0, sticky=NSEW)

        # bindings
        self.coalitionSelector.bind("<<CoalitionsChanged>>",
                                    self.refresh)

        self.built = True

    def refresh(self, *args):
        """Refresh data in all active display widgets."""
        self.sol = LogicalSolver(self.conflict)
        self.sol.findEquilibria()
        self.coalitionSelector.refresh()
        self.solutionTable.refresh()
        self.narrator.refresh()