예제 #1
2
def draw_automata(turing_machine=None):

    w = len(turing_machine.states)
    h = len(turing_machine.rules)

    root = Tk()
    frame = Frame(root, width=800, height=600)
    frame.grid(row=0, column=0)
    canvas = Canvas(frame, bg='#FFFFFF', width=800, height=600,
                    scrollregion=(0, -h * 15, w * 100, h * 15*3))
    hbar = Scrollbar(frame, orient=HORIZONTAL)
    hbar.pack(side=BOTTOM, fill=X)
    hbar.config(command=canvas.xview)
    vbar = Scrollbar(frame, orient=VERTICAL)
    vbar.pack(side=RIGHT, fill=Y)
    vbar.config(command=canvas.yview)
    canvas.config(width=800, height=600)
    canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
    canvas.pack(side=LEFT, expand=True, fill=BOTH)

    for position, state in enumerate(turing_machine.states):
        state_position[state] = position
        loop_occurrences[position] = 0
        canvas_id = canvas.create_text(10 + 80 * position, 400, anchor="nw")
        canvas.itemconfig(canvas_id, text="state-")
        canvas.insert(canvas_id, 12, "%d" % state)

    counter = 1
    for rule in turing_machine.rules:
        counter = draw_arrow(state_position[rule.current_state],
                             state_position[rule.next_state],
                             canvas, counter, rule)

    root.mainloop()
예제 #2
0
class Widget_:

	def __init__(self, parent_frame, row, column, width=50, height=50):
		self.widget_frame = Frame(parent_frame, width=width, height=height)
		self.widget_frame.grid(row=row, column=column)
		self.width, self.height = width, height
		return

	def add_tag(self, tag_library, string):
		tag_library[string] = self

	def delete_widget(self):
		for child in self.widget_frame.winfo_children():
			child.destroy()
		self.widget_frame.destroy()

	def hide_widget(self):
		self.widget_frame.grid_forget()

	def get_info(self):
		return

	def set_field(self):
		return

	pass
예제 #3
0
파일: logui.py 프로젝트: shawncx/LogParser
 def _initjoincondpanel(self):
     frame = Frame(self)
     frame.grid(row=0, column=2, sticky=E + W + S + N, padx=5)
     
     label = Label(frame, text="Join Condition: ")
     label.grid(sticky=N + W)
     
     self.joincondlist = Listbox(frame)
     self.joincondlist.grid(row=1, rowspan=1, columnspan=3, sticky=E + W + S + N)
     
     vsl = Scrollbar(frame, orient=VERTICAL)
     vsl.grid(row=1, column=3, rowspan=1, sticky=N + S + W)
     
     hsl = Scrollbar(frame, orient=HORIZONTAL)
     hsl.grid(row=2, column=0, columnspan=3, sticky=W + E + N)
     
     self.joincondlist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
     
     hsl.config(command=self.joincondlist.xview)
     vsl.config(command=self.joincondlist.yview)
     
     newbtn = Button(frame, text="New", width=7, command=self._addjoincondition)
     newbtn.grid(row=3, column=0, padx=5, pady=5, sticky=E)
     
     delbtn = Button(frame, text="Delete", width=7, command=self._deletejoincondition)
     delbtn.grid(row=3, column=1, sticky=E)
     
     modbtn = Button(frame, text="Update", width=7, command=self._modifyjoincondition)
     modbtn.grid(row=3, column=2, padx=5, pady=5, sticky=W)
예제 #4
0
    def showPlotTools(self):        
        
        f2= Frame(self.frame, relief=FLAT,bg='#FADC46')
        f2.grid(row=1,column=0,rowspan=2,columnspan=3,sticky=N+S+E+W,padx=10,pady =10)
        
        b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1))
        b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5)
        
        b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2))
        b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5)
        
        b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3))
        b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5)
        
        b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4))
        b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5)

        b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5))
        b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5)

        b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6))
        b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5)
        
        f2.columnconfigure(0, weight=1)
        f2.columnconfigure(1, weight=1)
        f2.columnconfigure(2, weight=1)

        f2.rowconfigure(0, weight=1)
        f2.rowconfigure(1, weight=1)
예제 #5
0
파일: logui.py 프로젝트: shawncx/LogParser
 def _initfilepanel(self):
     frame = Frame(self)
     frame.grid(row=0, column=0, sticky=E + W + S + N)
     
     label = Label(frame, text="File List: ")
     label.grid(sticky=N + W)
     
     self.filelist = Listbox(frame, width=40)
     self.filelist.grid(row=1, column=0, rowspan=2, columnspan=3)
     
     vsl = Scrollbar(frame, orient=VERTICAL)
     vsl.grid(row=1, column=3, rowspan=2, sticky=N + S + W)
     
     hsl = Scrollbar(frame, orient=HORIZONTAL)
     hsl.grid(row=3, column=0, columnspan=3, sticky=W + E + N)
     
     self.filelist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
     self.filelist.bind('<<ListboxSelect>>', self._onfilelistselection)
     
     hsl.config(command=self.filelist.xview)
     vsl.config(command=self.filelist.yview)
     
     upbtn = Button(frame, text="Up", width=7, command=self._upfile)
     upbtn.grid(row=1, column=4, padx=5, pady=5)
     
     downbtn = Button(frame, text="Down", width=7, command=self._downfile)
     downbtn.grid(row=2, column=4, padx=5, pady=5)
     
     newbtn = Button(frame, text="New", width=7, command=self._addfile)
     newbtn.grid(row=4, column=1, pady=5, sticky=E + S)
     
     delbtn = Button(frame, text="Delete", width=7, command=self._deletefile)
     delbtn.grid(row=4, column=2, padx=5, pady=5, sticky=W + S)
예제 #6
0
파일: tkui.py 프로젝트: mindhog/mawb
class ProgramWidget(Frame):

    def __init__(self, parent, client):
        super(ProgramWidget, self).__init__(parent)
        self.client = client
        self.client.onProgramChange = self.programChanged

        self.programLabel = Label(self, text = 'Program:')
        self.programLabel.grid(row = 0, column = 0)
        self.programEntry = Entry(self, text = 'Program name',
                                  state = 'readonly')
        self.programEntry.grid(row = 0, column = 1)
        self.buttonPanel = Frame(self)
        self.buttonPanel.grid(row = 1, column = 0, columnspan = 2, sticky = W)
        self.newButton = Button(self.buttonPanel, text='New',
                                command = self.newProgram)
        self.newButton.pack(side = LEFT)

    def programChanged(self):
        self.__setProgramText(str(self.client.state))

    def __setProgramText(self, text):
        self.programEntry.configure(state = NORMAL)
        self.programEntry.delete(0)
        self.programEntry.insert(0, text)
        self.programEntry.configure(state = 'readonly')

    def newProgram(self):
        self.client.makeNewProgram()
예제 #7
0
파일: Gui.py 프로젝트: xistingsherman/SPTOR
    def home_page(self, master):
        frame = Frame(master)
        frame.grid(row=0, column=0)

        image = PhotoImage(file="img/guido.gif")
        bg = Label(frame, image=image)
        bg.image = image
        bg.grid(row=0, column=0, rowspan=4, columnspan=2)

        index = 0
        while index < 3:
            frame.grid_columnconfigure(index, minsize=200)
            frame.grid_rowconfigure(index, minsize=80)
            index += 1

        summary_button = HomeButton(frame, self.to_summary, 'img/summary.png')
        summary_button.grid(row=0, column=0, sticky='w')

        edit_button = HomeButton(frame, self.to_edit, 'img/edit.png')
        edit_button.grid(row=0, column=1, sticky='e')

        momentary_button = HomeButton(frame, self.to_momentary, 'img/momentary.png')
        momentary_button.grid(row=1, column=0, sticky='w')

        preferences_button = HomeButton(frame, self.to_pref, 'img/preferences.png')
        preferences_button.grid(row=1, column=1, sticky='e')

        music = HomeButton(frame, self.to_summary, 'img/music.png')
        music.grid(row=2, column=0, sticky='w')

        info = HomeButton(frame, self.to_summary, 'img/info.png')
        info.grid(row=2, column=1, sticky='e')

        return frame
예제 #8
0
    def __init__(self, root, title):
        self.root = root
        self.root.title(title)

        # Variable that stores file handle (may be unnecessary)
        self.file_handle = ""

        master_frame = Frame(root)
        master_frame.pack(expand="yes", fill="both")

        # Create left button frame and buttons
        button_frame = Frame(master_frame)
        self.open_button = Button(button_frame, text="Choose File", command=self.load_file)
        self.open_button.pack(expand="yes", fill="both")
        self.apply_button = Button(button_frame, text="Apply", command=self.apply_consistent, state="disabled")
        self.apply_button.pack(expand="yes", fill="both")
        self.save_button = Button(button_frame, text="Save File", command=self.save_file, state="disabled")
        self.save_button.pack(expand="yes", fill="both")

        # Create text frame and initialize text widget
        text_frame = Frame(master_frame)
        self.text_box = Text(text_frame, height=10, width=50, state="disabled")
        self.text_box.pack(side="top", expand="yes", fill="both")

        # Configure weights for grid elements
        master_frame.columnconfigure(0, weight=1)
        master_frame.columnconfigure(1, weight=5)
        for i in range(3):
            master_frame.rowconfigure(i, weight=1)

        # Position button and text frames
        button_frame.grid(row=0, column=0, rowspan=3, sticky="nsew")
        text_frame.grid(row=0, column=1, rowspan=3, sticky="nsew")
        
        self.root.minsize(500, 200)
예제 #9
0
    def __init__(self):
        Toplevel.__init__(self)
        self.focus_set()
        self.grab_set()

        self.result = None
        self.module_data = None
        self.mod_applis = None
        self.title(ugettext("Instance editor"))
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self.ntbk = ttk.Notebook(self)
        self.ntbk.grid(row=0, column=0, columnspan=1, sticky=(N, S, E, W))

        self.frm_general = Frame(self.ntbk, width=350, height=150)
        self.frm_general.grid_columnconfigure(0, weight=0)
        self.frm_general.grid_columnconfigure(1, weight=1)
        self._general_tabs()
        self.ntbk.add(self.frm_general, text=ugettext('General'))

        self.frm_database = Frame(self.ntbk, width=350, height=150)
        self.frm_database.grid_columnconfigure(0, weight=0)
        self.frm_database.grid_columnconfigure(1, weight=1)
        self._database_tabs()
        self.ntbk.add(self.frm_database, text=ugettext('Database'))

        btnframe = Frame(self, bd=1)
        btnframe.grid(row=1, column=0, columnspan=1)
        Button(btnframe, text=ugettext("OK"), width=10, command=self.apply).grid(
            row=0, column=0, sticky=(N, S, E))
        Button(btnframe, text=ugettext("Cancel"), width=10, command=self.destroy).grid(
            row=0, column=1, sticky=(N, S, W))
예제 #10
0
 def create_region_frame(self, tid):
     """ Initiliases a frame on the map for region with id tid. """
     x = int(tid.split("_")[1])
     N = int(sqrt(len(self.board)))
     my_frame = Frame(self.frame_map, height=3 * self.size - 1,
                      width=3 * self.size - 1, bd=2, relief="flat")
     my_frame.grid(row=int((x - 1) / N), column=(x - 1) % N)
     self.board_regions[tid] = my_frame
예제 #11
0
 def make_frame(self,labeltext=None):
     "Return gridded labeled Frame for option or other buttons."
     if labeltext:
         l = Label(self.top, text=labeltext)
         l.grid(row=self.row, column=0, sticky="nw")
     f = Frame(self.top)
     f.grid(row=self.row, column=1, columnspan=1, sticky="nwe")
     self.row = self.row + 1
     return f
예제 #12
0
파일: client.py 프로젝트: Omertorren/ex12
 def __create_app_frame(self):
     """
     This function creates and pack (using grid) the main app frame
     (The left toolbar (users list) and the canvas
     """
     app_frame = Frame(self.__master_splinter)
     self.create_game_canvas(app_frame)
     self.create_left_toolbar(app_frame)
     app_frame.grid(row=1)
    def __init__(self, master):
        column0_padx = 24
        row_pady = 36

        #Label 1
        lbl_testcase_exec = Label(master, text="Test case execution",
                                  wraplength=100, anchor='w', justify='left')
        lbl_results_cmp = Label(master, text="Results comparison",
                                wraplength=100, justify='left')
        lbl_tolerance = Label(master, text="Tolerance (5%)", wraplength=100)
        testcase_exec = Checkbutton(master)
        results_cmp = Checkbutton(master)
        tolerance = Entry(master, width=4)
        lbl_analysis = Label(master, text="Analysis Library")
        analysis_lib = Entry(master, width=30)

        lbl_testcase_exec.grid(row=0, column=2, padx=20, pady=12, sticky='w')
        lbl_results_cmp.grid(row=0, column=3, pady=12, sticky='w')
        lbl_tolerance.grid(row=0, column=4, padx=20, pady=12, sticky='wn')
        lbl_analysis.grid(row=1, column=0, sticky='w', padx=column0_padx)
        analysis_lib.grid(row=1, column=1, sticky='w')
        testcase_exec.grid(row=1, column=2, padx=20, sticky='w')
        results_cmp.grid(row=1, column=3, sticky='w')
        tolerance.grid(row=1, column=4, padx=20, sticky='w')

        #Label 2
        lbl_ref_analysis = Label(
            master, text="Reference Analysis Libary Version",
            wraplength=150, justify='left', pady=row_pady)
        ref_analysis_lib = Entry(master, width=30)
        lbl_ref_analysis.grid(row=2, column=0, sticky='w', padx=column0_padx)
        ref_analysis_lib.grid(row=2, column=1, sticky='w')

        # version
        lbl_version = Label(master, text="Version under Test")
        version = Label(master, text="vA.B.C.D")
        lbl_version.grid(row=3, column=0, sticky='w', padx=column0_padx)
        version.grid(row=3, column=1, sticky='w')

        # test all
        lbl_testall = Label(master, text="Test All")
        testall = Checkbutton(master)
        lbl_testall.grid(row=4, column=0, pady=row_pady, padx=column0_padx,
                         sticky='w')
        testall.grid(row=4, column=1, sticky='w')

        # buttons
        bottom_frame = Frame(master)
        bottom_frame.grid(row=5, column=1, columnspan=3, sticky='w')

        btn_start = Button(bottom_frame, text = "Go", width=7)
        btn_start.pack(side='left')
        btn_commit = Button(bottom_frame, text="Commit", width=7)
        btn_commit.pack(side='left', padx=80)
        btn_exit = Button(bottom_frame, text="Exit", width=7)
        btn_exit.pack(side='left')
예제 #14
0
    def __init__(self):
        """
            À completer !.
        """
        super().__init__()

        # Nom de la fenêtre.
        self.title("Ultimate Tic-Tac-Toe")

        # La partie de ultimate Tic-Tac-Toe
        self.partie = Partie()

        # Un ditionnaire contenant les 9 canvas des 9 plateaux du jeu
        self.canvas_uplateau = {}

        Button(self.canvas_uplateau, text ='Débuter la partie', command =self.demande_confirmation).\
            grid(row =0, column =4)

        self.var = IntVar()
        Checkbutton(self, text= 'VS ordinateur', variable=self.var, onvalue =1, offvalue =0).grid(row =0, column =2)


        # L'entrée du joueur1 est automatiquement demandé
        Label(self.canvas_uplateau, text ="Nom du Joueur 1:").\
            grid(row =0, column =0, sticky=E)
        self.joueur1 = Entry(self.canvas_uplateau, width =14)
        self.joueur1.grid(row =0, column =1, padx=5, pady=5, sticky=E+W)

#        Label (self.canvas_uplateau, text="Le tour: {}".format(self.partie.joueur_courant.nom)).grid(row=3, column=3)

        # L'entrée du joueur2 est selon la checkbox (peut etre l'ordinateur
        Label(self.canvas_uplateau, text ="Nom du Joueur 2:").\
            grid(row =1, column =0, sticky=E)
        self.joueur2 = Entry(self.canvas_uplateau, width =14)
        self.joueur2.grid(row =1, column =1, padx=5, pady=5, sticky=E+W)

        Button(self.canvas_uplateau, text = 'Quitter', command = self.quit).\
            grid (row = 5, column = 4, sticky = E)

        # Création des frames et des canvas du jeu
        for i in range(0, 3):
            for j in range(0, 3):
                cadre = Frame(self, borderwidth=5, relief=GROOVE, background = '#e1e1e1')
                cadre.grid(row=i+3, column=j, padx=5, pady=5)
                cadre.bind('<Enter>', self.entrer_frame)
                cadre.bind('<Leave>', self.sortir_frame)
                self.canvas_uplateau[i,j] = CanvasPlateau(cadre, self.partie.uplateau[i,j])
                self.canvas_uplateau[i,j].grid()
                # On lie un clic sur le Canvas à une méthode.
                self.canvas_uplateau[i,j].bind('<Button-1>', self.selectionner)

        # Ajout d'une étiquette d'information.
        self.messages = Label(self)
        self.messages.grid(columnspan=3)
class AddRestrictionDialog:
    def __init__(self, parent):
        self.parent = parent
        self.gui = Toplevel(parent.guiRoot)
        self.gui.grab_set()
        self.gui.focus()

        self.gui.columnconfigure(0, weight=1)
        self.gui.columnconfigure(1, weight=1)

        Label(self.gui, text="Enzyme:").grid(row=0, column=0, sticky="e", padx=5)
        self.entryEnzyme = Entry(self.gui)
        self.entryEnzyme.grid(row=0, column=1, sticky="w", padx=5, pady=10)
        self.frameButtonGroup = Frame(self.gui)
        self.frameButtonGroup.grid(row=1, column=0, columnspan=2, pady=10)
        self.buttonOK = Button(self.frameButtonGroup, text=" OK ")
        self.buttonCancel = Button(self.frameButtonGroup, text=" Cancel ")
        self.buttonOK.grid(row=0, column=1, sticky="w", padx=5)
        self.buttonCancel.grid(row=0, column=0, sticky="e", padx=5)

        # Set (minimum + max) Window size
        self.gui.update()
        self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height())
        self.gui.maxsize(self.gui.winfo_width(), self.gui.winfo_height())

        self.entryEnzyme.focus()

        self.buttonOK.bind("<ButtonRelease>", self.actionOK)
        self.buttonCancel.bind("<ButtonRelease>", self.actionCancel)
        self.entryEnzyme.bind("<Return>", self.actionOK)

        self.gui.mainloop()

    #         self.gui.grab_release()
    #         self.gui.destroy()

    def actionOK(self, event):
        enzymeString = self.entryEnzyme.get()
        if enzymeString in rest_dict.keys():

            if enzymeString in self.parent.optimizer.restrictionEnzymeList:
                showinfo("", (enzymeString + " was already added to the list"))
                return

            self.parent.optimizer.restrictionEnzymeList.append(enzymeString)
            self.parent.guiRoot.event_generate("<<Update>>", when="tail")
            self.gui.destroy()
        else:
            showinfo("", (enzymeString + " is not a valid restriction enzyme"))

    def actionCancel(self, event):
        self.gui.destroy()
예제 #16
0
    def addActionFrame(self):

        frame=Frame(self,relief=tk.RAISED,borderwidth=1)
        frame.pack(fill=tk.X,side=tk.TOP,\
                expand=0,padx=8,pady=5)

        #label=tk.Label(frame,text='Actions:',bg='#bbb')
        #label.grid(row=0,column=0,sticky=tk.W,padx=8)

        #---------------Action checkbuttons---------------
        frame.columnconfigure(0,weight=1)

        #---------------------2nd row---------------------
        subframe=Frame(frame)
        subframe.grid(row=1,column=0,columnspan=6,sticky=tk.W+tk.E,\
                pady=5)

        #-------------------Album options-------------------
        albumlabel=tk.Label(subframe,text=dgbk('专辑:'),\
                bg='#bbb')
        albumlabel.pack(side=tk.LEFT, padx=8)

        self.album=tk.StringVar()
        self.albumnames=['All',]
        self.albummenu=Combobox(subframe,textvariable=\
                self.album,values=self.albumnames,state='readonly')
        self.albummenu.current(0)
        self.albummenu.bind('<<ComboboxSelected>>',self.setAlbum)
        self.albummenu.pack(side=tk.LEFT,padx=8)
        
        #-------------------Quit button-------------------
        quit_button=tk.Button(subframe,text=dgbk('退出'),\
                command=self.quit)
        quit_button.pack(side=tk.RIGHT,padx=8)

        #-------------------Stop button-------------------
        '''
        self.stop_button=tk.Button(subframe,text='Stop',\
                command=self.stop)
        self.stop_button.pack(side=tk.RIGHT,padx=8)
        '''
                
        #-------------------Start button-------------------
        self.start_button=tk.Button(subframe,text=dgbk('开始'),\
                command=self.start,state=tk.DISABLED)
        self.start_button.pack(side=tk.RIGHT,pady=8)

        #-------------------Help button-------------------
        self.help_button=tk.Button(subframe,text=dgbk('帮助'),\
                command=self.showHelp)
        self.help_button.pack(side=tk.RIGHT,padx=8)
예제 #17
0
 def _build_cell(self, row: int, col: int) -> Frame:
     cell = Frame(self._content, borderwidth=5, relief=const.SUNKEN, height=50, width=50)
     
     cell._canvas = Canvas(master=cell, height=50, width=50)
     cell.row = row
     cell.col = col
     cell.bound = False
     
     cell.grid(row=row, column=col, sticky="nsew")
     cell.columnconfigure(0, weight=1)
     cell.rowconfigure(0, weight=1)
     
     cell._canvas.grid(row=0, column=0, sticky="nsew")
     return cell
예제 #18
0
    def _init_game(self) -> None:
        # Make some game constants more easily accessible
        self.rows = self.game.board.rows
        self.columns = self.game.board.cols
        
        #
        # Main window
        #
        self._root = Tk()
        self._root.title("Othello")
        self._root.columnconfigure(0, weight=1)
        self._root.rowconfigure(2, weight=1)
        self._root.minsize(50 * self.columns + 100, 50 * self.rows + 100)
        
        #
        # Score Label
        #
        score_frame = Frame(self._root)
        self._score_label = ttk.Label(score_frame, background="white", foreground="black", text="TEMPORARY LABEL") #TODO: compute label text
        
        score_frame.grid(row=0, column=0, sticky="ew")
        self._score_label.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
        
        score_frame.columnconfigure(0, weight=1)
        
        #
        # Info Label
        #
        info_frame = Frame(self._root)
        self._info_label = ttk.Label(info_frame, text="", background="white", foreground="black")
        
        info_frame.grid(row=1, column=0, sticky="ew")
        self._info_label.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
        
        info_frame.columnconfigure(0, weight=1)
        
        #
        # Game content (Othello board)
        #
        self._content = Frame(self._root)
        self._content.grid(row=2, column=0, sticky="nsew")
        
        self.cells = []
        
        for row in range(self.rows):
            for col in range(self.columns):
                self.cells.append(self._build_cell(row, col))
                self._content.columnconfigure(col, weight=1)

            self._content.rowconfigure(row, weight=1)
예제 #19
0
    def dessiner_canvas(self, parent):

        # Création d'un frame qui contient le plateau de jeu
        self.frame_plateau = Frame(parent)
        self.frame_plateau.grid(row = 10, column=0, padx=5, pady=5)

        # Création des frames et des canvas du jeu
        for i in range(0, 3):
            for j in range(0, 3):
                cadre = Frame(self.frame_plateau, borderwidth=5, relief=GROOVE)
                cadre.grid(row=i, column=j, padx=5, pady=5)
                self.canvas_uplateau[i,j] = CanvasPlateau(cadre, self.partie.uplateau[i,j])
                self.canvas_uplateau[i,j].grid()
                # On lie un clic sur le Canvas à une méthode.
                self.canvas_uplateau[i,j].bind('<Button-1>', self.selectionner)
예제 #20
0
파일: searchbase.py 프로젝트: 1st1/cpython
    def make_frame(self,labeltext=None):
        '''Return (frame, label).

        frame - gridded labeled Frame for option or other buttons.
        label - Label widget, returned for testing.
        '''
        if labeltext:
            label = Label(self.top, text=labeltext)
            label.grid(row=self.row, column=0, sticky="nw")
        else:
            label = ''
        frame = Frame(self.top)
        frame.grid(row=self.row, column=1, columnspan=1, sticky="nwe")
        self.row = self.row + 1
        return frame, label
예제 #21
0
    def create_region(self, tid):
        """
        create and fill frame-region inside frame
        """
        region_owner = self.board[tid]["owner"]
        if region_owner is None:
            owner_text = "Unoccupied"
            tile_color = None
            own_tile = False
        else:
            own_tile = True if region_owner == game.player.name else False
            owner_text = "Owner: " + str(region_owner)
            tile_color = COLOURS[self.player_names.index(region_owner)]

        my_frame = Frame(self.frame_map, height=3 * self.size - 1,
                         width=3 * self.size - 1, bd=1, relief="flat",
                         bg = tile_color)
            
        x = int(tid.split("_")[1])
        N = int(sqrt(len(self.board)))
        my_frame.grid(row=int((x - 1)/ N),column=(x - 1) % N)
        counter_text = "Troops: " + str(game.board[tid]["counters"])

        button_pic = Button(my_frame, image = self.gifs[game.board[tid]["terrain"]],
                    name = tid, command = lambda: self.conquer_region(tid))
        label_owner = Label(my_frame, text=owner_text, bg = tile_color)
        label_counters = Label(my_frame, text=counter_text, bg = tile_color)
        
        if own_tile:
            button_plus = Button(my_frame, image = self.gifs["plus"],
                                 command=lambda: self.reinforce(tid, 1))
            button_minus = Button(my_frame, image = self.gifs["minus"],
                                  command=lambda: self.reinforce(tid, -1))

            button_plus.grid(row = 0, column=0)
            button_pic.grid(row = 0, column=1)
            button_minus.grid(row=0, column=2)

            label_owner.grid(row=1, columnspan=3)
            label_counters.grid(row=2, columnspan=3)
        else:
            button_pic.grid(row=0, column=1)
            label_owner.grid(row=1, column=1)
            label_counters.grid(row=2, column=1)

        if tid in game.player.adjacent_regions:
            my_frame.config(relief = "raised")
예제 #22
0
파일: client.py 프로젝트: Omertorren/ex12
 def create_left_toolbar(self, app_frame):
     """
     This function creates and pack the left toolbar
     :param app_frame: root for this toolbar.. (Frame obj)
     :return:
     """
     left_toolbar = Frame(app_frame)
     self.lb_users = Listbox(left_toolbar)
     self.lb_users.config(height=30)
     self.lb_users.grid(row=0, column=0)
     scroll_bar = Scrollbar(left_toolbar)
     scroll_bar.config(command=self.lb_users.yview)
     scroll_bar.grid(row=0, column=1, sticky='ns')
     left_toolbar.propagate("false")
     left_toolbar.grid(column=0, row=0)
     self.lb_users.config(yscrollcommand=scroll_bar.set)
     self.debug_event("Left toolbar was generated")
예제 #23
0
파일: console.py 프로젝트: cr0sh/NaOH
	def __init__(self, runner):
		self.runner = runner
		self.messages = {}
		Screen.destroy()
		Screen.reinit()
		super().__init__()
		Screen.title("NaOH: PocketMine-MP Console")

		# GUI initialization

		fstframe = Frame(Screen.root)
		fstframe.grid(row=0, rowspan=1, columnspan=8)
		sndframe = Frame(Screen.root)
		sndframe.grid(row=0, rowspan=1, column=8, columnspan=2)
		self.scrollbar = Scrollbar(fstframe)
		self.listbox = Listbox(fstframe, yscrollcommand=self.scrollbar.set, width=120, height=25)
		self.listbox.grid(row=0, column=0, rowspan=1, columnspan=7, sticky='nswe')
		self.scrollbar.config(command=self.listbox.yview)
		self.scrollbar.grid(row=0, column=7, rowspan=1, sticky='nse')
		self.scrolllock = False
		Button(fstframe, text='나가기 (주의: 강제 종료됩니다)', command=self.runner.killAll).grid(row=1, column=0, sticky='nwse')
		self.slbutton = Button(fstframe, text='ScrollLock Off', command=self.togglesl)
		self.slbutton.grid(row=1, column=1, sticky='new')
		Label(fstframe, text='명령어: /', justify='right').grid(row=1, column=2)
		self.cmdentry = Entry(fstframe)
		self.cmdentry.bind('<Return>', self.put_cmd)
		self.cmdentry.grid(row=1, column=3, columnspan=5, sticky='nwe')
		fstframe.rowconfigure(1, weight=1)
		fstframe.columnconfigure(3, weight=1)
		fstframe.columnconfigure(4, weight=20)
		sndframe.rowconfigure(0, weight=1)
		Button(sndframe, text='서버 상태', command=lambda: statusScreen(self)).grid(row=0, sticky='n')
		Button(sndframe, text='설정 편집', command=lambda: propertiesScreen(self.runner.workdir + sep + 'server.properties')).grid(row=1, sticky='n')
		Button(sndframe, text='덤프 삭제', command=self.removeDumps).grid(row=2, sticky='n')
		self.cmdentry.focus()
		Screen.root.focus_force()

		# GUI initialization done

		self.thread = threading.Thread(target=lambda: asyncStream(self)).start()
		Screen.root.protocol("WM_DELETE_WINDOW", self.runner.killAll)
		Screen.root.mainloop()
		try:
			Screen.root.destroy()
		except:
			self.runner.killAll()
예제 #24
0
파일: lab3.py 프로젝트: zmeiko/pythonImage
    def createWidgets(self):
        canvas = CanvasImage(640, 480)
        self.img = canvas.draw(Makaronina(40, 200, 0, 0))
        self.photo1 = ImageTk.PhotoImage(self.img)
        self.label1 = Label(self, image=self.photo1)
        self.label1.grid(row=0, column=0)

        frame = Frame(self)
        frame.grid(row=1, column=0)
        rotateRight = Button(frame, text="Rotate right", command=self.rotateRight)
        rotateRight.grid(row=1, column=1)
        rotateLeft = Button(frame, text="Rotate left", command=self.rotateLeft)
        rotateLeft.grid(row=1, column=0)

        rotateUp = Button(frame, text="Rotate up", command=self.rotateUp)
        rotateUp.grid(row=2, column=1)
        rotateDown = Button(frame, text="Rotate down", command=self.rotateDown)
        rotateDown.grid(row=2, column=0)
예제 #25
0
 def __init__(self):
     Tk.__init__(self)
     self.minsize(200, 250)
     self.result = None
     self._model_name = ''
     self._icon_name = ''
     self.title("Viewer generator")
     self.grid_columnconfigure(0, weight=0)
     self.grid_columnconfigure(1, weight=1)
     self.grid_rowconfigure(0, weight=0)
     self.grid_rowconfigure(1, weight=1)
     self.resizable(True, True)
     Label(self, text='Model').grid(row=0, column=0, sticky=(N, E))
     self.models = ttk.Combobox(
         self, textvariable=StringVar(), state='readonly')
     self.models.grid(row=0, column=1, sticky=(N, W, E, S), padx=3, pady=3)
     mainframe = Frame(self, bd=1, relief=SUNKEN)
     mainframe.grid(
         row=1, column=0, columnspan=2, sticky=(N, S, E, W), padx=3, pady=3)
     current_row = 0
     current_col = 0
     self.check = []
     for value in ('add', 'list', 'edit', 'search', 'modify', 'listing', 'show', 'label', 'delete', 'print'):
         chkbtn_val = IntVar()
         chkbtn = Checkbutton(mainframe, text=value, variable=chkbtn_val)
         chkbtn.grid(
             row=current_row, column=current_col, sticky=W, padx=3, pady=3)
         self.check.append((value, chkbtn_val))
         current_col += 1
         if current_col == 2:
             current_col = 0
             current_row += 1
     Label(mainframe, text='Icon').grid(
         row=(current_row + 1), column=0, columnspan=2, sticky=(N, W, E, S), padx=3)
     self.icons = ttk.Combobox(
         mainframe, textvariable=StringVar(), state='readonly')
     self.icons.grid(
         row=(current_row + 2), column=0, columnspan=2, sticky=(N, W, E, S), padx=3)
     btnframe = Frame(self, bd=1)
     btnframe.grid(row=2, column=0, columnspan=2)
     Button(btnframe, text="OK", width=10, command=self.cmd_ok).grid(
         row=1, column=0, sticky=(N, S, E, W), padx=5, pady=3)
     Button(btnframe, text="Cancel", width=10, command=self.cmd_cancel).grid(
         row=1, column=1, sticky=(N, S, E, W), padx=5, pady=3)
예제 #26
0
    def init_grid(self):
        background = Frame(self, bg=c.BACKGROUND_COLOR_GAME,
                           width=c.SIZE, height=c.SIZE)
        background.grid()

        for i in range(c.GRID_LEN):
            grid_row = []
            for j in range(c.GRID_LEN):
                cell = Frame(background, bg=c.BACKGROUND_COLOR_CELL_EMPTY,
                             width=c.SIZE / c.GRID_LEN,
                             height=c.SIZE / c.GRID_LEN)
                cell.grid(row=i, column=j, padx=c.GRID_PADDING,
                          pady=c.GRID_PADDING)
                t = Label(master=cell, text="",
                          bg=c.BACKGROUND_COLOR_CELL_EMPTY,
                          justify=CENTER, font=c.FONT, width=5, height=2)
                t.grid()
                grid_row.append(t)

            self.grid_cells.append(grid_row)
예제 #27
0
    def createContent(self):
    # Top Panel: ---------------------------------
        pnlTop = Frame(self)
        pnlTop.pack(side="top", fill="both", pady=10, padx=10)
        self.btnDB = Button(pnlTop, text=_("Open Data Base..."), command=lambda cmd='OPEN': self.onCommand(cmd))
        self.btnDB.grid(row=1, column=2, padx=5)

    # Query Panel: -----------------------------------
        self.pnlQuery = Frame(self)
        self.pnlQuery.pack(side="right", fill="both", expand=True, padx=10)
        #-- SQL Panel: 
        pnlSQL = Frame(self.pnlQuery)
        pnlSQL.pack(side="top", fill="both")
        Label(pnlSQL, text = "SQL:").grid(row=1, column=1, padx=5)
        self.txtSQL = TextSQL(pnlSQL, height=10, width = 60)
        self.txtSQL.grid(row=1, column=2, padx=5, pady=10)
        Button(pnlSQL, text = _("Run"), command=lambda cmd='RUN': self.onCommand(cmd)).grid(row=1, column=3, padx=5)
        #-- Buttons Panel
        pnlBtns = Frame(pnlSQL)
        pnlBtns.grid(row=2, column=2)
        Button(pnlBtns, text='INSERT', width = 12, command=lambda cmd='QUERY',query='INSERT': self.onCommand(cmd,query=query)).grid(row=1, column=1)
        Button(pnlBtns, text='SELECT', width = 12, command=lambda cmd='QUERY',query='SELECT': self.onCommand(cmd,query=query)).grid(row=1, column=2)
        Button(pnlBtns, text='UPDATE', width = 12, command=lambda cmd='QUERY',query='UPDATE': self.onCommand(cmd,query=query)).grid(row=1, column=3)
        Button(pnlBtns, text='DELETE', width = 12, command=lambda cmd='QUERY',query='DELETE': self.onCommand(cmd,query=query)).grid(row=1, column=4)        
        #-- Result Panel:
        self.pnlResult = Frame(self.pnlQuery)
        self.pnlResult.pack(side="top", fill="both", expand=True, pady=10, padx=10)
        self.resultGrid = TextResult(self.pnlResult)
        self.resultGrid.pack(side="top", fill="both", expand=True)
                
    #Table List Panel: ---------------------------------------
        self.pnlTables = Frame(self)
        self.pnlTables.pack(side="left", fill="both", pady=10, padx=10)
        #---Tables Buttons Panel: 
        self.pnlTableList = Frame(self.pnlTables)
        self.pnlTableList.pack(side="top", fill="both", pady=10)
        #---Panel Nueva: Button
        pnlNewTable = Frame(self.pnlTables)
        pnlNewTable.pack(side="bottom", pady=10, padx=10)
        Button(pnlNewTable, text=_("New Table"), command=lambda cmd='QUERY',query='CREATE': self.onCommand(cmd,query=query,table='<table>')).grid(row=1, column=2, padx=5)
예제 #28
0
    def create_widgets(self):

        self.status_text = StringVar()
        self.status_text.set("Not Started")

        self.grid()

        for r in range(6):
            self.rowconfigure(r, weight=1)    
        for c in range(2):
            self.columnconfigure(c, weight=1)
            #Button(self, text="Button {0}".format(c)).grid(row=6,column=c,sticky=E+W)

        frame1 = Frame(self) #, bg="red"
        frame1.grid(row = 0, column = 0, rowspan = 6, columnspan = 1, sticky = W+E+N+S)


        title_label = ttk.Label(frame1, text=self.title, font=self.TITLE_FONT)
        title_label.pack(fill=BOTH, padx=25, pady=20)

        for input_model in self.input_models:
            input_view = FileInputView(frame1, input_model)
            input_view.pack(fill=BOTH)
            input_model.location_text.trace("w", self.check_processing_possible)

        process_button_style = ttk.Style()
        process_button_style.configure("Bold.TButton", font = ('Sans','20'))

        self.process_button = ttk.Button(frame1, text="PROCESS", width=20, style="Bold.TButton", state='disabled', command=self.start_processing)
        self.process_button.pack(side=BOTTOM, padx=5, pady=50)
        
        status_view = Frame(self, bg="white")
        status_view.grid(row = 3, column = 1, rowspan = 3, columnspan = 1, sticky = W+E+N+S)

        status_label = Label(status_view, text="Status: ", font=self.TITLE_FONT, bg="white")
        status_label.pack(side=LEFT, padx=5, pady=5)

        current_status_label = Label(status_view, textvariable=self.status_text, bg="white", font=self.STATUS_FONT)
        current_status_label.pack(side=LEFT, padx=5, pady=5)
예제 #29
0
    def showPlotTools(self):        
        
        
        f2= Frame(self.selectPlotFrame, relief=FLAT,bg='#FADC46')
        f2.grid(row=1,column=0,sticky=N+S+E+W,padx=10,pady =10)
        
        b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1))
        b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5)

        b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2))
        b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5)
        
        b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3))
        b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5)
        
        b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4))
        b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5)

        b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5))
        b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5)

        b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6))
        b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5)
        
        
    
        b1.config(state=EguanaModel().machine.plot3DKButtonState)
        b2.config(state=EguanaModel().machine.plot3DDstButtonState)
        b3.config(state=EguanaModel().machine.plot3DDpButtonState)
        b4.config(state=EguanaModel().machine.plot2DKButtonState)
        b5.config(state=EguanaModel().machine.plot2DDstButtonState)
        b6.config(state=EguanaModel().machine.plot2DDpButtonState)

        f2.columnconfigure(0, weight=1)
        f2.columnconfigure(1, weight=1)
        f2.columnconfigure(2, weight=1)

        f2.rowconfigure(0, weight=1)
        f2.rowconfigure(1, weight=1)
예제 #30
0
def openBL3Hotfixfile():
    def open_file():
        """Open a file for editing."""
        filepath = askopenfilename(filetypes=[("BL3HotFix File",
                                               "*.bl3hotfix")])
        if not filepath:
            return
        txt_edit.delete(1.0, END)
        with open(filepath, "r") as input_file:
            text = input_file.read()
            txt_edit.insert(END, text)
        window.title(f"Text Editor Application - {filepath}")

    def save_file():
        """Save the current file as a new file."""
        filepath = asksaveasfilename(
            defaultextension="txt",
            filetypes=[("BL3HotFix File", "*.bl3hotfix")],
        )
        if not filepath:
            return
        with open(filepath, "w") as output_file:
            text = txt_edit.get(1.0, END)
            output_file.write(text)
        window.title(f"Text Editor Application - {filepath}")

    def find():
        i = 0
        content_list = []
        txt_edit.tag_remove('found', '1.0', END)
        s = Find_String.get()
        hold = txt_edit.get("1.0", "end")
        content_list = hold.split("\n")

        if len(Search_List) > 0:
            Search_List.clear(
            )  # Clears out the list so we don't geta data contamination
        while i < len(content_list):
            if s in content_list[i]:
                Search_List.append(content_list[i])
            i += 1
        ListBoxWindow(5)

    window = Tk()
    window.title("Text Editor Application")
    window.rowconfigure(0, minsize=800, weight=1)
    window.columnconfigure(1, minsize=800, weight=1)

    fr_buttons = Frame(window, relief=RAISED, bd=2)
    txt_edit = Text(window)

    btn_open = Button(fr_buttons, text="Open", command=open_file)
    btn_save = Button(fr_buttons, text="Save As...", command=save_file)
    Find_Text_Button = Button(fr_buttons, text='Find', command=find)
    Find_String = Entry(fr_buttons)

    btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
    btn_save.grid(row=1, column=0, sticky="ew", padx=5)
    Find_String.grid(row=2, column=0, sticky="ew", padx=5)
    Find_Text_Button.grid(row=3, column=0, sticky="ew", padx=5)

    fr_buttons.grid(row=0, column=0, sticky="ns")
    txt_edit.grid(row=0, column=1, sticky="nsew")

    window.mainloop()
예제 #31
0
"""Right click context menu.
   Stand-alone example from Tk Assistant.
   stevepython.wordpress.com"""

from tkinter import Frame, Menu, Tk

root = Tk()
root.title('Right Click Menu example')

main_frame = Frame(root, width=250, height=250, bg='green')
main_frame.grid()


def paste():
    """Called when Paste selected from right click menu."""
    print('Paste selected')


def copy():
    """Called when Copy selected from right click menu."""
    print('Copy selected')


def popup(event):
    """On right click display popup menu at mouse position."""
    rc_menu.post(event.x_root, event.y_root)


# Bind mouse right click to frame.
main_frame.bind('<Button-3>', popup)
    def diffie_hellman_page():
        global g_number, n_number, alice_number, bob_number, g_number_error, n_number_error, alice_number_error, bob_number_error, alice_key, bob_key

        alice_number = StringVar(mainframe)
        bob_number = StringVar(mainframe)
        g_number = StringVar(mainframe)
        n_number = StringVar(mainframe)

        clear_screen(mainframe)
        # ? Title
        Label(mainframe,
              text="Diffie Hellman Key Exchange",
              font=h1_font,
              bg=main_colour).grid(row=0, column=0, columnspan=5)
        # ?
        # ? Alice Frame
        alice_frame = Frame(mainframe, bg=main_colour)
        alice_frame.grid(row=1, column=0, rowspan=3)
        Label(alice_frame, text="Alice", font=h2_font,
              bg=main_colour).grid(row=0, column=0, columnspan=2)
        Label(alice_frame,
              text="Any random number:",
              font=h3_font,
              bg=main_colour).grid(row=1, column=0)
        Entry(alice_frame,
              width=10,
              font=h3_font,
              relief="solid",
              textvariable=alice_number).grid(row=1, column=1)
        alice_key = Label(alice_frame,
                          width=box_width,
                          font=h3_font,
                          bg=main_colour,
                          wraplength=350)
        alice_key.grid(row=2, column=0, columnspan=2, pady=(10, 0))

        # ? Bob Frame
        bob_frame = Frame(mainframe, bg=main_colour)
        bob_frame.grid(row=1, column=3, rowspan=3)
        Label(bob_frame, text="Bob", font=h2_font,
              bg=main_colour).grid(row=0, column=0, columnspan=2)
        Label(bob_frame,
              text="Any random number:",
              font=h3_font,
              bg=main_colour).grid(row=1, column=0)
        Entry(bob_frame,
              width=10,
              font=h3_font,
              relief="solid",
              textvariable=bob_number).grid(row=1, column=1)
        bob_key = Label(bob_frame,
                        width=box_width,
                        font=h3_font,
                        bg=main_colour,
                        wraplength=350)
        bob_key.grid(row=2, column=0, columnspan=2, pady=(10, 0))

        # ? Shared Number Frame
        shared_number_frame = Frame(mainframe, bg=main_colour)
        shared_number_frame.grid(row=1, column=1, padx=30, pady=20)
        Label(shared_number_frame,
              text="G (any prime number):",
              font=h3_font,
              bg=main_colour).grid(row=0, column=0)
        Entry(shared_number_frame,
              width=8,
              font=h3_font,
              relief="solid",
              textvariable=g_number).grid(row=0, column=1)
        Label(shared_number_frame,
              text="N (any prime number):",
              font=h3_font,
              bg=main_colour).grid(row=1, column=0)
        Entry(shared_number_frame,
              width=8,
              font=h3_font,
              relief="solid",
              textvariable=n_number).grid(row=1, column=1)

        # ? Button Frame
        button_frame = Frame(mainframe, bg=main_colour)
        button_frame.grid(row=2, column=1, pady=(10, 0))
        Button(button_frame,
               text="Generate Key",
               font=(font_family, 12),
               bg=button_colour,
               command=Diffie_hellman.generate_key).grid(row=0, column=0)
        # ? Error Frame
        error_frame = Frame(mainframe, bg=main_colour)
        error_frame.grid(row=3, column=0, columnspan=5)
        g_number_error = Label(error_frame)
        n_number_error = Label(error_frame)
        alice_number_error = Label(error_frame)
        bob_number_error = Label(error_frame)
        list_of_label_error = [
            g_number_error, n_number_error, alice_number_error,
            bob_number_error
        ]
        i = 0
        for label_error in list_of_label_error:
            label_error.config(font=error_font,
                               fg="red",
                               background=main_colour)
            label_error.grid(row=i, column=0)
            i += 1
예제 #33
0
l1 = Label(bottom_frame, textvariable=g_units, anchor=W)
l1.grid(row=1, column=2)

###########################################################################
# List of GIVEN prefixes
prefix_list1_frame = Frame(bottom_frame)
prefix_list1 = Listbox(prefix_list1_frame, height=8, width=8)
prefix_list1.pack(side=LEFT, fill=Y)

# Scroll bar for GIVEN prefixes
prefix_sb1 = Scrollbar(prefix_list1_frame)
prefix_sb1.pack(side=RIGHT, fill=Y)

prefix_list1.configure(yscrollcommand=prefix_sb1.set)
prefix_sb1.configure(command=prefix_list1.yview)
prefix_list1_frame.grid(row=1, column=3, rowspan=2, columnspan=3)

# List of GIVEN units
list1_frame = Frame(bottom_frame)
units_list1 = Listbox(list1_frame, height=8, width=8)
units_list1.pack(side=LEFT, fill=Y)

# Scroll bar for GIVEN units
units_sb1 = Scrollbar(list1_frame)
units_sb1.pack(side=RIGHT, fill=Y)

units_list1.configure(yscrollcommand=units_sb1.set)
units_sb1.configure(command=units_list1.yview)
list1_frame.grid(row=1, column=6, rowspan=8, columnspan=3)

# Inserts a frame in the middle of the bottom frame to allow an arrow to be created to show the direction of conversion.
예제 #34
0
class MainGUI:
    def __init__(self,player_filename=""):
        
        
        ############### load data and save settings
        self.save_on = True
        
        if not player_filename:
            player_filename = "data/character_template.json"
            self.save_on = False
        
        self.player_filename = player_filename
        
        with open(player_filename, 'r') as f:
            self.playerdata = json.load(f)
            
        self.player_class_data = data["classes"][self.playerdata["class"]]
        
        
            ##########
        
        self.root = Tk()
        
        
        

        
        
        ### variables
        
        self.levelvar = IntVar()
        self.levelvar.set(self.playerdata["level"])
        
        self.namevar = StringVar()
        self.namevar.set(self.playerdata["name"])
        
        self.goldvar = IntVar()
        self.goldvar.set(self.playerdata["gold"])
        
        self.background_text = self.playerdata["background"]
        
        self.journal_text = self.playerdata["journal"]
        
        ##############################
        #add widgets
        self.GUIMenu()
        
        self.GUIHeader()
        
        self.GUIBody()
        
        
        
        ##############################
        
        
        ### configure root
        self.root.grid_rowconfigure(0, weight=0)
        self.root.grid_rowconfigure(1, weight=1,minsize=400)
        self.root.grid_columnconfigure(0, weight=1,minsize=400)
        
        
        self.root.title("RPG Leveler")
        self.root.protocol("WM_DELETE_WINDOW", self.on_close)
        self.root.mainloop()
        
        
        
    ##############################
    #   Constructor functions    #
    ##############################
        
        
        
        ### add menu
    def GUIMenu(self):
        self.menubar = Menu(self.root)
        
        self.fileMenu = Menu(self.menubar, tearoff=0)
        self.fileMenu.add_command(label="Open", command=self.open_file)
        self.fileMenu.add_command(label="Save", command=self.save)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="Exit", command=self.root.quit)
        self.menubar.add_cascade(label="File", menu=self.fileMenu)
        
        self.spellMenu = Menu(self.menubar, tearoff=0)
        self.spellMenu.add_command(label="Add Spell", command=OpenGUI)
        self.spellMenu.add_command(label="Edit Spell", command=self.hello)
        self.menubar.add_cascade(label="Spells", menu=self.spellMenu)
        
        self.itemMenu = Menu(self.menubar, tearoff=0)
        self.itemMenu.add_command(label="Add Item", command=self.hello)
        self.itemMenu.add_command(label="Edit Item", command=self.hello)
        self.menubar.add_cascade(label="Items", menu=self.itemMenu)
        
        self.root.config(menu=self.menubar)
        
        
        
        
        
        
        
        ### add header
        
        
    def GUIHeader(self):
        
        self.header = Frame(self.root,pady=5)
        
        
        self.header_name = Label(self.header,text="Name: ")
        self.header_namevar = Label(self.header,textvariable=self.namevar)
        
        self.header_level = Label(self.header,text="Level: ")
        self.header_levelvar = Label(self.header,textvariable=self.levelvar)
        
        self.header_gold = Label(self.header,text="Gold: ")
        self.header_goldvar = Label(self.header,textvariable=self.goldvar)
        
        
        
        self.header.grid(row=0,column=0,sticky="NSEW")
        
        self.header_name.grid(row=0,column=0,sticky="NSEW")
        self.header_namevar.grid(row=0,column=1,sticky="NSEW")
        
        self.header_level.grid(row=0,column=3,sticky="NSEW")
        self.header_levelvar.grid(row=0,column=4,sticky="NSEW")
        
        self.header_gold.grid(row=0,column=6,sticky="NSEW")
        self.header_goldvar.grid(row=0,column=7,sticky="NSEW")
        
        
        
        ### configure header grid
        
        self.header.grid_columnconfigure(2,minsize=30,weight=2)
        self.header.grid_columnconfigure(5,minsize=30,weight=2)
        self.header.grid_columnconfigure(8,weight=5)
        
        
        
    def GUIBody(self):
        
        #notebook
        self.body = ttk.Notebook()
        
        self.tabAbilities = Frame(self.root)
        self.tabClass = Frame(self.root)
        self.tabSkills = Frame(self.root)
        self.tabItems = Frame(self.root)
        self.tabBackground = Frame(self.root)
        self.tabJournal = Frame(self.root)
        
        ###########################
        #add tabs
        self.GUIAbilitiesTab()
        self.GUIBackgroundTab()
        self.GUIClassTab()
        self.GUIItemsTab()
        self.GUIJournalTab()
        self.GUIOverviewTab()
        self.GUISkillsTab()
        #
        ###########################
        self.body.add(self.tabAbilities,text="Abilities")
        self.body.add(self.tabClass,text=self.player_class_data["tab_name"])
        self.body.add(self.tabSkills,text="Skills")
        self.body.add(self.tabItems,text="Items")
        self.body.add(self.tabBackground,text="Background")
        self.body.add(self.tabJournal,text="Journal")
        

        self.body.grid(row=1,column=0,sticky="NSEW")
     
     
     
        
    ##################################
    #            tabs                #
    ##################################
        
        

    def GUIBackgroundTab(self):
        self.background_box = Text(self.tabBackground,width=10,height=10,font="TkFixedFont",wrap=WORD)
        self.background_box.insert(END,self.background_text)
        self.background_box.grid(row=0,column=0,sticky="NSEW")
        self.tabBackground.grid_rowconfigure(0, weight=1)
        self.tabBackground.grid_columnconfigure(0, weight=1)


    

    def GUIJournalTab(self):
        self.journal_box = Text(self.tabJournal,width=10,height=10,font="TkFixedFont",wrap=WORD)
        self.journal_box.insert(END,self.journal_text)
        self.journal_box.grid(row=0,column=0,sticky="NSEW")
        self.tabJournal.grid_rowconfigure(0, weight=1)
        self.tabJournal.grid_columnconfigure(0, weight=1)
        
        
        
    def GUIAbilitiesTab(self):
        
        
        self.Attributes = {}
        self.i=0
        self.Abilities_pointsLeftvar = IntVar()
        self.Abilities_pointsLeftvar.set(self.playerdata["points"]["attributes"])
        
        #header
        self.tabAbilities_abil = Frame(self.tabAbilities,padx=10,pady=10)
        self.tabAbilities_pointsLeft = Label(self.tabAbilities,text="Points Left:")
        self.tabAbilities_pointsLeftvar = Label(self.tabAbilities,textvariable=self.Abilities_pointsLeftvar)
        
        
        
        #attributes
        for attribute in self.playerdata["stats"]["attributes"]:
                #print(attribute)
                self.Attributes[attribute] = {}
                self.Attributes[attribute]["value"] = IntVar()
                self.Attributes[attribute]["value"].set(self.playerdata["stats"]["attributes"][attribute])
                
                self.Attributes[attribute]["button+"] = Button(self.tabAbilities_abil,text="+",command=lambda attribute=attribute: self.change_attribute(attribute,1))
                self.Attributes[attribute]["button-"] = Button(self.tabAbilities_abil,text="-",command=lambda attribute=attribute: self.change_attribute(attribute,-1))
                self.Attributes[attribute]["valueLabel"] = Label(self.tabAbilities_abil,textvariable=self.Attributes[attribute]["value"],font=("Ariel", 25))
                self.Attributes[attribute]["atributeLabel"] = Label(self.tabAbilities_abil,text=attribute.upper()+" ",font=("Ariel", 25))
                self.Attributes[attribute]["spacerLabel"] = Label(self.tabAbilities_abil,text="",height=1)
                
                self.Attributes[attribute]["atributeLabel"].grid(row=self.i,column=0,sticky="NSEW",rowspan=2)
                self.Attributes[attribute]["button-"].grid(row=self.i+1,column=4,sticky="NSEW")
                self.Attributes[attribute]["valueLabel"].grid(row=self.i,column=2,sticky="NSEW",rowspan=2)
                self.Attributes[attribute]["button+"].grid(row=self.i,column=4,sticky="NSEW")
                self.Attributes[attribute]["spacerLabel"].grid(row=self.i+2,column=3,sticky="NSEW")
                
                self.i+=3
        
        self.tabAbilities_pointsLeftvar.grid(row=0,column=2)
        self.tabAbilities_pointsLeft.grid(row=0,column=1)
        self.tabAbilities_abil.grid(row=1,column=0)


        
    def GUISkillsTab(self):

        self.Skills = {}
        self.sk_x=0
        self.sk_y=0
        
        
        #attributes
        for skill in data["stats"]["skills"]:
            
            #print(skill)
            self.Skills[skill["name"]] = {}
            
            self.Skills[skill["name"]]["frame"] = Frame(self.tabSkills,relief="sunken",bd=1)
            
            self.Skills[skill["name"]]["isTrained"] = IntVar()
            self.Skills[skill["name"]]["isTrained"].set(self.playerdata["stats"]["skills"][skill["name"]])
            
            self.Skills[skill["name"]]["value"] = IntVar()
            self.Skills[skill["name"]]["value"].set((self.Attributes[skill["base"]]["value"].get()-10)//2+self.Skills[skill["name"]]["isTrained"].get()*2)
            
            #print (self.Skills[skill["name"]]["value"].get())
            
            self.Skills[skill["name"]]["check"] = Checkbutton(self.Skills[skill["name"]]["frame"],variable=self.Skills[skill["name"]]["isTrained"],state=DISABLED,command=lambda skill=skill: print(skill))
            self.Skills[skill["name"]]["valueLabel"] = Label(self.Skills[skill["name"]]["frame"],textvariable=self.Skills[skill["name"]]["value"],font=("Ariel", 12))
            self.Skills[skill["name"]]["atributeLabel"] = Label(self.Skills[skill["name"]]["frame"],text=skill["name"]+" ",font=("Ariel", 12))
            
            
            self.Skills[skill["name"]]["frame"].grid(row=self.sk_y,column=self.sk_x,sticky="we")
            
            self.Skills[skill["name"]]["check"].pack(side="left")
            self.Skills[skill["name"]]["atributeLabel"].pack(side="left")
            self.Skills[skill["name"]]["valueLabel"].pack(side="right")
            
            
            self.sk_x+=1
            if self.sk_x > 1:
                self.sk_y+=1
                self.sk_x=0
        


        ######## Items
    def GUIItemsTab(self):
        
        
        self.itemSFrame = FrameScrollbar(self.tabItems)
            
        self.itemid=0
        self.Items = []
        
        for item in self.playerdata["items"]:
            
            self.Items.append({})
            self.Items[self.itemid]["id"]=self.itemid
            self.Items[self.itemid]["frame"] = Frame(self.itemSFrame.frame,relief=RIDGE,bg="grey",padx=1,pady=1)
            self.Items[self.itemid]["button_delete"] = Button(self.Items[self.itemid]["frame"],text="X",fg="white",bg="red",command=lambda Itemid=self.itemid:delItem(Itemid))
            self.Items[self.itemid]["name"] = Entry(self.Items[self.itemid]["frame"])
            self.Items[self.itemid]["name"].insert(END, item["name"])
            self.Items[self.itemid]["description"] = Text(self.Items[self.itemid]["frame"],width=10,height=5,wrap=WORD)
            self.Items[self.itemid]["description"].insert(END,item["description"])
            
            self.Items[self.itemid]["name"].grid(row=0,column=0)
            self.Items[self.itemid]["button_delete"].grid(row=0,column=0,sticky="E")
            self.Items[self.itemid]["description"].grid(row=1,column=0,sticky="NSEW")
            self.Items[self.itemid]["frame"].grid(padx=10,pady=10,sticky="EW")
            
            self.Items[self.itemid]["frame"].grid_columnconfigure(0, weight=1)
            
            
            
            self.itemid+=1
            
        def addItem():
            item={}
            item["id"]=self.itemid
            item["frame"] = Frame(self.itemSFrame.frame,relief=RIDGE,bg="grey",padx=1,pady=1)
            item["button_delete"] = Button(item["frame"],text="X",fg="white",bg="red",command=lambda Itemid=self.itemid:delItem(Itemid))
            item["name"] = Entry(item["frame"])
            item["description"] = Text(item["frame"],width=10,height=5,wrap=WORD)
            item["name"].grid(row=0,column=0)
            item["button_delete"].grid(row=0,column=0,sticky="E")
            item["description"].grid(row=1,column=0,sticky="NSEW")
            item["frame"].grid(padx=20,pady=10,sticky="EW")
            item["frame"].grid_columnconfigure(0, weight=1)
            
            self.itemSFrame.frame.update_idletasks()
            self.itemSFrame.onCanvasConfigure(None)
            
            
            
            self.Items.append(item)
            
            self.itemid+=1
            
    
            
        def delItem(Itemid):
            item=""
            index=0
            for item in self.Items:
                if item["id"]==Itemid:
                    index=self.Items.index(item)
                    break
                else:
                    item=""
            if item:
                self.Items[index]["frame"].grid_remove()
                self.Items.remove(item)
                
            self.itemSFrame.frame.update_idletasks()
            self.itemSFrame.onCanvasConfigure(None)
        
        self.addItemButton = Button(self.itemSFrame.canvas_frame,text="+",bg="grey",command=addItem).place(rely=1.0, relx=0.0, x=5, y=-5, anchor="sw")
            
        ######## Class
    def GUIClassTab(self):
        pass

        ######## Overview
    def GUIOverviewTab(self):
        pass






        
        
        
        
        
        
        
    
    #######################################
    #            functions                #
    #######################################
        


    def hello(self):
        pass
    
    
    
    def change_attribute(self,attribute,amount):
        if amount>0:
            if self.Abilities_pointsLeftvar.get()>0:
                self.Attributes[attribute]["value"].set(self.Attributes[attribute]["value"].get()+amount)
                self.Abilities_pointsLeftvar.set(self.Abilities_pointsLeftvar.get()-1)
        else:
            if self.Attributes[attribute]["value"].get()>self.playerdata["stats"]["base_attributes"][attribute]:
                self.Attributes[attribute]["value"].set(self.Attributes[attribute]["value"].get()+amount)
                self.Abilities_pointsLeftvar.set(self.Abilities_pointsLeftvar.get()+1)
        self.updateSkills()
    
    
    def on_close(self):
        if self.save_on and messagebox.askyesno("RPG","Do you want to save changes?"):
            self.save()
        self.root.destroy()
    
    
    
    def save(self):
        if self.save_on:
            
            for attribute in self.playerdata["stats"]["attributes"]:
                self.playerdata["stats"]["attributes"][attribute] = self.Attributes[attribute]["value"].get()
                self.playerdata["items"]=[]
            for item in self.Items:
                ditem = {}
                ditem["name"]=item["name"].get()
                ditem["description"]=item["description"].get(1.0,END)[:-1]
                self.playerdata["items"].append(ditem)
            
            
            self.playerdata["level"] = self.levelvar.get()
            self.playerdata["name"] = self.namevar.get()
            self.playerdata["gold"] = self.goldvar.get() 
            self.playerdata["background"] = self.background_box.get(1.0,END)[:-1]
            self.playerdata["journal"] =  self.journal_box.get(1.0,END)[:-1]
            self.playerdata["points"]["attributes"] = self.Abilities_pointsLeftvar.get()
            
            print(self.playerdata)
            
            with open(self.player_filename, 'w') as player_file:
                json.dump(self.playerdata, player_file, indent=4)
        
    def updateSkills(self):
        for skill in data["stats"]["skills"]:
            self.Skills[skill["name"]]["value"].set((self.Attributes[skill["base"]]["value"].get()-10)//2+self.Skills[skill["name"]]["isTrained"].get()*2)
        
    def open_file(self):
        p_fn = openFileName()
        if p_fn:
            self.root.destroy()
            openGUI(p_fn)
예제 #35
0
class CrosstalkDropdown(Frame):
    def __init__(self, tab, style, dye_li):
        Frame.__init__(self, tab)
        self.tab = tab
        self.number = 3
        self.style = style
        self.dye_li = dye_li
        self.initUI()

    def initUI(self):
        self.frameTwo = Frame(self.tab)
        self.frameTwo.grid(row=0, column=0)

        self.canvas = Canvas(self.frameTwo)
        self.listFrame = Frame(self.canvas)

        self.initialize()
        self.put_text()
        self.divider()
        self.choice_algorithm()
        self.single_well_analysis()

    def initialize(self):
        # Dropdown Menu
        optionList = ['Dye']
        for dye in self.dye_li:
            for temp_sub in ['_L', '_H']:
                optionList.append(dye + temp_sub)
        self.entry_li = []
        for i in range(self.number):
            dropVar1 = StringVar()
            dropVar1.set('Dye')  # default choice
            dropMenu1 = ttk.OptionMenu(self.tab, dropVar1, *optionList)
            dropMenu1.config(width=13)
            dropMenu1.grid(column=1, row=i+2, padx=10)

            dropVar2 = StringVar()
            dropVar2.set('Dye')  # default choice
            dropMenu2 = ttk.OptionMenu(self.tab, dropVar2, *optionList)
            dropMenu2.config(width=13)
            dropMenu2.grid(column=3, row=i+2, padx=10)
            ct_drfu = ttk.Entry(self.tab, width=8)
            ct_drfu.insert(0, 0)
            ct_drfu.grid(row=i+2, column=4, padx=10)
            ct_thrd = ttk.Entry(self.tab, width=8)
            ct_thrd.insert(0, 0)
            ct_thrd.grid(row=i+2, column=5)
            self.entry_li.append([dropVar1, dropVar2, ct_drfu, ct_thrd])

    def divider(self):
        blank = Label(self.tab, text='', width=16)
        blank.grid(row=5, column=1, columnspan=2)
        ttk.Separator(self.tab, orient=HORIZONTAL).grid(row=6, columns=1,
                                                        columnspan=10,
                                                        sticky='we')
        blank = Label(self.tab, text='', width=16)
        blank.grid(row=11, column=1, columnspan=2)
        ttk.Separator(self.tab, orient=HORIZONTAL).grid(row=12, columns=1,
                                                        columnspan=10,
                                                        sticky='we')

    def put_text(self):
        label = Label(self.tab, text='CROSSTALK')
        label.grid(row=0, column=0)
        label = Label(self.tab, text='Target 1 (from)')
        label.grid(row=1, column=1)
        label = Label(self.tab, text='Target 2 (to)')
        label.grid(row=1, column=3)
        label = Label(self.tab, text='DRFU')
        label.grid(row=1, column=4)
        label = Label(self.tab, text='Ct Thrd')
        label.grid(row=1, column=5)
        for i in range(self.number):
            label = ttk.Label(self.tab, text=f'crosstalk {i+1}',
                              justify="left")
            label.grid(row=i+2, column=0)
            label = ttk.Label(self.tab, text='➜', justify='left')
            label.grid(row=i+2, column=2)

    def get_entry(self):
        return self.entry_li, self.algoritm_entry_li, self.singlewell_entry_li

    def product_selection(self):
        label = Label(self.tab, text='제품별 알고리즘')
        label.grid(row=10, column=0, columnspan=2)
        products = ['Defualt', 'Defualt', 'GI-V (cross-talk)', 'GI-BI (2-CR)',
                    'GI-P (Q670 PC)']
        product_choice = StringVar()
        product_choice.set('Default')  # default choice
        dropMenu1 = ttk.OptionMenu(self.tab, product_choice, *products)
        dropMenu1.config(width=18)
        dropMenu1.grid(column=2, row=10, padx=10, columnspan=2)
        return product_choice

    def _algorithm_dropdown(self, rw, col, txt):
        label = Label(self.tab, text=txt)
        label.grid(row=rw, column=col, columnspan=2)

        algorithm_li = ['Default (latest ver.)', 'Default (latest ver.)',
                        'Old ver.']
        algorithm_choice = StringVar()
        algorithm_choice.set('Default (latest ver.)')  # default choice
        dropMenu1 = ttk.OptionMenu(self.tab, algorithm_choice, *algorithm_li)
        dropMenu1.config(width=18)
        dropMenu1.grid(column=col+2, row=rw, padx=10, columnspan=2)

        sample_kind_li = ['All', 'All', 'PC only', 'Sample only']
        sample_choice = StringVar()
        sample_choice.set('All')
        dropMenu2 = ttk.OptionMenu(self.tab, sample_choice, *sample_kind_li)
        dropMenu2.config(width=18)
        dropMenu2.grid(column=col+4, row=rw, padx=10, columnspan=2)
        return [algorithm_choice, sample_choice]

    def choice_algorithm(self):
        label = Label(self.tab, text='Algorithm'.upper())
        label.grid(row=7, column=0)
        absd_corrector_switch = self._algorithm_dropdown(
            8, 0, '과도한 CR에 대한 보정')
        asymm_sigfit_switch = self._algorithm_dropdown(9, 0, 'Ct값 보정')
        product_choice = self.product_selection()
        self.algoritm_entry_li = [absd_corrector_switch, asymm_sigfit_switch,
                                  product_choice]

    def single_well_analysis(self):
        label = Label(self.tab, text='single well'.upper())
        label.grid(row=13, column=0)
        check_single = Checkbar(self.tab, ['On'], self.style)
        check_single.grid(row=13, column=1)

        label = Label(self.tab, text='Dye')
        label.grid(row=14, column=0)
        dye_choice = StringVar()
        dye_choice.set('Choose dye')  # default choice
        dye_options = ['Choose dye']
        dye_options.extend(self.dye_li)
        dropMenu1 = ttk.OptionMenu(self.tab, dye_choice, *dye_options)
        dropMenu1.config(width=14)
        dropMenu1.grid(column=1, row=14, padx=10, columnspan=2)

        label = Label(self.tab, text='Well')
        label.grid(row=14, column=3)
        well_entry = ttk.Entry(self.tab, width=8)
        well_entry.insert(0, '')
        well_entry.grid(row=14, column=4)
        self.singlewell_entry_li = [check_single.vars[0], dye_choice,
                                    well_entry]
예제 #36
0
def main(token):
    '''
    Main event loop, draw the image and text to tkinter window
    '''

    root = Tk()
    root.configure(bg="black", cursor="none")
    root.attributes('-fullscreen', True)

    f = Frame(root, bg="black", width=MONITOR_WIDTH, height=MONITOR_HEIGHT)
    f.grid(row=0, column=0, sticky="NW")
    f.grid_propagate(0)
    f.update()

    most_recent_song = ""
    while True:
        redraw = True

        time.sleep(5)
        current_song = get_current_playing(token)

        if current_song["name"] != most_recent_song:
            redraw = True
        else:
            redraw = False

        if redraw:
            artist = current_song["artist"]
            name = current_song["name"]
            most_recent_song = name
            hd_img = itunes_search(current_song["name"],
                                   current_song["artist"])

            if hd_img != None:
                pi = convert_image(hd_img)
            else:
                pi = convert_image(current_song["img_src"])

            img_x = MONITOR_WIDTH / 3
            img_y = MONITOR_HEIGHT / 2

            label = Label(f, image=pi, highlightthickness=0, bd=0)
            label.place(x=img_x, y=img_y, anchor="center")

            artist_label = Label(f,
                                 text=artist,
                                 bg="black",
                                 fg="white",
                                 font=("Courier New", 30))

            artist_x = MONITOR_WIDTH - (MONITOR_WIDTH / 5)
            artist_y = (MONITOR_HEIGHT / 2) - 50
            artist_label.place(x=artist_x, y=artist_y, anchor="center")

            song_label = Label(
                f,
                text=name,
                bg="black",
                fg="white",
                font=("Courier New", 50),
            )

            song_x = MONITOR_WIDTH - (MONITOR_WIDTH / 5)
            song_y = (MONITOR_HEIGHT / 2) + 50
            song_label.place(x=song_x, y=song_y, anchor="center")

            root.update()

            label.destroy()
            artist_label.destroy()
            song_label.destroy()
예제 #37
0
class CardAuthor(Frame):
    def __init__(self, parent, author: Author, clickable=False, on_click=None):
        super().__init__(master=parent)
        self.author = author
        self.clickable = clickable
        self.on_click = on_click

        self._init_components()

    def get_default_background(self):
        return WHITE

    def get_foreground(self):
        return BLACK

    def _init_components(self, ):
        """
          Khởi tạo các thành phần trên nút
        """
        icon_size = (BUTTON[1] + PADDING * 2) * 3

        self.config(background=self.get_default_background(), )

        self.icon_researcher = RBGAImage(ICON_RESEARCHER, size=icon_size)

        self.label_icon = Label(self, image=self.icon_researcher)
        self.label_icon.config(background=self.get_default_background(),
                               highlightthickness=0)

        self.frame_content = Frame(self)
        self.frame_content.config(background=self.get_default_background())

        self.label_name = Label(self.frame_content)
        self.label_name.config(
            text=self.author.name,
            font=TITLE_SCREEN,
            background=self.get_default_background(),
            foreground=self.get_foreground(),
            anchor="nw",
            justify="left",
            wraplengt=300
            # highlightthickness=BORDER_WITH,
            # highlightbackground=DARK_GREY,
        )

        text_similarity = None
        if (self.author.similarity is not None):
            text_similarity = "Similarity: %.2f" % self.author.similarity

        self.label_similarity = Label(self.frame_content)
        self.label_similarity.config(
            text=text_similarity,
            font=BUTTON,
            background=self.get_default_background(),
            foreground=self.get_foreground(),
            anchor="nw",
            justify="left"
            # highlightthickness=BORDER_WITH,
            # highlightbackground=DARK_GREY,
        )

        self.frame_status = Frame(self)
        self.frame_status.config(background=self.get_default_background())

        self.label_status_prediction = Label(self.frame_status)
        self.label_status_prediction.config(
            text="",
            font=BODY,
            background=self.get_default_background(),
            foreground=WHITE,
            anchor="nw",
            justify="left")

        self.label_status_acquaintance = Label(self.frame_status)
        self.label_status_acquaintance.config(
            text="",
            font=BODY,
            background=self.get_default_background(),
            foreground=WHITE,
            anchor="nw",
            justify="left")

        self._add_logic()
        self._add_animations()

    def _show_label_status_acquaintance(self, enable=False):
        if (enable == True):
            if (self.author.isAcquantaince is True):
                self.label_status_acquaintance.config(
                    text="Acquantaince",
                    background=DARK_BLUE,
                )
        else:
            self.label_status_acquaintance.config(
                text="",
                background=self.get_default_background(),
            )

    def _show_label_status_prediction(self, enable=False):
        if (enable == True):
            if (self.author.isCollaborated is True):
                self.label_status_prediction.config(
                    text="True-positive",
                    background=GREEN,
                )
            elif (self.author.isCollaborated is False):
                self.label_status_prediction.config(
                    text="False-negative",
                    background=RED,
                )
        else:
            self.label_status_prediction.config(
                text="",
                background=self.get_default_background(),
            )

    def show_valuation(self, enable=False):
        self._show_label_status_acquaintance(enable)
        self._show_label_status_prediction(enable)

    def _add_logic(self):
        if (self.clickable == True):
            self.bind("<Button-1>", self._on_click)
            self.label_similarity.bind("<Button-1>", self._on_click)
            self.label_icon.bind("<Button-1>", self._on_click)
            self.label_name.bind("<Button-1>", self._on_click)
            self.frame_content.bind("<Button-1>", self._on_click)

    def _on_enter(self, event, **kw):
        if (self.clickable == True):
            color = GREY
            self.config(background=color)
            self.label_similarity.config(background=color)
            self.label_icon.config(background=color)
            self.label_name.config(background=color)
            self.frame_content.config(background=color)
            self.frame_status.config(background=color)
            if (self.label_status_acquaintance['bg'] ==
                    self.get_default_background()):
                self.label_status_acquaintance.config(background=color)
            if (self.label_status_prediction['bg'] ==
                    self.get_default_background()):
                self.label_status_prediction.config(background=color)

    def _on_leave(self, event, **kw):
        if (self.clickable == True):
            color = self.get_default_background()
            self.config(background=color)
            self.label_similarity.config(background=color)
            self.label_icon.config(background=color)
            self.label_name.config(background=color)
            self.frame_content.config(background=color)
            self.frame_status.config(background=color)
            if (self.label_status_acquaintance['bg'] == GREY):
                self.label_status_acquaintance.config(background=color)
            if (self.label_status_prediction['bg'] == GREY):
                self.label_status_prediction.config(background=color)

    def _add_animations(self):
        if (self.clickable == True):
            self.bind("<Enter>", self._on_enter)
            self.bind("<Leave>", self._on_leave)

    def _on_click(self, event, **kw):
        if (self.on_click is not None):
            self.on_click(self.author)

    def show_components(self, ):
        """
          Khởi tạo các thành phần trên nút
        """
        colIdx_left = 0
        colIdx_label_icon = 1
        colIdx_content = 2
        colIdx_right = colIdx_content + 1

        rowIdx_header = 0
        rowIdx_frame_content = 1
        rowIdx_frame_status = 2
        rowIdx_footer = rowIdx_frame_status + 1

        rowIdx_name = 1
        rowIdx_similarity = 2
        rowIdx_works = 3

        colIdx_similarity = 0

        rowIdx_acquantaince = 0
        rowIdx_status_prediction = 0

        colIdx_status_prediction = 0
        colIdx_acquantaince = 1

        self.grid_columnconfigure(colIdx_left, weight=1)
        self.grid_columnconfigure(colIdx_right, weight=1)

        self.grid_rowconfigure(rowIdx_header, weight=1)
        self.grid_rowconfigure(rowIdx_footer, weight=1)

        grid_default = {
            "sticky": "news",
            "pady": (0, PADDING),
            "padx": (PADDING, PADDING),
        }

        # self.label_text.pack(fill="both", expand=1)
        self.label_icon.grid(row=rowIdx_frame_content,
                             column=colIdx_label_icon,
                             **grid_default)
        self.frame_content.grid(row=rowIdx_frame_content,
                                column=colIdx_content,
                                **grid_default)
        self.label_name.grid(row=rowIdx_name, column=0, **grid_default)
        self.label_similarity.grid(row=rowIdx_similarity,
                                   column=colIdx_similarity,
                                   **grid_default)
        self.frame_status.grid(row=rowIdx_frame_status,
                               column=colIdx_content,
                               **grid_default)
        self.label_status_acquaintance.grid(row=rowIdx_acquantaince,
                                            column=colIdx_acquantaince,
                                            **grid_default)
        self.label_status_prediction.grid(row=rowIdx_status_prediction,
                                          column=colIdx_status_prediction,
                                          **grid_default)
예제 #38
0
class MainWindow(Frame):
    __slots__ = (
        "_app",
        "_ctrl_frame",
        "_ctrl_new_button",
        "_master",
        "_puzzle_row_groups",
        "_puzzle_row_frames",
    )

    def __init__(self,
                 master: Optional[tkinter.Tk] = None,
                 *,
                 app: "Application") -> None:
        if master is None:
            self._master = tkinter.Tk()
        else:
            self._master = master
        super().__init__(self._master)
        self._app = app
        self._master.title(
            "Talos EvilSeed - randomizer full control configurator")
        self.grid()
        self._build_puzzle_rows()
        self._build_control_pane()

    def _build_puzzle_rows(self) -> None:
        self._puzzle_row_groups: List[List[PuzzleRow]] = []
        self._puzzle_row_frames: List[Frame] = []

        MATCHERS: Sequence[Callable[[str], bool]] = [
            lambda name:
            (name.startswith("A") or name.startswith("B")) and name != "ADev",
            lambda name:
            (name.startswith("C") or name.startswith("N")) or name == "ADev",
        ]

        for frame_idx, f_matcher in enumerate(MATCHERS):
            frame = Frame(self)
            frame.grid(row=0,
                       padx=20,
                       ipady=20,
                       column=frame_idx,
                       sticky=tkinter.N)
            self._puzzle_row_frames.append(frame)

            puzzle_rows = [
                PuzzleRow(
                    frame,
                    app=self._app,
                    level_name=level_name,
                    level=level,
                    row=i,
                ) for i, (
                    level_name,
                    level,
                ) in enumerate(sorted(list(schema.PUZZLES.items())))
                if f_matcher(level_name)
            ]

            self._puzzle_row_groups.append(puzzle_rows)

    def _build_control_pane(self) -> None:
        self._control_pane_frame = Frame(self)
        self._control_pane_frame.grid(
            row=1,
            column=0,
            columnspan=2,
            sticky=tkinter.S + tkinter.W + tkinter.E,
        )

        self._ctrl_new_button = Button(
            self._control_pane_frame,
            text="New seed",
        )
        self._ctrl_new_button.grid(column=0, row=0, ipadx=20, ipady=10)
예제 #39
0
    def checkEnc(self):
        if Functions().analyseEncryption(self.filesAddress) == True:
            self.displaySelectedFiles.config(text = "Files Can be Encrypted",bg = "light green" ,font=('calibri',12,'bold'))
            userIDFrame = Frame(self.root)
            self.root.update()
        
            askIDLable = Label(userIDFrame,text = " Enter Your Username:"******" Enter Your Password:"******" Confirm Password:    "******"Select only Unencrypted files ... !", bg = "red",font=('calibri',12,'bold'))
            self.root.update()
예제 #40
0
class Driver():
    """
        This class contains all the member funcions that are related with tkinter library
        so all the user interactable elements are defined here.
    """
    # def updateProgressBar(self,value):
    #     self.progressBar['value'] = value

    def getAddress(self):
        """
            "getAddress" function is used to fetch all the address of the selected files
            and diaplays the selected files inside a frame
        """
        self.filesAddress = Functions().getFilesAddress()
        self.displaySelectedFiles.config(text = "")
        self.root.update()
  
        displayFrame1 =Frame(self.root)
        for i in range(len(self.filesAddress)):
            Label(displayFrame1,text=self.filesAddress[i]).grid(column = 0, row = i+1)
            self.root.update()
        displayFrame1.grid(column = 0 , row = 3)


    def doEnc(self):
        if self.userPwd.get() == self.confirmUserPwd.get():
            pwdMatched = Label(self.confirmFrame,text="Password Matched",font=('calibri',8),bg='green')
            pwdMatched.grid(column = 0, row=0 )
            self.root.update()

            # Encrypt Files here and Delete the old file
            Functions().encryptFile(self.filesAddress,self.userName.get(),self.userPwd.get())
            print("Files Encrypted Syccessfully")
            displaySuccess= Label(self.confirmFrame,text='Encryption Successfull',font=('calibri',20,'bold'),bg='green',foreground='white')
            displaySuccess.grid(column = 0, row= 2)
            self.root.update()
    
        else:
            pwdMatched = Label(self.confirmFrame,text="Password Not Matched",font=('calibri',8),bg='red')
            pwdMatched.grid(column = 0, row=0 )
            self.root.update()

    def doDec(self):
        if Functions().verify(self.filesAddress,self.userName.get(),self.userPwd.get()) == True:
            pwdMatched = Label(self.confirmFrame,text="Password Matched",font=('calibri',8),bg='green')
            pwdMatched.grid(column = 0, row=0 )
            self.root.update()

            # Decrypt Files here and delete the old ones
            Functions().decryptFile(self.filesAddress,self.userName.get(),self.userPwd.get())
            # progressDisplay.config(text= str(percent) + "%",font= ("calibri",12,"bold"),bg='yellow')
            displaySuccess= Label(self.confirmFrame,text='Decryption Successfull',font=('calibri',20,'bold'),bg='green',foreground='white')
            displaySuccess.grid(column = 0, row= 2)
            
            print("Files Decrypted Successfully")
            self.root.update()

        else:
            pwdMatched = Label(self.confirmFrame,text="Incorrect Password",font=('calibri',8),bg='red')
            pwdMatched.grid(column = 0, row=0 )
            self.root.update()

        

    def checkEnc(self):
        if Functions().analyseEncryption(self.filesAddress) == True:
            self.displaySelectedFiles.config(text = "Files Can be Encrypted",bg = "light green" ,font=('calibri',12,'bold'))
            userIDFrame = Frame(self.root)
            self.root.update()
        
            askIDLable = Label(userIDFrame,text = " Enter Your Username:"******" Enter Your Password:"******" Confirm Password:    "******"Select only Unencrypted files ... !", bg = "red",font=('calibri',12,'bold'))
            self.root.update()


    def checkDec(self):
        if Functions().analyseDecryption(self.filesAddress) == True:
            self.displaySelectedFiles.config(text = "Files Can be Decrypted", bg = "light green",font=('calibri',12,'bold'))
            userIDFrame = Frame(self.root)
        
            askIDLable = Label(userIDFrame,text = " Enter Your Username:"******" Enter Your Password:"******"Select only Encrypted files ... !", bg = "red",font=('calibri',12,'bold'))
            self.root.update()

    def userInterface(self):
        self.root  = Tk()
        self.root.title('Uencryptor - File Encryptor')
        self.root.resizable(0,0)

        titleFrame = Frame(self.root)
        # contents in titleFrame 
        title = Label(titleFrame,text="Uencryptor",font = ('calibri',40,'bold'),padx=40,pady=5,bg='green',foreground='white')
        title.grid(column=0)
        subTitle = Label(titleFrame,text="Encrypt your personal files.",font=('calibir',10,'bold'),bg='light green',padx=103)
        subTitle.grid(column = 0, row = 1)
        titleFrame.grid(column =0,row =0)

        

        inputFrame = Frame(self.root)
        # contents to interact with user are here 
        selectFile = Label(inputFrame,text = "Select Files to Encrypt/Decrypt : ",pady=10,font=('calibri',12,'bold'))
        selectFile.grid(column =0 , row = 0)

        selectFileButton =  Button(inputFrame,text='Choose Files',command = self.getAddress)
        selectFileButton.grid(column =1 , row = 0)

        inputFrame.grid(column=0, row =1)




        displayFrame = Frame(self.root)
        # contents of display frame
        selectedFiles = Label(displayFrame,text = "Selected Files Are : ",font=('calibri',12,'bold'))
        selectedFiles.grid(column =0 , row = 0)
        blankLable = Label(displayFrame,pady = 5,text='                                                        ')
        blankLable.grid(column = 1 , row = 0)

        displayFrame.grid(column =0, row =2)

        # displayframe2 for message
        displayFrame2 = Frame(self.root)
        self.displaySelectedFiles = Label(displayFrame2,text='Selected files will be displayed here.')
        self.displaySelectedFiles.grid(column = 0, row =0 )
        displayFrame2.grid(column = 0, row = 4)

        buttonFrame = Frame(self.root)

        encryptButton = Button(buttonFrame,text='Verify Encryption',command= self.checkEnc)
        encryptButton.grid(column=0, row = 0)
        blankLable2 = Label(buttonFrame,pady = 5,text='                ')
        blankLable2.grid(column = 1 , row = 0)

        decryptButton = Button(buttonFrame,text='Verify Decryption',command= self.checkDec)
        decryptButton.grid(column=2,row=0)
        buttonFrame.grid(column = 0,row = 5)


        self.root.mainloop()
예제 #41
0
class WaltzGUI(lx.Lx200Commands):
    def __init__(self, master):
        """Class builds GUI to control Waltz Telescope.
           Uses Tkinter for GUI functionality.
           Inherits from lx200commands.Lx200Commands class.
           This class provides functionality to talk to serial connection 
           using the lx200 protocol.
        """
        
        super().__init__()
        
        self.master = master
        master.title("Waltz Control Panel")
       
        #Store CET and UCT
        self.CET = ''
        self.UTC = ''
        
        #Store if telescope is waiting for slew to finish
        self.waiting=True
        
        ## Building up GUI Widgets ##
        
        #Menubars
        menubar=Menu(self.master)
        
        #Connection menu
        connectionmenu = Menu(menubar, tearoff=0)
        connectionmenu.add_command(label="Open Connection", command=self.open_connection_buttonclick)
        connectionmenu.add_command(label="Close Connection", command=self.close_connection_buttonclick)
        menubar.add_cascade(label="Connection", menu=connectionmenu)
        
        #settings_menu
        settings_menu=Menu(menubar, tearoff=0)
        settings_menu.add_command(label="Enable buttons",command=self.stop_waiting)
        settings_menu.add_command(label="Toggle Precision",command=super().toggle_precision)
        menubar.add_cascade(label="Settings",menu=settings_menu)
        
        
        
        #Pointing_stars_menu
        pointing_stars_menu=Menu(menubar, tearoff=0)
        pointing_stars_menu.add_command(label="Pointing Star", command=self.save_pointing_star)
        menubar.add_cascade(label="Save as", menu= pointing_stars_menu)
        
        #Special_positions_menu
        special_positions_menu=Menu(menubar, tearoff=0)
        special_positions_menu.add_command(label="Slew to Primary Mirror Position",command=self.primary_mirror_pos_buttonclick)
        special_positions_menu.add_command(label="Slew to Secondary Mirror Position",command=self.secondary_mirror_pos_buttonclick)
        special_positions_menu.add_command(label="Slew to Park Position",command=self.park_telescope_buttonclick)
        menubar.add_cascade(label="Special Positions",menu=special_positions_menu)
        
        
        #Show menubar
        self.master.config(menu=menubar)
        
        #Output frame
        output_frame=Frame(master)
        output_frame.grid(row=0,columnspan=3)

        self.LST_label = Label(output_frame,
                               font=('arial', 15, 'bold'),
                               text="LST")
        self.LST_label.grid(row=0,column=0)
        
        self.LST_display = Label(output_frame,
                                 font=('arial', 20, 'bold'),
                                 bg='light green')
        self.LST_display.grid(row=0, column=1,padx=10, pady=10)
        
        self.local_time_label= Label(output_frame,
                              font=('arial', 15, 'bold'),
                              text='LT')
        self.local_time_label.grid(row=0, column=3)
        
        self.local_time_display = Label(output_frame,
                                 font=('arial', 20, 'bold'),
                                 bg='light green')
        self.local_time_display.grid(row=0, column=4,padx=10,pady=10)
        
        self.UTC_label= Label(output_frame,
                              font=('arial', 15, 'bold'),
                              text='UTC')
        self.UTC_label.grid(row=0, column=5)
        
        self.UTC_display = Label(output_frame,
                                 font=('arial', 20, 'bold'),
                                 bg='light green')
        self.UTC_display.grid(row=0, column=6,padx=10,pady=10)
        
        
        
        self.RA_label= Label(output_frame,
                             font=('arial', 15, 'bold'),
                             text= "RA")
        self.RA_label.grid(row=1, column =0)
        
        self.RA_display= Label(output_frame,
                               font=('arial', 20, 'bold'), 
                               bg='light green')
        self.RA_display.grid(row=1, column =1)
        
        self.DEC_label= Label(output_frame,
                              font=('arial', 15, 'bold'),
                              text= "DEC")
        self.DEC_label.grid(row=1, column =3)
        
        self.DEC_display= Label(output_frame,
                                font=('arial', 20, 'bold'),
                                bg='light green')
        self.DEC_display.grid(row=1, column =4)
        
        self.HA_label= Label(output_frame,
                              font=('arial', 15, 'bold'),
                              text= "HA")
        self.HA_label.grid(row=1, column =5)
        
        self.HA_display= Label(output_frame,
                                    font=('arial', 20, 'bold'),
                                    bg='light green')
        self.HA_display.grid(row=1, column=6)
        
        #Interchange_frame
        #To interchange W<->E buttons and N<->S
        self.interchange_frame=Frame(master)
        self.interchange_frame.grid(row=1, column=0,pady=10)
        #Define Variables
        self.inter_WE=IntVar()
        self.inter_NS=IntVar()
        self.inter_NS_checkbox=Checkbutton(self.interchange_frame,
                                           text='N <> S',
                                           font=('arial', 10, 'bold'),
                                           variable=self.inter_NS,
                                           command=self.interchange_north_south)
        self.inter_NS_checkbox.grid(row=0,column=0,sticky='w',pady=5)
        
        
        self.inter_WE_checkbox=Checkbutton(self.interchange_frame,
                                           text='W <> E',
                                           font=('arial', 10, 'bold'), 
                                           variable=self.inter_WE,
                                           command=self.interchange_west_east)
        self.inter_WE_checkbox.grid(row=1,column=0,sticky='w',pady=5)
        
        
        
        #Control frame
        self.control_frame=Frame(master)
        self.control_frame.grid(row=1,column=1,pady=10)


        self.south_button = Button(self.control_frame,
                                   text="S",
                                   font=('arial', 20, 'bold'),
                                   bg='LightGrey',
                                   height = 1, 
                                   width = 2)
        self.south_button.grid(row=0,column=1)
        
        self.west_button = Button(self.control_frame,
                                  text="W",
                                  font=('arial', 20, 'bold'),
                                  bg='LightGrey',
                                  height = 1,
                                  width = 2)
        self.west_button.grid(row=1,column=0)
        
        self.east_button = Button(self.control_frame,
                                  text="E",
                                  font=('arial', 20, 'bold'),
                                  bg='LightGrey',
                                  height = 1,
                                  width = 2)
        self.east_button.grid(row=1,column=2)
        
        
        self.north_button = Button(self.control_frame,
                                   text="N",
                                   font=('arial', 20, 'bold'),
                                   bg='LightGrey',
                                   height = 1,
                                   width = 2)
        self.north_button.grid(row=2,column=1)
        
        self.stop_button = Button(self.control_frame,
                                  text="STOP",
                                  font=('arial',20, 'bold'),
                                  fg='White',
                                  bg='Red',
                                  activeforeground='Red',
                                  activebackground='White',
                                  command=super().stop_at_current_pos)
        self.stop_button.grid(row=3,column=0, columnspan=3, pady=10)

        #Radiobutton frame
        self.radiobutton_frame=Frame(master)
        self.radiobutton_frame.grid(row=1,column=2,pady=10)
        
        
        radiobutton_parameters=[('Slew',0,self.set_speed_max),
                                ('Find',1, self.set_speed_find),
                                ('Center',2, self.set_speed_center),
                                ('Guide',3, self.set_speed_guide)]
        
        self.speed=StringVar()
        #Initialize speed to guiding speed
        self.speed.set('Guide')
        
        for keyword, position, execute in radiobutton_parameters:
            self.speed_radiobutton= Radiobutton(self.radiobutton_frame,
                                                text=keyword,
                                                variable=self.speed,
                                                value=keyword,
                                                command=execute,
                                                font=('arial', 10, 'bold'))
            self.speed_radiobutton.grid(row=position,column=0,sticky=W)
        
        #Options Frame
        self.options_frame=Frame(master)
        self.options_frame.grid(row=0,column=3,padx=20)
     
        self.sync_button = Button(self.options_frame,
                                       text="Synchronize \n with Target",
                                       font=('arial', 12, 'bold'),
                                       bg='LightGrey',
                                       command=self.sync_yes_no,
                                       state='disabled')
        self.sync_button.grid(row=0,column=0,padx=5)
        
        
        
        
        #Target Frame
        self.target_frame=LabelFrame(master,
                                text='Select Target (apparent position)',
                                font=('arial', 15))
        self.target_frame.grid(row=1,rowspan=1,column=3,padx=20)
        
        self.HIP_label = Label(self.target_frame,
                               font=('arial', 15),
                               text="Hipparcos")
        self.HIP_label.grid(row=0,column=0)
        
        self.HIP_entry= Entry(self.target_frame,
                              font=('arial', 15))
        self.HIP_entry.grid(row=0, column=1,pady=10)
        
        
        self.target_ra_label = Label(self.target_frame,
                                     font=('arial', 15),
                                     text="RA \n [hh mm ss]")
        self.target_ra_label.grid(row=1,column=0)
        
        self.target_ra_entry= Entry(self.target_frame,
                                    font=('arial', 15))
        self.target_ra_entry.grid(row=1, column=1,pady=10)

        
        self.target_dec_label = Label(self.target_frame,
                                      font=('arial', 15),
                                      text="""DEC \n [°° mm ss]""")
        self.target_dec_label.grid(row=2,column=0)
        
        self.target_dec_entry= Entry(self.target_frame,
                                     font=('arial', 15))
        self.target_dec_entry.grid(row=2, column=1,pady=10)
        
        self.target_time_label= Label(self.target_frame,
                                     font=('arial', 15),
                                     text=" Obs \n Time")
        self.target_time_label.grid(row=0,column=2,padx=10)
        
        self.target_time_display=Label(self.target_frame,
                                    font=('arial', 15),
                                    bg='red',
                                    width=10)
        self.target_time_display.grid(row=0,column=3,pady=10)
        
        self.target_alt_label = Label(self.target_frame,
                                     font=('arial', 15),
                                     text="ALT")
        self.target_alt_label.grid(row=1,column=2,padx=10)
        
        self.target_alt_display= Label(self.target_frame,
                                    font=('arial', 15),
                                    bg='red',
                                    width=10)
        self.target_alt_display.grid(row=1, column=3,pady=10)
        
        self.target_az_label = Label(self.target_frame,
                                     font=('arial', 15),
                                     text="AZ")
        self.target_az_label.grid(row=2,column=2,padx=10)
        
        self.target_az_display= Label(self.target_frame,
                                    font=('arial', 15),
                                    bg='red',
                                    width=10)
        self.target_az_display.grid(row=2, column=3,pady=10)
        
        self.slew_target_button = Button(self.target_frame,
                                         text="Slew to Target",
                                         font=('arial', 15),
                                         bg='LightGrey',
                                         state='disabled',
                                         command=self.slew_to_target_buttonclick)
        self.slew_target_button.grid(row=3,columnspan=4)
        
        #Plot Frame
        self.plot_frame=Frame(master)
        self.plot_frame.grid(row=2,columnspan=4)
        #Add instance variables to store the plot and the different axes,
        #and positions globally
        self.canvas=False
        self.ax1=False
        self.star_plot=False
        self.traj_plot=False
        self.pos_plot=False
        self.ax2=False
        
        #At first check if serial connection is open (also contains initial commands)
        self._respond_to_connection_state()
        
        #Message box for Warning
        caution=("CAUTION: THIS IS A FIRST ATTEMPT TO CONTROL THE WALTZ TELESCOPE.\n"+
                 "BAD INPUTS OR CRASHES OF THE PROGRAM COULD BE HARMFUL TO THE TELESCOPE.\n"+
                 "DO NOT USE THIS PROGRAM ALONE AND ALWAYS PREPARE FOR STOPING MOVEMENTS "+ 
                 "OF THE TELESCOPE VIA THE EMERGENCY STOPS IN THE DOME!")
        messagebox.showwarning("Warning",message=caution,parent=master)
    
    
    def close_connection_buttonclick(self):
        """ Closes the connection to serial and responds properly to it
        """
        #First check the connection state
        if self.connected==False:
            print('Connection already closed')
            return 0
        #Close serial connection
        super().close_connection()
        #Check if connection is realy closed
        #this will set self.connected=False
        #Respond to closed connection
        self._respond_to_connection_state()
        
        
    def open_connection_buttonclick(self):
        """ Closes the connection to serial and responds properly to it
        """
        #First check the connection state
        if self.connected==True:
            print('Connection already open')
            return 0
        #Open serial connection
        super().open_connection()
        #Respond to open connection
        self._respond_to_connection_state()
    
    
    def _start_commands(self):
        """ Contains all functions to be executed at start of program.
        """
        
        #Commands to be executed even without connection
        self.refresh_times()
        self.initialize_plot()
        
        #If connection is not open close program
        if not self.connected:
            return 0
        
        #Commands for initial settings
        self.set_speed_guide()
        #This is the StringVar defining which initial setting the speed Radiobuttons have
        self.speed.set('Guide')
        
        #Commands to be executed all the time (if connection is open)
        self.display_coordinates()
        self.refresh_target_alt_az_ha()
        
        #Check for format of coordinates and toggle automatically
        #We always want format DEC=dd mm ss
        if len(self.dec)==7:
            super().toggle_precision()
    def _respond_to_connection_state(self):
        """ Checks connection to serial port.
            Print Warning if not and closes program.
            Enables and binds all buttons if connection is set.
        """
        #If connection to Waltz is closed
        if not self.connected:
            #Disable all buttons
            self.disable_all_buttons()
            self.stop_button.config(state='disabled')
            #Message box if serial connection is not open
            caution=("Warning: No Connection to Waltz")
            messagebox.showwarning("Warning",message=caution,parent=self.master)
            #Start Commands 
            #(it will take care that only the ones that do not use the serial connection are executed)
            self._start_commands()
        if self.connected:
            #Enable all buttons
            self.enable_all_buttons()
            #Start Commands
            self._start_commands()
                    
    def refresh_times(self):
        """ Refreshs all times (LST, LT, UTC)
        
            Introduced to have only one function call in the background.
            Better to syn clocks
        """
        #Refresh individual times
        self.refresh_LST()
        self.refresh_local_time()
        self.refresh_UTC()
        
        #Also refresh hour_angle synced to times because it will change in the same pace
        super().calculate_hour_angle()
        self.HA_display.config(text=self.ha)
        #Calls itself all 200 ms
        self.master.after(200, self.refresh_times)
    
    def refresh_local_time(self):
        """ Displays the current Central Eruopean Time on CET_display.
            Calls itself all 200ms to refresh time.
        """
        
        # get the current local time from the PC
        local_time_now = time.strftime('%H:%M:%S')
        # if time string has changed, update it
        if local_time_now != self.CET:
            self.local_time = local_time_now
            self.local_time_display.config(text=self.local_time)
    
    def refresh_LST(self):
        """ Displays the current Local Sidereal Time on LST_display.
            Calls itself all 200ms to refresh time.
        """
        super().get_LST()
        self.LST_display.config(text=self.LST)
        
    def refresh_UTC(self):
        """ Displays the current Coordinated Universal Time on UTC_display.
            Calls itself all 200 ms to refresh time.
        """
        #Get current UTC from datetime
        UTC_now= datetime.datetime.utcnow()
        UTC_now=UTC_now.strftime("%H:%M:%S")
        #Check if UTC has changed since last call
        if UTC_now != self.UTC:
            #Save current UTC in self.UTC
            self.UTC = UTC_now
            #Display UTC
            self.UTC_display.config(text=self.UTC)
            
    def initialize_plot(self):
        """Refreshs Plot.
        """
        #Close all plots for safety reasons
        #plt.close('all')
        (fig,
         self.ax1) = plot_traj_limits_altaz_GUI(False,False,False,False)
        self.canvas = FigureCanvasTkAgg(fig, master = self.plot_frame)
        self.canvas._tkcanvas.grid(row=0,column=0)
        self.plot_current_pos()
        
    def plot_current_pos(self):
        """Overplots current position. Plot needs to already exist.
        """
        #First remove existing pos_plot (if it exists)
        if self.pos_plot:
            self.pos_plot.pop(0).remove()
        #Now add new pos_plot
        self.pos_plot=add_current_pos(self.ax1,self.ha_float,self.dec_float)
        self.canvas.draw()
        self.master.after(1000,self.plot_current_pos)
        
    def plot_star_and_traj(self):
        """Overplots star position and trajectory. Plot need to already exist.
        
           Will be called periodically with refresh_target_alt_az_ha.
        """
        #First remove existing star_plot/traj_plot (if they exists)
        if self.star_plot:
            self.star_plot.pop(0).remove()
            self.traj_plot.pop(0).remove()
            self.ax2.remove()
        if not self.target_ra_float or not self.target_dec_float:
            return 0
        #Now add new_star_plot
        (self.star_plot,
         self.traj_plot,
         self.ax2)=add_star_and_traj(self.ax1,
                                     self.target_ha_float,
                                     self.target_dec_float)
        self.canvas.draw()
        
        
    
    def display_coordinates(self):
        """ Displays Right ascension and Declination.
            
            Hour angle will be displayed synced to times.
            It should change at the same rate as LST.
            Look at refresh_times()
        """
        
        #If connection is not open close program
        if not self.connected:
            return 0
        
        self.get_coordinates()
        self.RA_display.config(text=self.ra)
        self.DEC_display.config(text=self.dec)
        if not self.connected:
            self._respond_to_connection_state()

        self.master.after(500,self.display_coordinates)
        
    def refresh_target_alt_az_ha(self,call_itself=True):
        """ Executes Lx200Commands.calculate_target_alt_az_ha every 500 ms.
        """
        #Calculate target alt and az and obs time
        super().calculate_target_alt_az_ha()
        #Display alt, az and obs time
        self.target_alt_display.config(text=self.target_alt)
        self.target_az_display.config(text=self.target_az)
        self.target_time_display.config(text=self.target_obs_time)
        #Check coordinates to reply with correct colors
        if check_coordinates(self.target_alt_float,
                                    self.target_az_float):
            self.display_alt_az('light green')
        else:
            self.display_alt_az('red')
        #Update the plot
        self.plot_star_and_traj()
        #Optionally call itself
        if call_itself:
            self.master.after(5000,self.refresh_target_alt_az_ha)
        
    def interchange_west_east(self):
        """Interchanges West and East Buttons.
        """
        #self.inter_WE.get() will return 1 if box is checked and 0 if not
        if self.inter_WE.get():
            #Grid Positions if checkbutton is checked
            self.west_button.grid(row=1,column=2)
            self.east_button.grid(row=1,column=0)  
        if not self.inter_WE.get():
            #Grid Position in default state
            self.west_button.grid(row=1,column=0)
            self.east_button.grid(row=1,column=2)
            
    def interchange_north_south(self):
        """Interchanges North and South Buttons.
        """
        #self.inter_WE.get() will return 1 if box is checked and 0 if not
        if self.inter_NS.get():
            #Grid Positions if checkbutton is checked
            self.south_button.grid(row=2,column=1)
            self.north_button.grid(row=0,column=1)  
        if not self.inter_NS.get():
            #Grid Position in default state
            self.south_button.grid(row=0,column=1)
            self.north_button.grid(row=2,column=1)
            
    def start_move_west_buttonclick(self, event):
        """ Sends move west LX200 command to serial connection
        """
        super().start_move_west()
        
    def stop_move_west_buttonclick(self, event):
        """ Sends stop move west LX200 command to serial connection
        """
        super().stop_move_west()
        
    def start_move_north_buttonclick(self, event):
        super().start_move_north()
        
    def stop_move_north_buttonclick(self, event):
        super().stop_move_north()
        
    def start_move_south_buttonclick(self, event):
        super().start_move_south()
        
    def stop_move_south_buttonclick(self, event):
        super().stop_move_south()
        
    def start_move_east_buttonclick(self, event):
        super().start_move_east()
        
    def stop_move_east_buttonclick(self, event):
        super().stop_move_east()
        
    def slew_to_target_buttonclick(self):
        """Slews to target.
           Target must be set before via set_target_dec_from_string and set_target_ra_from_string
        """
        super().set_target_coordinates()
        #Slew to target and wait for slew to finish
        super().slew_to_target()
        self.wait_for_slew_finish()
        
        #After slewing (and if something went wrong):
        #Set all valid_target entries to 0 (controller won't let you slew to
        #the same coordinates twice
        self.valid_target=[0,0]
        self.slew_target_button.config(state='disabled')
    
    #def continue_slew(self,initial_target_ra, initial_target_dec):
        """ Continues slewing after possible initial slew to medium position.
            Performs slewing if no slew to medium position is necessary.
        """
        #Check if slew is finished. Default Value of slew_done=True,
        #so it will also be True if no slew to medium position was necessary.)
        #if self.slew_done:
            #Set the initial target coordinates as normal target coordinates again
            #super().set_target_ra_from_string(initial_target_ra)
            #super().set_target_dec_from_string(initial_target_dec)
            #Slew to target
            #super().slew_to_target()
            #Wait for the slew to finish (disables all buttons etc.)
            #self.wait_for_slew_finish()
        #else:
            #If previous slew is not finished the funcion will call itself every second.
            #self.master.after(1000, self.continue_slew, initial_target_ra, initial_target_dec)
        
    def park_telescope_buttonclick(self,counter=1,park=True):
        """Parks telescope and waits for slew to finish.
           
           counter counts if parking is executed the first or 
           second time.
           park specifies if controller gets a parking command 
           or if the function just waits until first slew has finished.
        """
        #We need to call park telescope twice 
        #because the tracking will change RA while DEC is still adjusting
        #Park telescope for the first time
        if counter==1:
            #If parking is activated
            if park:
                print('Slew to Park Position the first time')
                #Slew telescope to parking position
                super().park_telescope()
                self.refresh_target_alt_az_ha(call_itself=False)
            #Start waiting: Call wait_for_slew_finish with call_itself=False
            #So the funtion will just check if slew has finished
            if not self.wait_for_slew_finish(call_itself=False):
                #If slew has not yet finished
                print('Waiting for First Parking to finish')
                #Call the park funtion after 1 sec with counter=1 and slew=False
                #So it will be in counter=1 loop but will not send 
                #a park command to the controller
                self.master.after(1000,self.park_telescope_buttonclick,
                                  1,False)
                return 0
            else:
                #If slewing has finished
                #Disable all buttons (need because it will otherwise wait
                #for one second until it disables again)
                self.disable_all_buttons()
                print('Finished First Parking')
                #Call park function again after 1 second but enter counter=2 loop
                #Also activate parking again with park=True
                #Useful to wait one second as safetiy that slewing has stopped
                self.master.after(1000,self.park_telescope_buttonclick,
                                  2,True)
                return 0
        #Second Parking loop
        if counter==2:
            if park:
                #If parking is activated
                print('Slew to Park Position the second time')
                #Slew telescope to parking position
                super().park_telescope()
                self.refresh_target_alt_az_ha(call_itself=False)
                #Wait again as above. But call counter=2 fpr second parking loop
            if not self.wait_for_slew_finish(call_itself=False):
                print('Waiting for Second Parking to finish')
                self.master.after(1000,self.park_telescope_buttonclick,
                                  2,False)
                return 0
            else:
                #When slewing is done
                print('Finished Second Parking')
                #Show message box to tell user to shut off the controller
                message=("Turn off the telescope controller to stop tracking"+
                 " and remain in park position!")
                messagebox.showinfo("Information",message=message,parent=self.master)
                return 0 
        
    def primary_mirror_pos_buttonclick(self):
        """Slew Telescope to Primary Mirror Cover Position.
        
           Uses LX200Commands primary_mirror_pos.
        """
        super().primary_mirror_pos()
        self.refresh_target_alt_az_ha(call_itself=False)
        self.wait_for_slew_finish()
        
    def secondary_mirror_pos_buttonclick(self):
        """Slew Telescope to Secondary Mirror Cover Position.
        
           Uses LX200Commands secondary_mirror_pos.
        """
        super().secondary_mirror_pos()
        self.refresh_target_alt_az_ha(call_itself=False)
        self.wait_for_slew_finish()
        
    def set_target_coordinates_gui(self):
        """ Calls set_target_coordinates() of Lx200Commands.
            Defines GUIs reaction to target_coordinates.
        """
        
        #Call set_target_coordinates
        if not self.set_target_coordinates():
            self.slew_target_button.config(state='disabled')
            self.display_alt_az('red')
            #Also plot target coordinates
            self.plot_star_and_traj()
            return 0
        else:
            #Display target_alt and az
            self.slew_target_button.config(state='normal')
            self.display_alt_az('light green')
            #Also plot target coordinates
            self.plot_star_and_traj()
            
    def display_alt_az(self,color):
        """Displays alt and az with given color.
        
           Convenience function.
        """
        self.target_alt_display.config(text=self.target_alt)
        self.target_alt_display.config(bg=color)
        self.target_az_display.config(text=self.target_az)
        self.target_az_display.config(bg=color)
        self.target_time_display.config(text=self.target_obs_time)
        self.target_time_display.config(bg=color)
        
      
    def set_hip_target_from_entry(self, event):
        """ Gets a HIP number from the HIP_entry widget and calculates the coordinates.
            Sets these coordinates as target_ra and target_dec 
            and displays them in the corresponding entry widgets.
        """
        hip_nr=self.HIP_entry.get()
        super().set_hip_target(hip_nr)
        self.target_ra_entry.delete(0, END)
        self.target_ra_entry.insert(0, self.target_ra)
        self.target_dec_entry.delete(0, END)
        self.target_dec_entry.insert(0, self.target_dec)
        self.set_target_coordinates_gui()
        
           
    def set_target_ra_from_entry(self, event):
        """ Gets a ra input from the target_ra_entry widget and sets it as target_ra.
            Accepted formats include hh mm ss and hh mm.t.
            
            Also tries to set set target dec from entry.
            Clears text of HIP_entry widget.
        """
        #Delete hip entry
        self.HIP_entry.delete(0, END)
        #Get ra input and set as target_ra
        ra_input=self.target_ra_entry.get()
        super().set_target_ra_from_string(ra_input)
        self.target_ra_entry.delete(0, END)
        self.target_ra_entry.insert(0, self.target_ra)
        
        #Try to get dec entry also
        dec_input=self.target_dec_entry.get()
        #If dec entry is empty do not try to set target_dec
        if not dec_input=='':
            super().set_target_dec_from_string(dec_input)
            self.target_dec_entry.delete(0, END)
            self.target_dec_entry.insert(0, self.target_dec)
        
        self.set_target_coordinates_gui()
        
    def set_target_dec_from_entry(self, event):
        """ Gets a dec input from the target_dec_entry widget and sets it as target_ra.
            Accepted formats include dd mm ss and dd mm.
            Clears text of HIP_entry widget.
        """
        #Delete hip entry
        #Get dec input and set as target_dec
        self.HIP_entry.delete(0, END)
        dec_input=self.target_dec_entry.get()
        super().set_target_dec_from_string(dec_input)
        self.target_dec_entry.delete(0, END)
        self.target_dec_entry.insert(0, self.target_dec)
        
        #Try to get ra entry also
        ra_input=self.target_ra_entry.get()
        #If ra entry is empty do not try to set target_ra
        if not ra_input=='':
            super().set_target_ra_from_string(ra_input)
            self.target_ra_entry.delete(0, END)
            self.target_ra_entry.insert(0, self.target_ra)
        
        self.set_target_coordinates_gui()
        
    def sync_yes_no(self):
        """Displays yes/no message if sync_button is clicked on.
        """
        result=messagebox.askyesno("Synchroniziation", 
                                     "Do you really want to synchronize coordinates with target coordinates?")
        if result:
            self.sync_on_target_buttonclick()
        
    def sync_on_target_buttonclick(self):
        """Gets target coordinates from entries.
           Synchronizes coordinates with target coordinates.
           In Case of Hipparcos target it will recalculate target coordinates
           at time of synchronization.
        """
        hip_nr=self.HIP_entry.get()
        if hip_nr!='':
            super().sync_on_hip(hip_nr)
            self.target_ra_entry.delete(0, END)
            self.target_ra_entry.insert(0, self.target_ra)
            self.target_dec_entry.delete(0, END)
            self.target_dec_entry.insert(0, self.target_dec)
        else:
            #If no Hip target_ get coordinates from entries
            #Calling one entry is enough since always both entries are checked
            #None refers to no event (such as Return)
            self.set_target_ra_from_entry(None)
            if hip_nr=='' and self.target_ra and self.target_dec:
                super().sync_on_coordinates()
            else:
                print('No valid coordinates set. Synchronisation stopped')
        #After sync (and if something went wrong):
        #Set all valid_target entries to 0 (controller won't let you slew to
        #the same coordinates twice
        self.valid_target=[0,0]
        self.slew_target_button.config(state='disabled')
            
    def wait_for_slew_finish(self,call_itself=True):
        """Waits until coordinates equal target coordinates within tolerance.
           Disables all (except STOP) buttons until target coordinates are reached.
           call_itself determines if funtion will call itself after 1 second.
           This is very useful to set to False if you want to call waiting from
           different function that should pause until waiting is over.
           
           Can be stopped by stop_waiting.
        """
        #Disable all buttons
        self.disable_all_buttons()
        #Check if slew has finished or self.stop_waiting parameter=True
        #Enable buttons if so.
        #self.stop_waiting parameter can be set by button in menubar
        #Then break the loop
        if super().slew_finished():
            #Enable all buttons again
            self.enable_all_buttons()
            return True
        else:
            #If variable call_itself is true
            #Calls itself after 1 second.
            #After call is asigned to global variable waiting 
            #to stop it via stop_waiting.
            if call_itself:
                global waiting
                waiting=self.master.after(1000,self.wait_for_slew_finish)
            return False
    
    def stop_waiting(self):
        """Stops Waiting for slew to finish and enables all buttons.
        
           Can be called in the menu.
        """
        #First disable all buttons to avoid binding events more than once.
        self.disable_all_buttons()
        #Enable all buttons 
        self.enable_all_buttons()
        #And try to stop waiting if waiting is going on.
        try:
            self.master.after_cancel(waiting)
        except NameError:
            return 0
        
    def delete_entries(self,event):
        """ Deletes entries of target_ra and target_dec.
        
            Used when entering new Hipparcos Number.
        """
        self.target_ra_entry.delete(0,END)
        self.target_dec_entry.delete(0,END)
            
        
    def disable_all_buttons(self):
        """ Disables all buttons and unbinds all bindings.
            Except of Stop Button
        """
        #Disable all buttons 
        #We also need to unbind the buttons which are called by events instead of commands
        for child in self.control_frame.winfo_children():
            child.config(state='disabled')
            child.unbind("<ButtonPress-1>")
            child.unbind("<ButtonRelease-1>")
        #Enable Stop Button again. It should always be enabled.
        self.stop_button.config(state='normal')
        
        #Disable and unbind entry widgets in target_frame
        for child in self.target_frame.winfo_children():
            child.config(state='disabled')
            child.unbind("<Return>")
            child.unbind("<Tab>")
        
        
        self.sync_button.config(state='disabled')
        
        #Radiobuttons
        for child in self.radiobutton_frame.winfo_children():
            child.config(state='disabled')
        
    def enable_all_buttons(self):
        """ Enables all buttons and binds all bindings.
            Except of Stop Button.
            All bindings are defined here, except of commands of buttons.
        """
        #Disable all buttons 
        #We also need to bind the buttons which are called by events instead of commands
        for child in self.control_frame.winfo_children():
            child.config(state='normal')
        #Add the bindings manually
        self.north_button.bind("<ButtonPress-1>",self.start_move_north_buttonclick)
        self.north_button.bind("<ButtonRelease-1>",self.stop_move_north_buttonclick)
        self.west_button.bind("<ButtonPress-1>",self.start_move_west_buttonclick)
        self.west_button.bind("<ButtonRelease-1>",self.stop_move_west_buttonclick)
        self.south_button.bind("<ButtonPress-1>",self.start_move_south_buttonclick)
        self.south_button.bind("<ButtonRelease-1>",self.stop_move_south_buttonclick)
        self.east_button.bind("<ButtonPress-1>",self.start_move_east_buttonclick)
        self.east_button.bind("<ButtonRelease-1>",self.stop_move_east_buttonclick)
        
        
        self.sync_button.config(state='normal')
        
        #Enable and bind entry widgets in target_frame
        for child in self.target_frame.winfo_children():
            child.config(state='normal')
        #Do not enable slew button
        self.slew_target_button.config(state='disabled')
        #Add the bindings manually
        #When entering any new number or char (also when deleting),
        #the entries of target_ra and target_dec should be deleted
        #Important to bind Return and Tab after this first binding to override this functionality
        #Otherwise it would also just delete the entries
        self.HIP_entry.bind("<Key>",
                            self.delete_entries,add='+')
        self.HIP_entry.bind("<Return>",
                            self.set_hip_target_from_entry, add="+")
        self.HIP_entry.bind("<Tab>",
                            self.set_hip_target_from_entry, add="+")

        
        self.target_ra_entry.bind("<Return>",
                                  self.set_target_ra_from_entry, add="+") 
        self.target_ra_entry.bind("<Tab>",
                                  self.set_target_ra_from_entry,add="+")
        
        
        self.target_dec_entry.bind("<Return>",
                                   self.set_target_dec_from_entry, add="+")
        self.target_dec_entry.bind("<Tab>", 
                                   self.set_target_dec_from_entry, add="+")
        
        
        #Radiobuttons
        for child in self.radiobutton_frame.winfo_children():
            child.config(state='normal')
    
    def save_pointing_star(self):
        """ Saves Pointings Stars Information to file.
            
            Takes Hipparcos Number, RA, DEC LST and Date and saves to file.
            
            Also Saves Hipparcos Number, RA, DEC, HA, 
            target_ra, target_dec, LST, UTC and Date to second file.
            This could lead to potentially new system of pointing_star data.
            This could be easier to handle.
            Not done yet.
        """
        ### Traditional File ###
        try:
            hipparcos=self.HIP_entry.get()
            #Need integer to catch errors and for formatting
            hipparcos=int(hipparcos)
            #Format Hipparcos Number to 000123
            hip_pointing="{:06d}".format(hipparcos)
        except ValueError:
            print('Invalid Hiparcos number')
            return 0
        
        #Format RA to hh mm ss
        (RA_hours,h,rest)=self.ra.partition('h')
        (RA_min,m,rest)=rest.partition('m')
        (RA_sec,s,rest)=rest.partition('s')
        RA_pointing="{} {} {}".format(RA_hours, RA_min, RA_sec)
        
        #Format DEC to +dd mm ss
        (DEC_deg,grad,rest)=self.dec.partition('°')
        (DEC_min,m,rest)=rest.partition("'")
        (DEC_sec,s,rest)=rest.partition('"')
        DEC_pointing="{} {} {}".format(DEC_deg, DEC_min, DEC_sec)
        
        #Format LST to hh mm ss
        (LST_hours,h,rest)=self.LST.partition(':')
        (LST_min,m,rest)=rest.partition(':')
        (LST_sec,s,rest)=rest.partition(':')
        LST_pointing="{} {} {}".format(LST_hours, LST_min, LST_sec)
        
        #Get Date in Format dd.mm.yyyy (using locale module)
        today = datetime.date.today()
        Date_pointing=today.strftime('%d.%m.%Y')
        
        line="{}    {}    {}    {}    {}\n".format(hip_pointing,
                                                 RA_pointing,
                                                 DEC_pointing,
                                                 LST_pointing,
                                                 Date_pointing)
        #Filename and path using pathlib module
        #File is in parrent_directory/pointing_stars/pointings_stars.txt
        current_path=pathlib.Path.cwd()
        parrent_path=current_path.parent
        file_path=parrent_path / 'pointing_stars' / 'pointing_stars.txt'
        #With automatically closes the file in the end
        with open(str(file_path), 'a') as ps_file:
            print('Saving pointing star to (old format) file')
            ps_file.write(line)
            
            
        ### New Format File ###
        
        #Format HA to hh mm ss
        (HA_hours,h,rest)=self.ha.partition('h')
        (HA_min,m,rest)=rest.partition('m')
        (HA_sec,s,rest)=rest.partition('s')
        HA_pointing="{} {} {}".format(HA_hours, HA_min, HA_sec)
        
        
        line=("{}    {}    {}    {}    {}    {}    {}    {}    {}"
            "    {}    {}    {}    {}    {}    {}\n")
        line=line.format(hip_pointing,
                         RA_pointing,
                         self.ra_float,
                         DEC_pointing,
                         self.dec_float,
                         HA_pointing,
                         self.ha_float,
                         self.target_ra,
                         self.target_ra_float,
                         self.target_dec,
                         self.target_dec_float,
                         self.target_ha_float,
                         self.LST,
                         self.UTC,
                         Date_pointing)
        
        #Filename and path using pathlib module
        #File is in parrent_directory/pointing_stars/pointings_stars_new_format.txt
        current_path=pathlib.Path.cwd()
        parrent_path=current_path.parent
        file_path=parrent_path / 'pointing_stars' / 'pointing_stars_new_format.txt'
        #With automatically closes the file in the end
        with open(str(file_path), 'a') as ps_file:
            print('Saving pointing star to (new format) file')
            ps_file.write(line)
예제 #42
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.ranking = []
        ## Define os três frames existentes na janela principal
        ## A janela principal foi dividida em 3 frames (esquerda, central e direita)
        self.leftframe = Frame(self)
        self.leftframe.grid(row=0, column=0, stick=Tk.NS + Tk.E)
        self.centerframe = Frame(self)
        self.centerframe.grid(row=0, column=1, stick=Tk.NS)
        self.rightframe = Frame(self)
        self.rightframe.grid(row=0, column=2, stick=Tk.NS + Tk.W)
        # Inicializei as instancias aqui porque senão self.botaoSelecionaEntrada\
        # não existe quando da criação dos botoes do frame esquerdo
        # container 1 - contem os objetos para leitura de arquivo
        # container 2 - contem os objetos para entrada de dados manual
        # container 3 - contem os objetos para escolha aleatoria dos rankings
        self.container1 = LabelFrame(self.centerframe,
                                     text="Escolha o arquivo",
                                     padx=5,
                                     pady=5)
        self.container2 = LabelFrame(self.centerframe,
                                     text="Entrada de dados",
                                     padx=5,
                                     pady=5)
        self.container3 = LabelFrame(self.centerframe,
                                     text="Escolha aleatória",
                                     padx=5,
                                     pady=5)

        ###
        #### Monta frame esquerdo
        #### Frame dos botões
        ###
        lblframe = LabelFrame(self.leftframe,
                              text="Selecione entrada",
                              padx=5,
                              pady=5)
        lblframe.grid(row=0, column=0)
        button1 = Button(lblframe,
                         text="Arquivo",
                         width=20,
                         command=lambda: self.botaoSelecionaEntrada(1))
        button1.grid(row=0, column=0)
        button2 = Button(lblframe,
                         text="Manual",
                         width=20,
                         command=lambda: self.botaoSelecionaEntrada(2))
        button2.grid(row=1, column=0)
        button3 = Button(lblframe,
                         text="Aleatório",
                         width=20,
                         command=lambda: self.botaoSelecionaEntrada(3))
        button3.grid(row=2, column=0)
        lblframe = LabelFrame(self.leftframe,
                              text="Calculadora",
                              padx=5,
                              pady=5)
        lblframe.grid(row=3, column=0, pady=20)
        button1 = Button(lblframe,
                         text="Calculadora",
                         width=20,
                         command=lambda: self.Calculadora())
        button1.grid(row=0, column=0)
        button2 = Button(lblframe,
                         text="Reset",
                         width=20,
                         command=lambda: self.resetDisplayResults())
        button2.grid(row=1, column=0)

        ###
        ### Monta Frame central
        ###
        ### O Frame central contém 3 "containers" que serão ligados e desligados em tempo
        ### de execução através dos botões existentes no frame esquerdo
        ###
        ##Entrada através de arquivo
        ##
        self.mySelectionF = Tk.StringVar()
        labelvalue = self.mySelectionF
        self.container1.grid(row=0, column=0)
        buttonFile = Tk.Button(self.container1,
                               text='Ler arquivo',
                               width=10,
                               command=self.askopenfilename)
        buttonFile.grid(row=0, column=0, sticky='N')
        self.displayRanking1()
        ### Desliga objeto do frame da tela
        self.container1.isgridded = True
        #self.container1.grid_forget()

        #
        # Entrada manual
        #
        #### DESISTI DE FAZER ASSIM SE DER TEMPO VOLTO A FAZER SENAO
        #### FAÇO DEPOIS DA ENTRAGA DA AD
        ####
        #self.mySelection = Tk.StringVar()
        #labelvalue = self.mySelection
        #self.container2 = LabelFrame(self.centerframe, text="Entrada de dados", padx=5, pady=5) ## Foi criado la em cima
        #self.container2.grid(row=0, column=0)
        # label com nome do ranking
        #self.label = Label(self.container2, text=labelvalue)
        #self.label.grid(row=0,column=1)
        # campo de entrada
        #entryA = Entry(self.container2,width=6)               #criamos o campo de texto
        #entryA.grid(column=0,row=1,sticky='EW'+'S')
        # Botao
        #button4 = Tk.Button(self.container2, text = '->', width = 10)
        #button4.grid( row=2,column=0,sticky='EW'+'N')
        #Combobox
        #self.comboboxM = ttk.Combobox(self.container2, width= 15, state="readonly", textvariable = self.mySelection)
        #self.comboboxM["values"] = ("Ranking 1", "Ranking 2")
        #self.comboboxM.grid(row=0, column=0)
        #self.comboboxM.bind("<<ComboboxSelected>>", self.callbackFunc)
        #ListBox
        #value=["one", "two", "three", "four", "five", "six", "seven","eight","nine","ten","eleven","twelve"] ### Somente para teste
        #value = []
        #self.listbox = Listbox(self.container2,selectmode=Tk.SINGLE)
        #scrollbar = Tk.Scrollbar(self.container2, orient=Tk.VERTICAL)
        #self.listbox.config( yscrollcommand=scrollbar.set)
        #scrollbar.configure(command=self.listbox.yview)
        #scrollbar.config(command=self.listbox.yview)
        #self.listbox.insert(Tk.END, None)
        #for item in value:
        #    self.listbox.insert(Tk.END, item)
        #self.listbox.grid(row=1, column=1,stick=Tk.W)
        #scrollbar.grid(row=1,column=2,stick=Tk.NS+Tk.W)

        ### Aqui resolvi fazer assim, senão não ia dar tempo para fazer do jeito que eu queria
        ### Caminho mais fácil, senão nao consigo fazer os testes se é que vou conseguir
        self.container2.grid(row=0, column=0)
        self.v1 = Tk.IntVar(value=1)
        #self.v1 = Tk.StringVar(value="1")
        self.v1.set(1)
        self.v2 = Tk.IntVar(value=1)
        #self.v2 = Tk.StringVar(value="1")
        self.v2.set(1)

        self.displayEntradaManual()
        #self.label = Label(self.container2, text="Escolha o tipo de entrada")
        #self.label.grid(row=0,column=0, columnspan=2)
        #self.rb1 = Tk.Radiobutton(self.container2, text="Ranking", variable=self.v1, value=1,state=Tk.ACTIVE,indicatoron=1)
        #self.rb1.grid(row=1,column=0)
        #self.rb2 = Tk.Radiobutton(self.container2, text="Score", variable=self.v1, value=2,state=Tk.ACTIVE,indicatoron=1)
        #self.rb2.grid(row=1,column=1)
        #self.label = Label(self.container2, text="Ranking / Score 1")
        #self.label.grid(row=2,column=0)
        #self.entryM1 = Entry(self.container2,width=30)               #criamos o campo de texto
        #self.entryM1.grid(row=3,column=0,sticky='EW'+'S',columnspan=2)

        #self.rb3 = Tk.Radiobutton(self.container2, text="Ranking", variable=self.v2, value=1,state=Tk.ACTIVE,indicatoron=1)
        #self.rb3.grid(row=4,column=0)
        #self.rb4 = Tk.Radiobutton(self.container2, text="Score", variable=self.v2, value=2,state=Tk.ACTIVE,indicatoron=1)
        #self.rb4.grid(row=4,column=1)
        #self.label = Label(self.container2, text="Ranking / Score 2")
        #self.label.grid(row=5,column=0)
        #self.entryM2 = Entry(self.container2,width=30)               #criamos o campo de texto
        #self.entryM2.grid(row=6,column=0,sticky='EW'+'S',columnspan=2)
        self.container2.isgridded = False
        self.container2.grid_forget()

        ##entrada aleatoria
        #self.container3 = LabelFrame(self.centerframe, text="Entrada de dados", padx=5, pady=5)
        self.mySelectionA = Tk.StringVar()
        self.container3.grid(row=0, column=0)
        self.container3A = LabelFrame(self.container3,
                                      text="Define tamanho",
                                      padx=5,
                                      pady=5)
        self.container3A.grid(row=0, column=0)
        # label com nome do ranking
        self.label = Label(self.container3A,
                           text='Selecione o tamanho dos rankings')
        self.label.grid(row=0, column=0, sticky="S")
        self.entryB = Entry(self.container3A,
                            width=6)  #criamos o campo de texto
        self.entryB.grid(row=1, column=0, sticky='EW' + 'S')
        button5 = Tk.Button(self.container3A,
                            text='Gerar',
                            width=10,
                            command=self.gerarRankingAleatorio)
        button5.grid(row=2, column=0, sticky='EW' + 'N')

        self.displayRanking()
        #self.container3B = LabelFrame(self.container3,text="Visualiza RANKINGs", padx=5, pady=5)
        #self.container3B.grid(row=0, column=1)
        self.container3.isgridded = False
        self.container3.grid_forget()
        ####self.container3B = LabelFrame(self.container3, text="Visualiza RANKINGs", padx=5, pady=5)
        ####self.container3B.grid(row=0, column=1)
        ####self.comboboxA = ttk.Combobox(self.container3B, width= 15, state="readonly", textvariable = self.mySelectionA)
        ####self.comboboxA["values"] = ("Ranking 1", "Ranking 2")
        ####self.comboboxA.grid(row=0, column=1)
        ####self.comboboxA.bind("<<ComboboxSelected>>", self.callbackRandom)
        #value=["one", "two", "three", "four", "five", "six", "seven","eight","nine","ten","eleven","twelve"] ### Somente para teste
        ####value = []
        ####self.listbox = Listbox(self.container3B,selectmode=Tk.SINGLE)
        ####scrollbar = Tk.Scrollbar(self.container3B, orient=Tk.VERTICAL)
        ####self.listbox.config( yscrollcommand=scrollbar.set)
        ####scrollbar.configure(command=self.listbox.yview)
        ####scrollbar.config(command=self.listbox.yview)
        ####self.listbox.insert(Tk.END, None)
        ####for item in value:
        ####    self.listbox.insert(Tk.END, item)
        ####self.listbox.grid(row=1, column=1,stick=Tk.W)
        ####scrollbar.grid(row=1,column=2,stick=Tk.NS+Tk.W)
        ####self.container3.isgridded = False
        ####self.container3.grid_forget()

        ###
        #### Monta frame direito
        ###
        self.lblframe = LabelFrame(self.rightframe,
                                   text="RESULTADOS",
                                   padx=5,
                                   pady=5)
        self.lblframe.grid(row=0, column=0)
        self.label = Label(self.lblframe, text="Kemeny = ")
        self.label.grid(row=0, column=0, sticky=Tk.W)
        result = str(0)
        self.labelkemeny = Label(self.lblframe, text=result)
        self.labelkemeny.grid(row=0, column=1)
        self.label = Label(self.lblframe, text="Footrule = ")
        self.label.grid(row=1, column=0, sticky=Tk.W)
        self.labelfootrule = Label(self.lblframe, text=result)
        self.labelfootrule.grid(row=1, column=1)
        self.label = Label(self.lblframe, text="*** Inversões ***")
        self.label.grid(row=2, column=0)
        self.label = Label(self.lblframe, text="Inversões Ranking 1 = ")
        self.label.grid(row=3, column=0, sticky=Tk.W)
        self.label = Label(self.lblframe, text="Inversões Ranking 2 = ")
        self.label.grid(row=4, column=0, sticky=Tk.W)
        self.labelinv1 = Label(self.lblframe, text=result)
        self.labelinv1.grid(row=3, column=1)
        self.labelinv2 = Label(self.lblframe, text=result)
        self.labelinv2.grid(row=4, column=1)
        self.bye = Button(self.rightframe, text="Bye Bye", command=self.quit)
        self.bye.grid(row=5, column=0)
        self.pack()

    # Monta radiobutton no frame central container 2
    def displayEntradaManual(self):
        """@ Show RadioButton on container2 in Application Class
           @example self.displayEntradaManual()
        """
        self.label = Label(self.container2, text="Escolha o tipo de entrada")
        self.label.grid(row=0, column=0, columnspan=2)
        self.rb1 = Tk.Radiobutton(self.container2,
                                  text="Ranking",
                                  variable=self.v1,
                                  value=1,
                                  state=Tk.ACTIVE,
                                  indicatoron=1)
        self.rb1.grid(row=1, column=0)
        self.rb2 = Tk.Radiobutton(self.container2,
                                  text="Score",
                                  variable=self.v1,
                                  value=2,
                                  state=Tk.ACTIVE,
                                  indicatoron=1)
        self.rb2.grid(row=1, column=1)
        self.label = Label(self.container2, text="Ranking / Score 1")
        self.label.grid(row=2, column=0)
        self.entryM1 = Entry(self.container2,
                             width=30)  #criamos o campo de texto
        self.entryM1.grid(row=3, column=0, sticky='EW' + 'S', columnspan=2)

        self.rb3 = Tk.Radiobutton(self.container2,
                                  text="Ranking",
                                  variable=self.v2,
                                  value=1,
                                  state=Tk.ACTIVE,
                                  indicatoron=1)
        self.rb3.grid(row=4, column=0)
        self.rb4 = Tk.Radiobutton(self.container2,
                                  text="Score",
                                  variable=self.v2,
                                  value=2,
                                  state=Tk.ACTIVE,
                                  indicatoron=1)
        self.rb4.grid(row=4, column=1)
        self.label = Label(self.container2, text="Ranking / Score 2")
        self.label.grid(row=5, column=0)
        self.entryM2 = Entry(self.container2,
                             width=30)  #criamos o campo de texto
        self.entryM2.grid(row=6, column=0, sticky='EW' + 'S', columnspan=2)
        self.label = Label(self.container2,
                           text="Formato da entrada(ranking): 5 4 3 2 1")
        self.label.grid(row=7, column=0, sticky='W')
        self.label = Label(
            self.container2,
            text="Formato da entrada(score): 0.65 0.32 0.62 0.23 0.34")
        self.label.grid(row=8, column=0, sticky='W')
        self.container2.isgridded = False
        self.container2.grid_forget()

    # Reset nos valores do frame direito
    def resetDisplayResults(self):
        """@ Reset values kemeny, footrule and Inversions and clean labels
           @example self.resetDisplayResults()
        """
        del self.ranking[:]
        result = str(0)
        self.labelkemeny = Label(self.lblframe, text=result)
        self.labelkemeny.grid(row=0, column=1)
        self.labelfootrule = Label(self.lblframe, text=result)
        self.labelfootrule.grid(row=1, column=1)
        self.labelinv1 = Label(self.lblframe, text=result)
        self.labelinv1.grid(row=3, column=1)
        self.labelinv2 = Label(self.lblframe, text=result)
        self.labelinv2.grid(row=4, column=1)
        if self.buttonClick == 1:
            self.displayRanking1()
        if self.buttonClick == 2:
            self.entryM1.delete(0, 'end')  #limpamos o campo de texto
            self.entryM1.grid(row=3, column=0, sticky='EW' + 'S', columnspan=2)
            self.entryM2.delete(0, 'end')  #limpamos o campo de texto
            self.entryM2.grid(row=6, column=0, sticky='EW' + 'S', columnspan=2)
        if self.buttonClick == 3:
            self.displayRanking()
        messagebox.showinfo("Mensagem",
                            "Kemeny, footrule e inversões zeradas!")

    # Metodo que retorna um evento de selecao
    def displayRanking(self):
        """@ Show combobox on screen
           @example self.displayRanking()
        """
        self.container3B = LabelFrame(self.container3,
                                      text="Visualiza RANKINGs",
                                      padx=5,
                                      pady=5)
        self.container3B.grid(row=0, column=1)
        self.comboboxA = ttk.Combobox(self.container3B,
                                      width=15,
                                      state="readonly",
                                      textvariable=self.mySelectionA)
        self.comboboxA["values"] = ("Ranking 1", "Ranking 2")
        self.comboboxA.grid(row=0, column=1)
        self.comboboxA.bind("<<ComboboxSelected>>", self.callbackRandom)
        #value=["one", "two", "three", "four", "five", "six", "seven","eight","nine","ten","eleven","twelve"] ### Somente para teste
        self.displayRankingListbox()
        #####value = []
        #####self.listbox = Listbox(self.container3B,selectmode=Tk.SINGLE)
        #####scrollbar = Tk.Scrollbar(self, orient=Tk.VERTICAL)
        #####self.listbox.config( yscrollcommand=scrollbar.set)
        #####scrollbar.configure(command=self.listbox.yview)
        #####scrollbar.config(command=self.listbox.yview)
        #####self.listbox.insert(Tk.END, None)
        #####for item in value:
        #####    self.listbox.insert(Tk.END, item)
        #####self.listbox.grid(row=1, column=1,stick=Tk.W)
        #####scrollbar.grid(row=1,column=2,stick=Tk.NS+Tk.W)
        #self.container3B = LabelFrame(self.container3B,text="Visualiza RANKINGs", padx=5, pady=5)
        #self.container3B.grid(row=0, column=1)
    def displayRankingListbox(self, value=[]):
        """@note show Ranking on display
           @param[in] a list
           @example self.displayRankingListbox([1 2 3 4 5])
        """
        self.value = value
        self.listbox = Listbox(self.container3B, selectmode=Tk.SINGLE)
        scrollbar = Tk.Scrollbar(self.container3B, orient=Tk.VERTICAL)
        self.listbox.config(yscrollcommand=scrollbar.set)
        scrollbar.configure(command=self.listbox.yview)
        scrollbar.config(command=self.listbox.yview)
        self.listbox.insert(Tk.END, None)
        for item in value:
            self.listbox.insert(Tk.END, item)
        self.listbox.grid(row=1, column=1, stick=Tk.W)
        scrollbar.grid(row=1, column=2, stick=Tk.NS + Tk.W)

    ## Segui o Caminho mais fácil
    ## Dupliquei displayRanking e alterei o container apenas
    ## Não é o correto, mas não está errado, se sobrar tempo faço da forma correta
    def displayRanking1(self):
        """@ Show combobox on screen
           @example self.displayRanking1()
        """
        self.container1B = LabelFrame(self.container1,
                                      text="Visualiza RANKINGs",
                                      padx=5,
                                      pady=5)
        self.container1B.grid(row=0, column=1)
        self.comboboxF = ttk.Combobox(self.container1B,
                                      width=15,
                                      state="readonly",
                                      textvariable=self.mySelectionF)
        self.comboboxF["values"] = ("Ranking 1", "Ranking 2")
        self.comboboxF.grid(row=0, column=1)
        self.comboboxF.bind("<<ComboboxSelected>>", self.callbackRandom)
        #value=["one", "two", "three", "four", "five", "six", "seven","eight","nine","ten","eleven","twelve"] ### Somente para teste
        self.displayRankingListbox1()
        '''
        value = []
        self.listbox = Listbox(self.container3B,selectmode=Tk.SINGLE)
        scrollbar = Tk.Scrollbar(self, orient=Tk.VERTICAL)
        self.listbox.config( yscrollcommand=scrollbar.set)
        scrollbar.configure(command=self.listbox.yview)
        scrollbar.config(command=self.listbox.yview)
        self.listbox.insert(Tk.END, None)
        for item in value:
            self.listbox.insert(Tk.END, item)
        self.listbox.grid(row=1, column=1,stick=Tk.W)
        scrollbar.grid(row=1,column=2,stick=Tk.NS+Tk.W) '''
        #self.container3B = LabelFrame(self.container3B,text="Visualiza RANKINGs", padx=5, pady=5)
        #self.container3B.grid(row=0, column=1)
    def displayRankingListbox1(self, value=[]):
        """@note show Ranking on display
           @param[in] a list
           @example self.displayRankingListbox([1 2 3 4 5])
        """
        self.value = value
        self.listbox = Listbox(self.container1B, selectmode=Tk.SINGLE)
        scrollbar = Tk.Scrollbar(self.container1B, orient=Tk.VERTICAL)
        self.listbox.config(yscrollcommand=scrollbar.set)
        scrollbar.configure(command=self.listbox.yview)
        scrollbar.config(command=self.listbox.yview)
        self.listbox.insert(Tk.END, None)
        for item in value:
            self.listbox.insert(Tk.END, item)
        self.listbox.grid(row=1, column=1, stick=Tk.W)
        scrollbar.grid(row=1, column=2, stick=Tk.NS + Tk.W)

    #
    # Gera dois rankings Aleatórios a partir de um inteiro
    # os rankings sao colocados em um vetor self.ranking
    def gerarRankingAleatorio(self):
        """@note Build a random Ranking and show on display
           @example self.gerarRankingAleatorio()
        """
        self.resetDisplayResults()
        try:
            value = int(self.entryB.get())
        except ValueError:
            messagebox.showinfo("ERRO!",
                                "Informar o tamanho do ranking a ser gerado!")
            return
        #choice = self.mySelectionA.get()  ### Não precisei a selecao acontece em displayrankinglistbox
        #index = self.comboboxA.current()  ### nao precisei a selecao acontece em displayrankinglistbox
        if value < 1:
            messagebox.showinfo("Title", "Valor inválido ( " + value + " )")
        else:
            del self.ranking[:]
            for _ in range(2):
                self.ranking.append(Ranking(value))
            messagebox.showinfo("Title", "Rankings 1 e 2 gerados")
            self.comboboxA.current(0)
            self.displayRankingListbox(getattr(self.ranking[0], 'ranking'))
            #self.resetDisplayResults()

    #def callbackFunc(self, event):
    #    select = self.mySelection.get()
    #    self.labelvalue = select
    #    self.label = Label(self.container2, text=self.labelvalue)
    #    self.label.grid(row=0,column=1)
    #    print(select)

    def callbackRandom(self, event):
        """@note auxiliary method to gerarRankingAleatorio
           @example self.callbackRandom()
        """
        #select = self.mySelection.get()
        try:
            #_ = self.ranking[0]
            #_ = getattr(self.ranking[0],"ranking")
            index = self.comboboxA.current()
            array = getattr(self.ranking[index], 'ranking')
            self.listbox.delete(0, Tk.END)
            self.listbox.insert(Tk.END, None)
            for item in array:
                self.listbox.insert(Tk.END, item)
            self.listbox.grid(row=1, column=1, stick=Tk.W)
        except IndexError:
            messagebox.showinfo("ERRO!", "Não existem Rankings gerados!")
            return

    def askopenfilename(self):
        """@note Open ranking file
           @example self.askopenfilename()
        """
        filepath = askopenfilename()
        if filepath:
            #self.container1.filepaths.append(filepath)
            with open(filepath, "r+") as f:
                del self.ranking[:]
                for line in f:
                    value = line.replace("\n", "").replace(
                        "\r", "")  # do something with the line
                    try:
                        value = literal_eval(value)
                    except SyntaxError:
                        messagebox.showinfo("ERRO!", "Arquivo incompatível!")
                        return
                    else:
                        if type(value) is int:
                            del self.ranking[:]
                            for _ in range(2):
                                self.ranking.append(Ranking(value))
                            messagebox.showinfo("Title",
                                                "Rankings 1 e 2 gerados")
                        elif type(value) is list:
                            self.ranking.append(Ranking(value))
                        elif type(value) is tuple:
                            self.ranking.append(Ranking(value))
            #for line in inputfile.readline():
            ##    line = line.replace("\n", "").replace("\r", "")
            #   print(line)

            #   #value = literal_eval(line)
            #   #print(type(value))
            self.comboboxF.current(0)
            self.displayRankingListbox1(getattr(self.ranking[0], 'ranking'))
            f.close()

    def botaoSelecionaEntrada(self, value):
        """@note Build a rank from tuple.
           @param[in] integer
           @example self.botaoSelecionaEntrada(1)
        """
        self.buttonClick = value
        print("Called" + str(self.value))
        self.container1.isgridded = False
        self.container1.grid_forget()
        self.container2.isgridded = False
        self.container2.grid_forget()
        self.container3.isgridded = False
        self.container3.grid_forget()
        if self.buttonClick == 1:
            self.container1.isgridded = True
            self.container1.grid(row=0, column=0)
        if self.buttonClick == 2:
            # Ativa radiobutton do ranking / score (nao esta ativando)
            self.v1.set(1)
            self.v2.set(1)
            # Liga container 2
            self.displayEntradaManual()
            self.container2.isgridded = True
            self.container2.grid(row=0, column=0)
        if self.buttonClick == 3:
            self.container3.isgridded = True
            self.container3.grid(row=0, column=0)

    def checkType(self, lista):
        """@note Verify there are only digits from list
           @param[in] list
           @return Boolean
           @example self.checkType([1, 3, 4, 2])
        """
        for x in lista:
            if type(x) is str:
                return False
        return True

    def Calculadora(self):
        """@note Method to activate auxiliaries methods to show results
           @example self.Calculadora()
        """
        try:
            if self.buttonClick == 1:
                #value1 = self.entryM1.get().split()
                #value2 = self.entryM2.get().split()
                #print("Valor 1", value1, "Valor 2",value2)
                #del self.ranking[:]
                # Adiciona a entrada 1 ao vetor self.ranking
                #if int(self.v1.get()) == 1:
                #    self.ranking.append(Ranking(value1))
                #else:
                #    self.ranking.append(Ranking(tuple(value1)))
                # Adiciona a entrada 2 ao vetor self.ranking
                #if int(self.v2.get()) == 1:
                #    self.ranking.append(Ranking(value2))
                #else:
                #    self.ranking.append(Ranking(tuple(value2)))
                try:
                    #_ = self.ranking[0]
                    _ = getattr(self.ranking[0], "ranking")
                except IndexError:
                    messagebox.showinfo("ERRO!",
                                        "Não existem Rankings gerados!")
                    return
                self.showKemeny()
                self.showFootrule()
                self.showInvert()
                print(getattr(self.ranking[0], 'ranking'))
                print(getattr(self.ranking[1], 'ranking'))
            if self.buttonClick == 2:
                value1 = self.entryM1.get().split()
                value2 = self.entryM2.get().split()
                print("Valor 1", value1, "Valor 2", value2)
                if self.checkType(value1) and self.checkType(value2) or\
                not (len(value1)) or any(d is None for d in value1) or value1 is None or\
                not (len(value2)) or any(d is None for d in value2) or value2 is None or\
                len(value1) != len(set(value1)) or len(value2) != len(set(value2)) or\
                len(set(value1)) != len(set(value2)):
                    messagebox.showinfo(
                        "ERRO!",
                        "Erro na entrada de dados - Ranking inválido!")
                else:
                    del self.ranking[:]
                    # Adiciona a entrada 1 ao vetor self.ranking
                    if int(self.v1.get()) == 1:
                        self.ranking.append(Ranking(tuple(value1)))
                    else:
                        self.ranking.append(Ranking(value1))
                    # Adiciona a entrada 2 ao vetor self.ranking
                    if int(self.v2.get()) == 1:
                        self.ranking.append(Ranking(tuple(value2)))
                    else:
                        self.ranking.append(Ranking(value2))
                    self.showKemeny()
                    self.showFootrule()
                    self.showInvert()
                    #print(getattr(self.ranking[0],'ranking'))
                    #print(getattr(self.ranking[1],'ranking'))
            if self.buttonClick == 3:
                try:
                    _ = getattr(self.ranking[0], "ranking")
                except (IndexError, AttributeError):
                    messagebox.showinfo("Title",
                                        "Não existem Rankings gerados!")
                else:
                    #    print(len(getattr(self.ranking,"ranking")))
                    self.showKemeny()
                    self.showFootrule()
                    self.showInvert()
        except AttributeError:
            messagebox.showinfo("ERRO!",
                                "Não existem valores a ser calculados!")
            return

    def showKemeny(self):
        """@note Calculate Kemeny distance from Ranking Class than show on screen
           @example self.showKemeny()
        """
        value1 = Ranking(getattr(self.ranking[0], 'ranking'))
        value2 = Ranking(getattr(self.ranking[1], 'ranking'))
        print(value1, value2)
        result = value1.kDist(value2)
        self.labelkemeny = Label(self.lblframe, text=result)
        self.labelkemeny.grid(row=0, column=1)

    def showFootrule(self):
        """@note Calculate Footrule distance from Ranking Class than show on screen
           @example self.showFootrule()
        """
        value1 = Ranking(getattr(self.ranking[0], 'ranking'))
        value2 = Ranking(getattr(self.ranking[1], 'ranking'))
        print(value1, value2)
        result = value1.fDist(value2)
        self.labelfootrule = Label(self.lblframe, text=result)
        self.labelfootrule.grid(row=1, column=1)

    def showInvert(self):
        """@note Calculate inversions from Ranking Class than show on screen
           @example self.showInvert()
        """
        value1 = Ranking(getattr(self.ranking[0], 'ranking'))
        value2 = Ranking(getattr(self.ranking[1], 'ranking'))
        print(value1, value2)
        result = value1.invCount()
        self.labelinv1 = Label(self.lblframe, text=result)
        self.labelinv1.grid(row=3, column=1)
        result = value2.invCount()
        self.labelinv2 = Label(self.lblframe, text=result)
        self.labelinv2.grid(row=4, column=1)
예제 #43
0
class addexpense:
    def __init__(self):
        self.window = Tk()
        self.mainframe = Frame(self.window)

        self.instructionL = Label(self.mainframe, text="Please fill in the fields\nwith appropriate values. ")
        self.dateL = Label(self.mainframe, text="Date: ")
        self.electricityL = Label(self.mainframe, text="Electricity: ")
        self.gasL = Label(self.mainframe, text="Gas: ")
        self.waterL = Label(self.mainframe, text="Water: ")
        self.salaryL = Label(self.mainframe, text="Salary: ")
        self.rentL = Label(self.mainframe, text="Rent: ")
        self.costofgoodL = Label(self.mainframe, text="Cost of Goods: ")

        self.dateI = Entry(self.mainframe)
        self.electricityI = Entry(self.mainframe)
        self.gasI = Entry(self.mainframe)
        self.waterI = Entry(self.mainframe)
        self.salaryI = Entry(self.mainframe)
        self.rentI = Entry(self.mainframe)
        self.costofgoodI = Entry(self.mainframe)

        self.okayB = Button(self.mainframe, text="OKAY")
        self.cancelB = Button(self.mainframe, text="CANCEL", command=self.cancel)
        self.mainframe.grid(row = 0, column = 0, columnspan = 2, sticky = W + E + N +S)
        self.mainframe.propagate(0)

        self.instructionL.grid(row = 0, column = 0, columnspan = 2)
        self.dateL.grid(row = 1, column = 0)
        self.electricityL.grid(row = 2, column = 0)
        self.gasL.grid(row = 3, column = 0)
        self.waterL.grid(row = 4, column = 0)
        self.salaryL.grid(row = 5, column = 0)
        self.rentL.grid(row = 6, column = 0)
        self.costofgoodL.grid(row = 7, column = 0)

        self.dateI.grid(row=1, column=1)
        self.electricityI.grid(row=2, column=1)
        self.gasI.grid(row=3, column=1)
        self.waterI.grid(row=4, column=1)
        self.salaryI.grid(row=5, column=1)
        self.rentI.grid(row=6, column=1)
        self.costofgoodI.grid(row=7, column=1)

        self.okayB.grid(row = 8, column = 0)
        self.okayB.bind("<Button-1>", self.okayE)
        self.cancelB.grid(row = 8, column = 1)

    def cancel(self):
        self.window.destroy()

    # Date, Electricity, Gas, Water, Salary, Rent, CostofGood
    def okayE(self, event):
        info = []
        date = self.dateI.get()
        electricity = self.electricityI.get()
        gas=self.gasI.get()
        water=self.waterI.get()
        salary=self.salaryI.get()
        rent=self.rentI.get()
        costofgood=self.costofgoodI.get()
        try:
            info.append(date)
            info.append(electricity)
            info.append(gas)
            info.append(water)
            info.append(salary)
            info.append(rent)
            info.append(costofgood)
            expense = tuple(info)
            QF.addExpense(expense)
            self.window.destroy()
        except:
            messagebox.showerror("Error", "Something is Wrong\nExpenses must be nonnegative numbers!\nCheck your input!")
            self.window.destroy()
예제 #44
0
class AboutWindow:
    def __init__(self, parent):
        self.aboutWindow = Toplevel(parent)
        self.aboutWindow.withdraw()
        self.aboutWindow.geometry('+{x}+{y}'.format(x=parent.winfo_x(),
                                                    y=parent.winfo_y()))
        self.aboutWindow.wm_attributes("-topmost", 1)
        self.aboutWindow.focus_force()
        self.aboutWindow.iconbitmap("imagefiles/stIcon.ico")
        self.aboutWindow.title("About")
        self.aboutWindow.resizable(False, False)
        self.aboutWindow.grab_set()

        self.frameTop = Frame(self.aboutWindow)

        self.aboutImage = PhotoImage(file="imagefiles/stLogo64.png")
        self.aboutImageLabel = Label(self.frameTop,
                                     image=self.aboutImage,
                                     cursor="hand2")
        self.aboutImageLabel.bind(
            "<Button-1>",
            lambda x: webbrowser.open('https://www.go1den.com/streamticker',
                                      new=2))
        self.aboutImageLabel.grid(row=0, column=0, padx=4, pady=4)

        self.aboutLabel = Label(
            self.frameTop,
            text="StreamTicker\n\nVersion 2.0.7\n\nReleased: 5/4/2021",
            justify=LEFT)
        self.aboutLabel.grid(row=0, column=1, sticky=W, pady=4)

        self.frameTop.grid(row=0, column=0, sticky=W)

        self.aboutSupportLabel = Label(
            self.aboutWindow,
            text=
            "Hello. I'm Go1den. I developed StreamTicker.\nThis program is available to use for free.\nThat being said, I devoted many hours to it.\n\nPlease consider supporting me if you enjoy it:",
            justify=LEFT)
        self.aboutSupportLabel.grid(row=1,
                                    column=0,
                                    sticky=W,
                                    padx=4,
                                    columnspan=2)

        self.myPaypalImage = PhotoImage(file="imagefiles/donate.png")
        self.myPaypalButton = Label(self.aboutWindow,
                                    image=self.myPaypalImage,
                                    cursor="hand2")
        self.myPaypalButton.bind(
            "<Button-1>", lambda x: webbrowser.open(
                'https://www.paypal.com/donate/?hosted_button_id=LXMBXT59KL578',
                new=2))
        self.myPaypalButton.grid(row=2, column=0, columnspan=2, pady=4, padx=4)

        self.aboutThanksLabel = Label(
            self.aboutWindow,
            text=
            "Thank you so much for trying my program!\nIf you enjoy it, please tell others about it.",
            justify=LEFT)
        self.aboutThanksLabel.grid(row=3, column=0, sticky=W, pady=4, padx=4)

        self.okButton = HoverButton(self.aboutWindow,
                                    text="OK",
                                    width=10,
                                    bd=2,
                                    relief=GROOVE,
                                    command=lambda: self.aboutWindow.destroy())
        self.okButton.grid(row=4, column=0, sticky=SE, pady=4)

        self.aboutWindow.deiconify()
        self.aboutWindow.mainloop()
예제 #45
0
Label(login_w, text="Username & password:"******"*", width=14).grid(row=0,
                                                                column=1)
Button(login_w, text="Submit", command=login).pack()
login_w.mainloop()

main_w = Tk()
main_w.title("Minecraft Server")
main_w.resizable(0, 0)
main_w.protocol("WM_DELETE_WINDOW", main_close)

sid_bar = Frame(main_w)
sid_bar.grid(row=0, column=0)
status = LabelFrame(sid_bar, text="Status")
status.pack()
Label(status, text="State:").grid(row=0, column=0)
online = StringVar()
online.set("N/A")
Label(status, textvariable=online).grid(row=0, column=1)
Label(status, text="Players:").grid(row=1, column=0)
players = IntVar()
players.set(0)
Label(status, textvariable=players).grid(row=1, column=1)
Label(status, text="Latency:").grid(row=2, column=0)
latency = IntVar()
latency.set(0)
Label(status, textvariable=latency).grid(row=2, column=1)
actions = LabelFrame(sid_bar, text="Actions")
예제 #46
0
    def __init__(self, tkobj):
        #Frame: Label + Entryfeld
        TiFrame = Frame(tkobj)
        TiFrame.grid(column=0, row=0, pady=5, padx=5, sticky=NW)

        #Label Titel
        lblTi = MyLabel(TiFrame)
        lblTi.set('Titel')
        lblTi.grid(column=0, row=1, pady=5, padx=5, sticky=NW)

        #Label SOPNr.
        lblSOP = MyLabel(TiFrame)
        lblSOP.set('SOP-Nr.')
        lblSOP.grid(column=0, row=2, pady=5, padx=5, sticky=NW)

        #Label Institut
        lblins = MyLabel(TiFrame)
        lblins.set('Institut')
        lblins.grid(column=0, row=3, pady=5, padx=5, sticky=NW)

        #Label Abteilung
        lblabt = MyLabel(TiFrame)
        lblabt.set('Abteilung')
        lblabt.grid(column=0, row=4, pady=5, padx=5, sticky=NW)

        #Entry Titel
        self.txtTitel = MyEntryfield(TiFrame)
        self.txtTitel.grid(column=1, row=1, pady=5, padx=5, sticky=NW)
        self.txtTitel.focus()

        #Entry SOPNr.
        self.txtSOPNr = MyEntryfield(TiFrame, fg='red')
        self.txtSOPNr.insert(INSERT, 'XX_999')
        self.txtSOPNr.config(width=10)
        self.txtSOPNr.grid(column=1, row=2, pady=5, padx=5, sticky=NW)

        #Entry Institut
        self.txtInst = MyEntryfield(TiFrame)
        self.txtInst.grid(column=1, row=3, pady=5, padx=5, sticky=NW)

        #Entry Abteilung
        self.txtAbt = MyEntryfield(TiFrame)
        self.txtAbt.grid(column=1, row=4, pady=5, padx=5, sticky=NW)

        #Frame Checkbox
        CheckFrame = Frame(tkobj)
        CheckFrame.grid(column=0, row=1, pady=5, padx=5, sticky=NW)

        #Label Name, Rolle, Datum
        lblName = MyLabel(CheckFrame)
        lblName.set('Name, Rolle')
        lblName.grid(column=1, row=0, pady=5, padx=5, sticky=NW)

        lblDatum = MyLabel(CheckFrame)
        lblDatum.set('Datum (YYYY.MM.DD)')
        lblDatum.grid(column=2, row=0, pady=5, padx=5, sticky=NW)

        #Label der Checkbox
        #Label - Erstellung
        lblErstellung = MyLabel(CheckFrame)
        lblErstellung.set('erstellt')
        lblErstellung.grid(column=0, row=1, pady=5, padx=5, sticky=NW)

        #Label - Prüfung
        lbl1Prüfung = MyLabel(CheckFrame)
        lbl1Prüfung.set('geprüft')
        lbl1Prüfung.grid(column=0, row=2, pady=5, padx=5, sticky=NW)

        #Label - Prüfung
        lbl2Prüfung = MyLabel(CheckFrame)
        lbl2Prüfung.set('geprüft')
        lbl2Prüfung.grid(column=0, row=3, pady=5, padx=5, sticky=NW)

        #Label - Genehmigung
        lblFreigabe = MyLabel(CheckFrame)
        lblFreigabe.set('freigegeben')
        lblFreigabe.grid(column=0, row=4, pady=5, padx=5, sticky=NW)

        #Label - Veröffentlichung
        lblRel = MyLabel(CheckFrame)
        lblRel.set('veröffentlicht')
        lblRel.grid(column=0, row=5, pady=5, padx=5, sticky=NW)

        #Combobox zum Check-Block
        self.ComNaRo = MyCombobox(CheckFrame)
        self.ComNaRo.grid(column=1, row=1, pady=5, padx=5, sticky=NW)
        self.Ch1NaRo = MyCombobox(CheckFrame)
        self.Ch1NaRo.grid(column=1, row=2, pady=5, padx=5, sticky=NW)
        self.Ch2NaRo = MyCombobox(CheckFrame)
        self.Ch2NaRo.grid(column=1, row=3, pady=5, padx=5, sticky=NW)
        self.AppNaRo = MyCombobox(CheckFrame)
        self.AppNaRo.grid(column=1, row=4, pady=5, padx=5, sticky=NW)
        self.RelNaRo = MyCombobox(CheckFrame)
        #RelNaRo.configure(state='readonly')
        self.RelNaRo.grid(column=1, row=5, pady=5, padx=5, sticky=NW)

        #Spinbox zum Check-Block
        self.ComSpin = MySpinDate(CheckFrame)
        self.ComSpin.grid(column=2, row=1, pady=5, padx=5, sticky=NW)
        self.Ch1Spin = MySpinDate(CheckFrame)
        self.Ch1Spin.grid(column=2, row=2, pady=5, padx=5, sticky=NW)
        self.Ch2Spin = MySpinDate(CheckFrame)
        self.Ch2Spin.grid(column=2, row=3, pady=5, padx=5, sticky=NW)
        self.AppSpin = MySpinDate(CheckFrame)
        self.AppSpin.grid(column=2, row=4, pady=5, padx=5, sticky=NW)
        self.RelSpin = MySpinDate(CheckFrame)
        self.RelSpin.grid(column=2, row=5, pady=5, padx=5, sticky=NW)

        #Radiobutton
        LangFrame = Frame(tkobj)
        LangFrame.grid(column=0, row=2, pady=5, padx=5, sticky=NW)
        lblSprache = MyLabel(LangFrame)
        lblSprache.set('Sprachausgabe PDF')
        lblSprache.grid(column=0, row=0, sticky=NW, pady=5, padx=5)
        self.radioSprache = MyRadioButton(LangFrame)
        self.radioSprache.grid(column=1, row=0, pady=5, padx=5, sticky=NW)
예제 #47
0
    def __init__(self, master):
        """Class builds GUI to control Waltz Telescope.
           Uses Tkinter for GUI functionality.
           Inherits from lx200commands.Lx200Commands class.
           This class provides functionality to talk to serial connection 
           using the lx200 protocol.
        """
        
        super().__init__()
        
        self.master = master
        master.title("Waltz Control Panel")
       
        #Store CET and UCT
        self.CET = ''
        self.UTC = ''
        
        #Store if telescope is waiting for slew to finish
        self.waiting=True
        
        ## Building up GUI Widgets ##
        
        #Menubars
        menubar=Menu(self.master)
        
        #Connection menu
        connectionmenu = Menu(menubar, tearoff=0)
        connectionmenu.add_command(label="Open Connection", command=self.open_connection_buttonclick)
        connectionmenu.add_command(label="Close Connection", command=self.close_connection_buttonclick)
        menubar.add_cascade(label="Connection", menu=connectionmenu)
        
        #settings_menu
        settings_menu=Menu(menubar, tearoff=0)
        settings_menu.add_command(label="Enable buttons",command=self.stop_waiting)
        settings_menu.add_command(label="Toggle Precision",command=super().toggle_precision)
        menubar.add_cascade(label="Settings",menu=settings_menu)
        
        
        
        #Pointing_stars_menu
        pointing_stars_menu=Menu(menubar, tearoff=0)
        pointing_stars_menu.add_command(label="Pointing Star", command=self.save_pointing_star)
        menubar.add_cascade(label="Save as", menu= pointing_stars_menu)
        
        #Special_positions_menu
        special_positions_menu=Menu(menubar, tearoff=0)
        special_positions_menu.add_command(label="Slew to Primary Mirror Position",command=self.primary_mirror_pos_buttonclick)
        special_positions_menu.add_command(label="Slew to Secondary Mirror Position",command=self.secondary_mirror_pos_buttonclick)
        special_positions_menu.add_command(label="Slew to Park Position",command=self.park_telescope_buttonclick)
        menubar.add_cascade(label="Special Positions",menu=special_positions_menu)
        
        
        #Show menubar
        self.master.config(menu=menubar)
        
        #Output frame
        output_frame=Frame(master)
        output_frame.grid(row=0,columnspan=3)

        self.LST_label = Label(output_frame,
                               font=('arial', 15, 'bold'),
                               text="LST")
        self.LST_label.grid(row=0,column=0)
        
        self.LST_display = Label(output_frame,
                                 font=('arial', 20, 'bold'),
                                 bg='light green')
        self.LST_display.grid(row=0, column=1,padx=10, pady=10)
        
        self.local_time_label= Label(output_frame,
                              font=('arial', 15, 'bold'),
                              text='LT')
        self.local_time_label.grid(row=0, column=3)
        
        self.local_time_display = Label(output_frame,
                                 font=('arial', 20, 'bold'),
                                 bg='light green')
        self.local_time_display.grid(row=0, column=4,padx=10,pady=10)
        
        self.UTC_label= Label(output_frame,
                              font=('arial', 15, 'bold'),
                              text='UTC')
        self.UTC_label.grid(row=0, column=5)
        
        self.UTC_display = Label(output_frame,
                                 font=('arial', 20, 'bold'),
                                 bg='light green')
        self.UTC_display.grid(row=0, column=6,padx=10,pady=10)
        
        
        
        self.RA_label= Label(output_frame,
                             font=('arial', 15, 'bold'),
                             text= "RA")
        self.RA_label.grid(row=1, column =0)
        
        self.RA_display= Label(output_frame,
                               font=('arial', 20, 'bold'), 
                               bg='light green')
        self.RA_display.grid(row=1, column =1)
        
        self.DEC_label= Label(output_frame,
                              font=('arial', 15, 'bold'),
                              text= "DEC")
        self.DEC_label.grid(row=1, column =3)
        
        self.DEC_display= Label(output_frame,
                                font=('arial', 20, 'bold'),
                                bg='light green')
        self.DEC_display.grid(row=1, column =4)
        
        self.HA_label= Label(output_frame,
                              font=('arial', 15, 'bold'),
                              text= "HA")
        self.HA_label.grid(row=1, column =5)
        
        self.HA_display= Label(output_frame,
                                    font=('arial', 20, 'bold'),
                                    bg='light green')
        self.HA_display.grid(row=1, column=6)
        
        #Interchange_frame
        #To interchange W<->E buttons and N<->S
        self.interchange_frame=Frame(master)
        self.interchange_frame.grid(row=1, column=0,pady=10)
        #Define Variables
        self.inter_WE=IntVar()
        self.inter_NS=IntVar()
        self.inter_NS_checkbox=Checkbutton(self.interchange_frame,
                                           text='N <> S',
                                           font=('arial', 10, 'bold'),
                                           variable=self.inter_NS,
                                           command=self.interchange_north_south)
        self.inter_NS_checkbox.grid(row=0,column=0,sticky='w',pady=5)
        
        
        self.inter_WE_checkbox=Checkbutton(self.interchange_frame,
                                           text='W <> E',
                                           font=('arial', 10, 'bold'), 
                                           variable=self.inter_WE,
                                           command=self.interchange_west_east)
        self.inter_WE_checkbox.grid(row=1,column=0,sticky='w',pady=5)
        
        
        
        #Control frame
        self.control_frame=Frame(master)
        self.control_frame.grid(row=1,column=1,pady=10)


        self.south_button = Button(self.control_frame,
                                   text="S",
                                   font=('arial', 20, 'bold'),
                                   bg='LightGrey',
                                   height = 1, 
                                   width = 2)
        self.south_button.grid(row=0,column=1)
        
        self.west_button = Button(self.control_frame,
                                  text="W",
                                  font=('arial', 20, 'bold'),
                                  bg='LightGrey',
                                  height = 1,
                                  width = 2)
        self.west_button.grid(row=1,column=0)
        
        self.east_button = Button(self.control_frame,
                                  text="E",
                                  font=('arial', 20, 'bold'),
                                  bg='LightGrey',
                                  height = 1,
                                  width = 2)
        self.east_button.grid(row=1,column=2)
        
        
        self.north_button = Button(self.control_frame,
                                   text="N",
                                   font=('arial', 20, 'bold'),
                                   bg='LightGrey',
                                   height = 1,
                                   width = 2)
        self.north_button.grid(row=2,column=1)
        
        self.stop_button = Button(self.control_frame,
                                  text="STOP",
                                  font=('arial',20, 'bold'),
                                  fg='White',
                                  bg='Red',
                                  activeforeground='Red',
                                  activebackground='White',
                                  command=super().stop_at_current_pos)
        self.stop_button.grid(row=3,column=0, columnspan=3, pady=10)

        #Radiobutton frame
        self.radiobutton_frame=Frame(master)
        self.radiobutton_frame.grid(row=1,column=2,pady=10)
        
        
        radiobutton_parameters=[('Slew',0,self.set_speed_max),
                                ('Find',1, self.set_speed_find),
                                ('Center',2, self.set_speed_center),
                                ('Guide',3, self.set_speed_guide)]
        
        self.speed=StringVar()
        #Initialize speed to guiding speed
        self.speed.set('Guide')
        
        for keyword, position, execute in radiobutton_parameters:
            self.speed_radiobutton= Radiobutton(self.radiobutton_frame,
                                                text=keyword,
                                                variable=self.speed,
                                                value=keyword,
                                                command=execute,
                                                font=('arial', 10, 'bold'))
            self.speed_radiobutton.grid(row=position,column=0,sticky=W)
        
        #Options Frame
        self.options_frame=Frame(master)
        self.options_frame.grid(row=0,column=3,padx=20)
     
        self.sync_button = Button(self.options_frame,
                                       text="Synchronize \n with Target",
                                       font=('arial', 12, 'bold'),
                                       bg='LightGrey',
                                       command=self.sync_yes_no,
                                       state='disabled')
        self.sync_button.grid(row=0,column=0,padx=5)
        
        
        
        
        #Target Frame
        self.target_frame=LabelFrame(master,
                                text='Select Target (apparent position)',
                                font=('arial', 15))
        self.target_frame.grid(row=1,rowspan=1,column=3,padx=20)
        
        self.HIP_label = Label(self.target_frame,
                               font=('arial', 15),
                               text="Hipparcos")
        self.HIP_label.grid(row=0,column=0)
        
        self.HIP_entry= Entry(self.target_frame,
                              font=('arial', 15))
        self.HIP_entry.grid(row=0, column=1,pady=10)
        
        
        self.target_ra_label = Label(self.target_frame,
                                     font=('arial', 15),
                                     text="RA \n [hh mm ss]")
        self.target_ra_label.grid(row=1,column=0)
        
        self.target_ra_entry= Entry(self.target_frame,
                                    font=('arial', 15))
        self.target_ra_entry.grid(row=1, column=1,pady=10)

        
        self.target_dec_label = Label(self.target_frame,
                                      font=('arial', 15),
                                      text="""DEC \n [°° mm ss]""")
        self.target_dec_label.grid(row=2,column=0)
        
        self.target_dec_entry= Entry(self.target_frame,
                                     font=('arial', 15))
        self.target_dec_entry.grid(row=2, column=1,pady=10)
        
        self.target_time_label= Label(self.target_frame,
                                     font=('arial', 15),
                                     text=" Obs \n Time")
        self.target_time_label.grid(row=0,column=2,padx=10)
        
        self.target_time_display=Label(self.target_frame,
                                    font=('arial', 15),
                                    bg='red',
                                    width=10)
        self.target_time_display.grid(row=0,column=3,pady=10)
        
        self.target_alt_label = Label(self.target_frame,
                                     font=('arial', 15),
                                     text="ALT")
        self.target_alt_label.grid(row=1,column=2,padx=10)
        
        self.target_alt_display= Label(self.target_frame,
                                    font=('arial', 15),
                                    bg='red',
                                    width=10)
        self.target_alt_display.grid(row=1, column=3,pady=10)
        
        self.target_az_label = Label(self.target_frame,
                                     font=('arial', 15),
                                     text="AZ")
        self.target_az_label.grid(row=2,column=2,padx=10)
        
        self.target_az_display= Label(self.target_frame,
                                    font=('arial', 15),
                                    bg='red',
                                    width=10)
        self.target_az_display.grid(row=2, column=3,pady=10)
        
        self.slew_target_button = Button(self.target_frame,
                                         text="Slew to Target",
                                         font=('arial', 15),
                                         bg='LightGrey',
                                         state='disabled',
                                         command=self.slew_to_target_buttonclick)
        self.slew_target_button.grid(row=3,columnspan=4)
        
        #Plot Frame
        self.plot_frame=Frame(master)
        self.plot_frame.grid(row=2,columnspan=4)
        #Add instance variables to store the plot and the different axes,
        #and positions globally
        self.canvas=False
        self.ax1=False
        self.star_plot=False
        self.traj_plot=False
        self.pos_plot=False
        self.ax2=False
        
        #At first check if serial connection is open (also contains initial commands)
        self._respond_to_connection_state()
        
        #Message box for Warning
        caution=("CAUTION: THIS IS A FIRST ATTEMPT TO CONTROL THE WALTZ TELESCOPE.\n"+
                 "BAD INPUTS OR CRASHES OF THE PROGRAM COULD BE HARMFUL TO THE TELESCOPE.\n"+
                 "DO NOT USE THIS PROGRAM ALONE AND ALWAYS PREPARE FOR STOPING MOVEMENTS "+ 
                 "OF THE TELESCOPE VIA THE EMERGENCY STOPS IN THE DOME!")
        messagebox.showwarning("Warning",message=caution,parent=master)
예제 #48
0
class MainGUI():
    def __init__(self, root):
        self.root = root
        self.create_gui()

    # Create the main window
    def create_gui(self):
        '''used to create GUI elements'''

        self.root.title("MangaReaDex v1.2 - By Nadhif")
        self.root.geometry("1000x1080")

        # Initialize the webdriver headless
        options = Options()
        options.add_argument("--headless")
        self.driver = webdriver.Firefox(options=options)

        # Make frame for every different GUI element
        self.header = Frame(self.root, height=100, width=900)
        self.lefthead = Frame(self.header,
                              height=80,
                              width=465,
                              highlightbackground="green",
                              highlightcolor="green",
                              highlightthickness=1)
        self.righthead = Frame(self.header,
                               height=80,
                               width=465,
                               highlightbackground="green",
                               highlightcolor="green",
                               highlightthickness=1)
        self.prighthead = Frame(self.righthead, height=35, width=465)
        self.body = Frame(self.root,
                          height=900,
                          width=930,
                          highlightbackground="blue",
                          highlightcolor="blue",
                          highlightthickness=1)
        self.footer = Frame(self.root,
                            height=20,
                            width=930,
                            highlightbackground="red",
                            highlightcolor="red",
                            highlightthickness=1)

        # Freeze the frame so it doesn't shrink
        self.header.pack_propagate(False)
        self.body.pack_propagate(False)
        self.lefthead.pack_propagate(False)
        self.righthead.pack_propagate(False)
        self.footer.pack_propagate(False)

        # Put all the frames inside the main window
        self.header.pack()
        self.body.pack()
        self.footer.pack()
        self.lefthead.grid(row=0, column=0)
        self.righthead.grid(row=0, column=1)
        self.prighthead.pack(side=BOTTOM)

        # Initialize the manga object (Canvas)
        self.manga = Manga(self.body,
                           width=907,
                           height=1200,
                           scrollregion=(0, 0, 900, 1300),
                           driver=self.driver)

        # Make labels and place them inside the window
        manga_label = Label(self.lefthead,
                            text="Enter your manga title",
                            font=(22))
        chapter_label = Label(self.righthead,
                              text="Pick your chapter",
                              font=(14))
        page_label = Label(self.prighthead, text="Page :", font=(14))

        manga_label.pack()
        chapter_label.pack()

        # Make boxes as Manga's attribute and place them inside the window
        self.manga.manga_box = Combobox(self.lefthead, width=50)
        self.manga.chapter_box = Combobox(self.righthead,
                                          width=50,
                                          state='readonly')
        self.manga.page_box = Combobox(self.prighthead,
                                       width=10,
                                       state='readonly')

        self.manga.manga_box.pack()
        self.manga.chapter_box.pack()

        page_label.pack(side=LEFT)
        self.manga.page_box.pack(side=RIGHT)

        # Make buttons and place them inside the window
        left_button = Button(self.footer,
                             text="<-",
                             command=self.prev_page,
                             width=51,
                             font=(16))
        right_button = Button(self.footer,
                              text="->",
                              command=self.next_page,
                              width=51,
                              font=(16))
        search_button = Button(self.lefthead,
                               text="Search",
                               command=self.update_manga_list)

        left_button.pack(side=LEFT)
        right_button.pack(side=RIGHT)
        search_button.pack()

        # Make a scrollbar for the canvas and pack the canvas
        scrollbar = Scrollbar(self.body, orient=VERTICAL)

        self.manga.config(yscrollcommand=scrollbar.set)
        self.manga.pack(side=LEFT)

        # Create a title screen image and show it in the canvas
        img = ImageTk.PhotoImage(file="mangareadex.png")
        self.manga.image = self.manga.create_image(450, 650, image=img)
        self.manga.img = img

        # Pack the scrollbar
        scrollbar.config(command=self.manga.yview)
        scrollbar.pack(side=RIGHT, fill=Y)

        # Make the controls
        self.controller()

    def controller(self):
        '''make the necessary keyboard and mouse controls'''

        # Bind the boxes to get elements
        self.manga.manga_box.bind('<Return>', self.update_manga_list)
        self.manga.manga_box.bind('<<ComboboxSelected>>',
                                  self.update_chapter_list)
        self.manga.chapter_box.bind('<<ComboboxSelected>>',
                                    self.update_page_list)
        self.manga.page_box.bind('<<ComboboxSelected>>', self.jump_to)

        # Bind the mouse controls
        self.root.bind('<MouseWheel>', self.mousewheel)
        self.manga.bind('<Button-1>', self.click)

        # Bind the keyboard controls
        self.root.bind('<Right>', self.next_page)
        self.root.bind('<Left>', self.prev_page)
        self.root.bind('<Up>', self.scroll_up)
        self.root.bind('<Down>', self.scroll_down)

    def mousewheel(self, event):
        '''event for mousewheel scroll'''
        self.manga.yview_scroll(-1 * (int(event.delta / 120)), 'units')

    def scroll_up(self, event):
        '''event for keyboard press up'''
        self.manga.yview_scroll(-1, 'units')

    def scroll_down(self, event):
        '''event for keyboard press down'''
        self.manga.yview_scroll(1, 'units')

    def update_manga_list(self, event=None):
        # Call find_manga in manga object and populate box
        self.title_dir = self.manga.find_manga(self.manga.manga_box.get())
        self.manga.manga_box['values'] = [
            title for title in self.title_dir.keys()
        ]

    def update_chapter_list(self, event):
        # Clear chapter and page box
        self.manga.chapter_box.set('')
        self.manga.page_box.set('')
        self.manga.page_box['values'] = []

        title = self.manga.manga_box.get()
        href = self.title_dir[title]

        # Call find_chapter in manga object and populate the box
        self.chapter_dir = self.manga.find_chapter(href)
        self.manga.chapter_box['values'] = [
            chapter for chapter in self.chapter_dir.keys()
        ]

    def update_page_list(self, event):
        # Set the page to be the first page
        self.manga.current_page = 1
        self.manga.page_box.set(1)

        chapter = self.manga.chapter_box.get()
        cha_list = [chapter for chapter in self.chapter_dir.keys()]
        self.manga.current_chapter = cha_list.index(chapter)
        id = self.chapter_dir[chapter]

        # Call find_image in manga object and populate the box
        self.page_dir = self.manga.find_image(id)
        self.manga.page_box['values'] = [num for num in self.page_dir.keys()]

    def click(self, event):
        '''event for click on the page'''
        if int(event.x) < 465:
            self.prev_page()
        else:
            self.next_page()

    def next_page(self, event=None):
        '''event for keyboard press right'''
        try:
            self.manga.change_page(1)
        except Exception:
            pass

    def prev_page(self, event=None):
        '''event for keyboard press left'''
        try:
            self.manga.change_page(-1)
        except Exception:
            pass

    def jump_to(self, event):
        '''event for changing page via the page_box'''
        page = self.manga.page_box.get()
        self.manga.current_page = int(page)
        self.manga.change_image()

    def mainloop(self):
        # If you close the gui window
        self.root.protocol("WM_DELETE_WINDOW", self.quit)
        self.root.mainloop()

    def quit(self):
        # Destroy the driver and the root
        self.root.destroy()
        self.driver.quit()
예제 #49
0
from PIL import ImageTk, Image
from tkinter import Frame

root = Tk()
root.title("image")
root.iconbitmap(
    "C:/Users/kalsa/Documents/python gui codemy youtube/icon_0m1_icon.ico")
root.geometry("400x400")

resizeframe = Frame(root,
                    width=10,
                    height=10,
                    bd=1,
                    bg="#faa045",
                    relief=SUNKEN)
resizeframe.grid(row=0, column=1, padx=5, pady=5, sticky=NW)

controllerframe = LabelFrame(root, text="sliders")
controllerframe.grid(row=0, column=0, padx=10, pady=10, sticky=N)


def slide(xvalue):
    resizeframe.configure(height=int(xvalue))


def click():

    yvalue = horizontalslider.get()
    resizeframe.configure(width=int(yvalue))

예제 #50
0
addRecord = Button(frame1, text="Nowy Rekord", command=addRec)
deleteRecord = Button(frame1, text="Usuń Rekord gdzie ->", command=delRec)

record = Listbox(frame1, height=4)
record.insert(1, "Id")
record.insert(2, "Imię")
record.insert(3, "Nazwisko")
record.insert(4, "Wiek")

l = Label(frame1, text="=")
where = Entry(frame1)

name.grid(row=0, column=0)
dbName.grid(row=0, column=1)
user.grid(row=0, column=2)
userName.grid(row=0, column=3)
surname.grid(row=0, column=4)
userSurname.grid(row=0, column=5)
age.grid(row=0, column=6)
userAge.grid(row=0, column=7)
createDb.grid(row=1, column=0)
disconnect.grid(row=1, column=1)
addRecord.grid(row=1, column=2)
deleteRecord.grid(row=1, column=3)
record.grid(row=1, column=4)
l.grid(row=1, column=5)
where.grid(row=1, column=6)
frame1.grid(row=0)
frame.grid(row=2)

mainloop()
예제 #51
0
class StockGui(object):
    """define StockGui class"""
    def __init__(self, window):
        """Setup GUI on given window"""

        self.header_frame = Frame(window,
                                  bg='deepskyblue',
                                  width=600,
                                  height=70)
        self.header_frame.grid(row=0, column=0, columnspan=2)

        self.main_frame = Frame(window,
                                bg='white',
                                highlightbackground="white",
                                highlightthickness=20,
                                width=600,
                                height=700)
        self.main_frame.grid(row=1, column=1, rowspan=2)

        # Header Frame
        self.header_frame.grid_propagate(0)
        self.header_frame.grid_rowconfigure(0, weight=1)
        self.header_frame.grid_columnconfigure(1, weight=1)

        self.label_header_text_2 = tk.Label(self.header_frame,
                                            text='ABC classification results',
                                            bg='deepskyblue',
                                            fg='white',
                                            font=("Arial", 28))
        self.label_header_text_2.grid(row=0, column=1)

        # Main Frame
        self.main_frame.grid_propagate(0)
        self.main_frame.grid_rowconfigure(1, weight=1)
        self.main_frame.grid_columnconfigure(1, weight=1)

        #Create 2 frames inside the main frame
        self.top_main_frame = Frame(self.main_frame,
                                    bg='white',
                                    highlightbackground="#5f9cad",
                                    highlightthickness=2,
                                    width=560,
                                    height=120)
        self.top_main_frame.grid(row=0)
        self.top_main_frame.grid_propagate(0)
        self.top_main_frame.grid_rowconfigure(0, weight=1)
        self.top_main_frame.grid_columnconfigure(2, weight=1)

        self.bottom_main_frame = Frame(self.main_frame,
                                       bg='white',
                                       width=560,
                                       height=580)
        self.bottom_main_frame.grid(row=1, sticky='n')
        self.bottom_main_frame.grid_propagate(0)
        self.bottom_main_frame.grid_rowconfigure(0, weight=1)
        self.bottom_main_frame.grid_columnconfigure(2, weight=1)

        # create the widgets for the top_main_frame
        self.btn_stock_info = tk.Button(self.top_main_frame,
                                        text='See my stock status',
                                        command=self.stock_status)

        self.btn_stock_info.grid(row=0, column=2)

        self.label_stock_info = tk.Label(self.top_main_frame,
                                         text="",
                                         bg='white')
        self.label_stock_info.grid(row=1, column=2, sticky='n')

        # create the widgets for the bottom_main_frame
        self.label_threshold = tk.Label(
            self.bottom_main_frame,
            text='Please input your threshold for each class',
            bg='white')
        self.label_threshold.grid(row=0, column=0, pady=5)

        template_threshold = "For example: class A accounts for 70% of stock value (please input: 0.7),\nclass B accounts for 25% of stock value (input: 0.25) and class C accounts for the rest 5% of stock value"
        self.label_threshold_note = tk.Label(self.bottom_main_frame,
                                             text=template_threshold,
                                             bg='white')
        self.label_threshold_note.grid(row=1, column=0, pady=5)

        self.label_class_a = tk.Label(self.bottom_main_frame,
                                      text='Class A',
                                      bg='white')
        self.label_class_a.grid(row=2, column=0, pady=5)

        self.entry_class_a = tk.Entry(self.bottom_main_frame, width=20)
        self.entry_class_a.grid(row=3, column=0)

        self.label_class_b = tk.Label(self.bottom_main_frame,
                                      text='Class B',
                                      bg='white')
        self.label_class_b.grid(row=4, column=0, pady=5)

        self.entry_class_b = tk.Entry(self.bottom_main_frame, width=20)
        self.entry_class_b.grid(row=5, column=0)

        self.label_class_c = tk.Label(self.bottom_main_frame,
                                      text='Class C: the rest',
                                      bg='white')
        self.label_class_c.grid(row=6, column=0, pady=5)

        self.btn_ABC_classification = tk.Button(self.bottom_main_frame,
                                                text='Stock classification',
                                                command=self.ABC_results)
        self.btn_ABC_classification.grid(row=7, column=0, pady=5)

        self.label_result = tk.Label(self.bottom_main_frame,
                                     text='Results for stock classification:',
                                     bg='white')
        self.label_result.grid(row=8, column=0, pady=5)

        self.label_message = tk.Label(self.bottom_main_frame,
                                      text='',
                                      bg='white',
                                      anchor=W,
                                      justify=LEFT)
        self.label_message.grid(row=9, column=0)

        self.btn_savefile = tk.Button(self.bottom_main_frame,
                                      text='Export ABC classification file',
                                      command=self.save_file)
        self.btn_savefile.grid(row=16, column=0, pady=5)

        self.btn_plotgraph = tk.Button(self.bottom_main_frame,
                                       text='View Pareto chart',
                                       command=self.plot_graph)
        self.btn_plotgraph.grid(row=17, column=0, pady=10)

    def stock_status(self):
        """The event handler for clicks on the button stock_status
        The purpose: to see current stock status based on descriptive analysis"""
        stock_info = Descriptive_stats("Data_stock.csv")
        self.label_stock_info.configure(text=stock_info)

    def ABC_results(self):
        """The event handler for clicks on the ABC results
        Purpose: to get threshold values from user input and print results after classification
        This event handler also handling Exception in case user input wrong"""

        if float(self.entry_class_a.get()) >= 1 or float(
                self.entry_class_b.get()) > 1:
            self.label_message.configure(
                text="ERROR: Threshold value must less than 1!", fg='red')
        elif float(self.entry_class_a.get()) + float(
                self.entry_class_b.get()) > 1:
            self.label_message.configure(
                text=
                "ERROR: Sum of threshold values for class A, B, C must be equal to 1!",
                fg='red')
        else:
            ABC_stock = ABC_classification("Data_stock.csv",
                                           float(self.entry_class_a.get()),
                                           float(self.entry_class_b.get()))
            self.label_message.configure(text=ABC_stock, fg='blue')

    def save_file(self):
        """The event handler for clicks on the button save file
        The output will be a new Excel file with result of ABC classification for each item"""

        ABC_stock = ABC_classification("Data_stock.csv",
                                       float(self.entry_class_a.get()),
                                       float(self.entry_class_b.get()))
        ABC_stock.export_results()

    def plot_graph(self):
        """The event handler for clicks on the button plot_graph
        Purpose: to plot the Pareto chart
        """

        import matplotlib.pyplot as plt
        ABC_stock = ABC_classification("Data_stock.csv",
                                       float(self.entry_class_a.get()),
                                       float(self.entry_class_b.get()))
        df = ABC_stock.new_dataframe()
        x = np.arange(0, 416)
        y = df["Cumulative spending percentage"]
        plt.plot(x, y)
        plt.xlabel('Number of items')
        plt.ylabel('Weekly spending')
        plt.title("Pareto chart about Accumulated amount of value")
        plt.legend()
        plt.grid(True)
        plt.show()
예제 #52
0
class Viewer(Frame):
    files = None
    folder = None

    def __init__(self, parent):
        Frame.__init__(self, parent)
        # Frame for Listbox and Scrollbar
        self.frm = Frame(self)
        self.frm.grid(row=2, sticky=NW)

        # Button and Labels
        self.file_path = Button(self,
                                text="Choose Folder",
                                command=self.set_dcm_files)
        self.file_path.grid(row=0)

        self.msg_label = Label(
            self, text="Double click the folder \n and then click OK")
        self.msg_label.grid(row=1)

        self.info = StringVar(self)
        self.info_label = Label(self.frm, textvariable=self.info)
        self.info_label.grid(row=3)

        # Declaring Scrollbar and Listbox
        self.sbar = Scrollbar(self.frm, orient='vertical')
        self.dcm_list = Listbox(self.frm,
                                width=20,
                                yscrollcommand=self.sbar.set)
        self.dcm_list.bind("<<ListboxSelect>>", self.view_selected_item)
        self.sbar.config(command=self.dcm_list.yview)

        self.dcm_list.grid(row=0, column=0)
        self.sbar.grid(row=0, column=1, sticky=NS)

    # Sets dcm files and populates Listbox
    def set_dcm_files(self):
        self.folder = askdirectory()
        self.files = os.listdir(self.folder)
        self.files.sort()
        self.populate_list()

    # Populates the Listbox
    def populate_list(self):
        self.dcm_list.delete(0, 'end')
        for f in self.files:
            self.dcm_list.insert(END, f)

    # Views the selected item from the Listbox
    def view_selected_item(self, event):
        file = self.dcm_list.get(self.dcm_list.curselection())
        try:
            if file.split(".")[1] == 'dcm':
                self.show_info(file)
                dataset = pydicom.read_file(self.folder + "/" + file)
                plt.imshow(dataset.pixel_array, cmap=plt.cm.bone)
                plt.show()
            else:
                self.show_info(f"{file} is not a .dcm file")
        except IndexError:
            self.show_info(f'{file} is a directory')

    # Display info below the Listbox
    def show_info(self, text=""):
        self.info.set(text)
        self.info_label.grid(row=3)
예제 #53
0
class MQ(ttk.Frame):
    # The  gui and functions.

    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.movieLabeltext = StringVar()
        self.moviefile = ""
        self.outfolder = ""
        self.fileloaded = False
        self.folderloaded = False
        self.movieLabeltext.set("<none>")
        self.movieDuration = 0.0
        self.root = parent
        userDir = os.path.expanduser('~')
        self.path_OSX = os.path.join(userDir, 'Library', 'Application Support',
                                     'Movie Quantizer')
        self.init_gui()

    def on_quit(self):
        # Exits program.
        sys.exit()

    def go_nogo(self):
        # check if ffmpeg is installed
        if (self.checkifffmpeg() == False):
            answer = mbox.askyesno(
                "ERROR", "This application needs ffmpeg "
                "installed in the system!\n\n"
                "Do you want to install it?")
            if answer == True:
                root.update()
                self.tryGettingffmpeg()
                return
            self.on_quit()
            return

    # Get the movie file
    def loadmovie(self):
        opts = {}
        opts['filetypes'] = [
            ('Supported types',
             ("*.mov", "*.mp4", "*.mpg", "*.avi", "*.h264", "*.mpeg", "*.mkv",
              "*.m4a", "*.3gp", "*.ogg", "*.wmv", "*.vob"))
        ]
        self.moviefile = filedialog.askopenfilename(**opts)
        if self.moviefile != "":
            self.movie_button['text'] = os.path.basename(self.moviefile)
            self.fileloaded = True
            self.checkDuration()
            self.interval_spin['state'] = 'normal'
            self.calculate_images()
        if (self.fileloaded and self.folderloaded) == True:
            self.action_button['state'] = 'normal'

        # Get informations and duration of the movie
    def checkDuration(self):
        cmd = "'" + FFMPEG_BIN + "' -i " + "'" + self.moviefile + "'" + " 2>&1 | grep Duration"
        c = os.popen(cmd)
        out = c.read()
        self.answer_label['text'] = "Movie info:" + out
        c.close()
        dur = out.index("Duration:")
        duration = out[dur + 10:dur + out[dur:].index(",")]
        hh, mm, ss = map(float, duration.split(":"))
        self.movieDuration = (hh * 60 + mm) * 60 + ss

    def selectFolder(self):
        self.outfolder = filedialog.askdirectory()
        if self.outfolder != "":
            self.folder_button['text'] = os.path.basename(self.outfolder)
            self.folderloaded = True
        if (self.fileloaded and self.folderloaded) == True:
            self.action_button['state'] = 'normal'

    def checkifffmpeg(self):
        global FFMPEG_BIN
        try:
            devnull = open(os.devnull)
            subprocess.call(['ffmpeg', '-version'],
                            stderr=subprocess.STDOUT,
                            stdout=devnull)
            FFMPEG_BIN = "ffmpeg"
        except (OSError, ValueError, subprocess.CalledProcessError):
            try:
                subprocess.call([self.path_OSX + '/ffmpeg.osx', '-version'],
                                stderr=subprocess.STDOUT,
                                stdout=devnull)
                FFMPEG_BIN = self.path_OSX + "/ffmpeg.osx"
            except (OSError, ValueError, subprocess.CalledProcessError):
                return False
        self.set_ffmpegversion()
        return True

    def tryGettingffmpeg(self):
        global FFMPEG_BIN
        self.progLabelText = "Downloading ffmpeg. Please wait.."
        self.progress_win()
        root.update()
        t1 = threading.Thread(target=get_ffmpeg, args=(self, ))
        t1.start()
        FFMPEG_BIN = self.path_OSX + "/ffmpeg.osx"

    def set_ffmpegversion(self):
        cmd = [FFMPEG_BIN, " -version"]
        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        out, err = p.communicate()
        lines = out.splitlines()
        ver = lines[0].decode('utf8').split('version',
                                            1)[-1].split('Copyright')[0]
        self.answer_label['text'] = "Movie Quantizer v." + \
            VERSION + " - using ffmpeg v." + ver

    def calculate_images(self):
        images = int(
            float(self.movieDuration) / float(self.interval_spin.get()))
        self.images_nrs['state'] = 'normal'
        self.images_nrs.delete(0, 'end')
        self.images_nrs.insert(0, images)
        self.images_nrs['state'] = 'disabled'

    def execute(self):
        # Grab the images
        format = self.image_formatbox.get()
        result = (os.system('ls "' + self.outfolder + '"/img*.' + format))

        if result == 0:
            answer = mbox.askyesno(
                "Warning",
                "Folder already contains image files, that will be overwritten. Proceed?"
            )
            if answer == False:
                return
            root.update()
        self.progLabelText = "Processing images. Please wait.."
        self.progress_win()
        t1 = threading.Thread(target=self.exec_thread)
        t1.start()

    def exec_thread(self):
        format = self.image_formatbox.get()
        if format == "tiff":
            pixformat = " -pix_fmt rgb565 "
        else:
            pixformat = " "
        fps = float(1 / float(self.interval_spin.get()))
        cmd = "'"+FFMPEG_BIN + "' -i '" + self.moviefile + "'" + pixformat + "-vf fps=" +\
            str(fps) + " '" + self.outfolder + "'/img%04d." + format + " 2>&1"
        try:
            subprocess.check_call(cmd, shell=True)
            self.popup.destroy()
            cnt = subprocess.check_output('ls "' + self.outfolder + '"/img*.' +
                                          format + ' | wc -l',
                                          shell=True)
            self.answer_label['text'] = "Result: " +\
                (cnt.decode('ascii').strip()) +\
                " image files have been successfully created in " + self.outfolder
            return
        except subprocess.CalledProcessError as e:
            self.answer_label['text'] = e.output
            self.popup.destroy()
            return

    def progress_win(self):
        self.popup = Toplevel(self)
        progress_bar = ttk.Progressbar(self.popup,
                                       orient='horizontal',
                                       mode='determinate',
                                       takefocus=True,
                                       length=400)
        progress_bar.grid(row=1, column=0, sticky="we")

        self.progLabel = ttk.Label(self.popup,
                                   text=self.progLabelText).grid(column=0,
                                                                 row=0,
                                                                 sticky="we")
        self.popup.attributes('-topmost', True)
        progress_bar.start(50)

    def init_gui(self):
        # Builds GUI.
        self.root.title('Movie Quantizer')
        self.root.option_add('*tearOff', 'FALSE')

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

        self.menubar = tkinter.Menu(self.root)

        self.menu_file = tkinter.Menu(self.menubar)
        self.menu_file.add_command(label='Open Movie File...',
                                   command=self.loadmovie)
        self.menu_file.add_command(label='Select Output Folder...',
                                   command=self.selectFolder)
        self.menu_file.add_command(label='Exit', command=self.on_quit)

        self.menubar.add_cascade(menu=self.menu_file, label='File')

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

        self.movie_button = ttk.Button(self,
                                       text='Select',
                                       command=self.loadmovie)
        self.movie_button.grid(column=1, row=2)

        self.interval_spin = Spinbox(self,
                                     from_=0.5,
                                     to=20.0,
                                     increment=0.5,
                                     width=4,
                                     fg="red",
                                     command=self.calculate_images,
                                     state='disabled')
        self.interval_spin.grid(column=1, row=3, sticky="e")

        self.folder_button = ttk.Button(self,
                                        text='Select',
                                        command=self.selectFolder)
        self.folder_button.grid(column=3, row=2)

        self.images_nrs = ttk.Entry(self, text='', width=5, state='disabled')
        self.images_nrs.grid(column=3, row=3, sticky="e")

        self.box_value = StringVar()
        self.image_formatbox = ttk.Combobox(self,
                                            textvariable=self.box_value,
                                            state='readonly',
                                            width=4,
                                            justify='center')
        self.image_formatbox['values'] = ("jpg", "tiff")
        self.image_formatbox.current(0)
        self.image_formatbox.grid(column=1, row=4, sticky="w")

        self.action_button = ttk.Button(self,
                                        text='Grab Images',
                                        command=self.execute,
                                        state='disabled')
        self.action_button.grid(column=0, row=5, columnspan=4)

        self.answer_frame = Frame(self, height=300, background="white")

        self.answer_frame.grid(column=0, row=6, columnspan=4, sticky='nesw')

        self.answer_label = Message(self.answer_frame,
                                    text='',
                                    justify='center',
                                    width=600)
        self.answer_label.grid(column=0, row=0)

        # Labels that remain constant throughout execution.
        ttk.Label(self, text=' ').grid(column=0, row=0, columnspan=4)
        ttk.Label(self, text='Movie File:').grid(column=0, row=2, sticky='w')
        ttk.Label(self, text='Output Folder:').grid(column=2,
                                                    row=2,
                                                    sticky='w')
        ttk.Label(self, text="Grab a frame each (sec.):").grid(column=0,
                                                               row=3,
                                                               sticky='w')
        ttk.Label(self, text="Nr. of images:").grid(column=2,
                                                    row=3,
                                                    sticky='w')
        ttk.Label(self, text="Images format:").grid(column=0,
                                                    row=4,
                                                    sticky='w')

        for child in self.winfo_children():
            child.grid_configure(padx=7, pady=7)
예제 #54
0
    draw.polygon([ST0[0], ST0[1], 0, HEIGHT - 1, WIDTH - 1, HEIGHT - 1],
                 fill=LIGHT)
    draw.polygon([ST0[0], ST0[1], ST0[0], 0, 0, HEIGHT - 1], fill=DARK)
    draw.polygon([ST0[0], ST0[1], WIDTH - 1, HEIGHT - 1, ST0[0], 0],
                 fill=MEDIUM)
    sliderp = ImageTk.PhotoImage(imp)

    style = Style()
    style.theme_settings(
        'default', {
            'Horizontal.Scale.trough': {
                "element create": ('image', trough, {
                    'border': 0,
                    'sticky': 'wes'
                })
            },
            'Horizontal.Scale.slider': {
                "element create": ('image', slider, ('pressed', sliderp), {
                    'border': 3,
                    'sticky': 'n'
                })
            }
        })

    style.theme_use('default')

    fr = Frame(root)
    fr.grid(row=0, column=0, sticky='nsew')
    YiqSelect(fr)
    root.mainloop()
예제 #55
0
from tkinter import Tk, Frame, StringVar, Entry, Label, OptionMenu, Button, END, Spinbox
import random
import math

root = Tk()

root.title('Happy Number')
root.geometry('600x400')

frame = Frame(root,bd=10)
frame.grid(column=0,row=0)

numbers_label = Label(frame,width=25,text='The first 8 Happy Numbers are: ')
number1_input = Entry(frame,width=5,justify='center')
number2_input = Entry(frame,width=5,justify='center')
number3_input = Entry(frame,width=5,justify='center')
number4_input = Entry(frame,width=5,justify='center')
number5_input = Entry(frame,width=5,justify='center')
number6_input = Entry(frame,width=5,justify='center')
number7_input = Entry(frame,width=5,justify='center')
number8_input = Entry(frame,width=5,justify='center')

numbers_label.grid(row=0,column=0)
number1_input.grid(row=0,column=1)
number2_input.grid(row=0,column=2)
number3_input.grid(row=0,column=3)
number4_input.grid(row=0,column=4)
number5_input.grid(row=0,column=5)
number6_input.grid(row=0,column=6)
number7_input.grid(row=0,column=7)
number8_input.grid(row=0,column=8)
class PiAudio(tkinter.Tk):
    def __init__(self):
        Tk.__init__(self)
        self.nom_carte = "sysdefault:CARD=U0x46d0x825"
        self.fichier_courant = None
        self.stop_thread = False
        self.options_fichier = {"filetypes": [("Fichiers .wav", ".wav")]}
        self.creer_composant()
        self.mainloop()

    def creer_composant(self):
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.frame_haut = Frame(self)
        self.frame_haut.grid(row=0)
        self.frame_bas = Frame(self)
        self.frame_bas.grid(row=1)
        self.bouton_ouvrir = Button(self.frame_haut,
                                    text="Lire\nun enregistrement",
                                    command=lambda: self.ouvrir())
        self.bouton_ouvrir.grid(row=0, column=0)
        self.bouton_enreg_sous = Button(
            self.frame_haut,
            text="Enregistrer\ndu son",
            command=lambda: self.enregistrer_sous())
        self.bouton_enreg_sous.grid(row=0, column=1)
        self.lire_image = PhotoImage(file="resources/lire.png"),
        self.bouton_lire = Button(self.frame_bas,
                                  image=self.lire_image,
                                  command=lambda: self.lire())
        self.bouton_lire.grid(row=1, column=0)
        self.bouton_lire.configure(state="disabled")
        self.stop_image = PhotoImage(file="resources/stop.png"),
        self.bouton_stop = Button(self.frame_bas,
                                  image=self.stop_image,
                                  command=lambda: self.stop())
        self.bouton_stop.grid(row=1, column=1)
        self.bouton_stop.configure(state="disabled")
        self.enreg_image = PhotoImage(file="resources/enreg.png"),
        self.bouton_enreg = Button(self.frame_bas,
                                   image=self.enreg_image,
                                   command=lambda: self.enregistrer())
        self.bouton_enreg.grid(row=1, column=2)
        self.bouton_enreg.configure(state="disabled")
        self.title(self.__class__.__name__)

    def ouvrir(self):
        fichier = askopenfilename(**self.options_fichier)
        if fichier:
            self.fichier_courant = fichier
            self.bouton_lire.configure(state="active")
            self.bouton_stop.configure(state="active")
            self.bouton_enreg.configure(state="disabled")

    def enregistrer_sous(self):
        fichier = asksaveasfilename(**self.options_fichier)
        if fichier:
            self.fichier_courant = fichier
            self.bouton_lire.configure(state="disabled")
            self.bouton_stop.configure(state="active")
            self.bouton_enreg.configure(state="active")

    def lire(self):
        self.stop_thread = False
        t = threading.Thread(target=self._lire)
        t.start()

    def _lire(self):
        with wave.open(self.fichier_courant, "rb") as w:
            output = alsaaudio.PCM()
            output.setchannels(w.getnchannels())
            output.setrate(w.getframerate())
            output.setformat(alsaaudio.PCM_FORMAT_S16_LE)
            output.setperiodsize(1024)
            self.stop_thread = False
            while True:
                data = w.readframes(320)
                if not data or self.stop_thread:
                    break
                output.write(data)

    def stop(self):
        self.stop_thread = True
        self.bouton_lire.configure(state="active")
        self.bouton_enreg.configure(state="active")

    def enregistrer(self):
        self.stop_thread = False
        self.bouton_lire.configure(state="disabled")
        self.bouton_enreg.configure(state="disabled")
        t = threading.Thread(target=self._enregistrer)
        t.start()

    def _enregistrer(self):
        entree = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK,
                               self.nom_carte)
        entree.setchannels(1)
        entree.setrate(44100)
        entree.setformat(alsaaudio.PCM_FORMAT_S16_LE)
        entree.setperiodsize(1024)
        with wave.open(self.fichier_courant, "w") as w:
            w.setnchannels(1)
            w.setsampwidth(2)
            w.setframerate(44100)
            while True:
                _, data = entree.read()
                w.writeframes(data)
                if self.stop_thread:
                    break
예제 #57
0
        self.varYear.set(today.year)
        self.varMonth.set(today.month)
        self.varDay.set(today.day)


'''Programmstart'''

if __name__ == "__main__":
    root = Tk()
    root.title('Test Date')
    root.geometry('200x150')

    #myspindate = MySpinDate(root)
    s1 = Frame(root)
    s1.grid(column=0, row=0)

    ComSpin = MySpinDate(root, today=True)
    ComSpin.grid(column=2, row=1, pady=5, padx=5, sticky=NW)
    Ch1Spin = MySpinDate(root)
    Ch1Spin.grid(column=2, row=2, pady=5, padx=5, sticky=NW)
    Ch2Spin = MySpinDate(root)
    Ch2Spin.grid(column=2, row=3, pady=5, padx=5, sticky=NW)
    AppSpin = MySpinDate(root)
    AppSpin.grid(column=2, row=4, pady=5, padx=5, sticky=NW)
    RelSpin = MySpinDate(root)
    RelSpin.grid(column=2, row=5, pady=5, padx=5, sticky=NW)
    RelSpin.set([1999, 12, 31])

    root.mainloop()
예제 #58
0
runbtn.pack(side=LEFT, padx=5)
quitbtn.pack(side=LEFT, padx=5)

filebtns = Frame(rightbtns)
openbtn = Button(filebtns,
                 text="Open program",
                 command=lambda: open_program(textarea))
savebtn = Button(filebtns,
                 text="Save program",
                 command=lambda: save_program(textarea))
openbtn.pack(side=LEFT, padx=5)
savebtn.pack(side=LEFT, padx=5)

browserbuttons.pack(side=LEFT, padx=10)
filebtns.pack(side=LEFT, padx=10)
rightbtns.grid(row=1, column=1, sticky=S, padx=10, pady=10)

csvarea = Frame(top)
pluggy = Image.open(r'./pluggy.png').convert("RGBA").resize((115, 125))
img = ImageTk.PhotoImage(pluggy)
plabel = Label(csvarea, image=img)
plabel.img = img
plabel.pack(padx=10, pady=10)
loadtitle = Label(csvarea, text="CSV status", font="TkDefaultFont 16 bold")
loadtitle.pack(fill="y", expand=True)
#plabel.bind("<Button-1>", trap)
csvstatus = Label(csvarea, textvariable=loadstatus)
csvstatus.pack()
availfields = Label(csvarea, textvariable=available)
availfields.pack(fill="y", expand=True)
예제 #59
0
class App(Tk):
    def __init__(self, *args, **kwargs):
        '''
        the ui stuff
        '''
        super().__init__(*args, **kwargs)
        
        self.color = 'blue'
        
        self.winfo_toplevel().title('Judgy Hexagon')

        #Menu for a bit of documentation and help
        self.menu = Menu(self)
        self.menu.add_command(label='Change Color', command=self.change_color)
        self.menu.add_command(label='Help', command=self.help)
        self.menu.add_command(label='People', command=self.people)
        self.config(menu=self.menu)
        


        #the main canvas to show the hexagon
        self.canvas = Canvas(self, height=566, width=800)
        self.canvas.grid(row=1, column=1)

        
        #frame to put all the sliders in
        self.sf = Frame(self)
        self.sf.grid(row=1, column=3)

        #entries for the trait names (with default values)
        self.sl1 = Entry(self.sf)
        self.sl1.grid(row=0, column=0)
        self.sl1.insert(END, 'IQ')
        self.sl2 = Entry(self.sf, text='EQ')
        self.sl2.grid(row=1, column=0)
        self.sl2.insert(END, 'EQ')
        self.sl3 = Entry(self.sf)
        self.sl3.grid(row=2, column=0)
        self.sl3.insert(END, 'Attractiveness')
        self.sl4 = Entry(self.sf)
        self.sl4.grid(row=3, column=0)
        self.sl4.insert(END, 'Personality')
        self.sl5 = Entry(self.sf)
        self.sl5.grid(row=4, column=0)
        self.sl5.insert(END, 'Athleticism')
        self.sl6 = Entry(self.sf)
        self.sl6.grid(row=5, column=0)
        self.sl6.insert(END, 'Artisticness')


        #sliders
        self.t1scale = Scale(self.sf, from_=0, to=9, orient=HORIZONTAL)
        self.t1scale.grid(column=1, row=0)
        self.t2scale = Scale(self.sf, from_=0, to=9, orient=HORIZONTAL)
        self.t2scale.grid(column=1, row=1)
        self.t3scale = Scale(self.sf, from_=0, to=9, orient=HORIZONTAL)
        self.t3scale.grid(column=1, row=2)
        self.t4scale = Scale(self.sf, from_=0, to=9, orient=HORIZONTAL)
        self.t4scale.grid(column=1, row=3)
        self.t5scale = Scale(self.sf, from_=0, to=9, orient=HORIZONTAL)
        self.t5scale.grid(column=1, row=4)
        self.t6scale = Scale(self.sf, from_=0, to=9, orient=HORIZONTAL)
        self.t6scale.grid(column=1, row=5)

        #the labels to make clear which line is which trait
        self.l1 = Label(self, text=self.sl1.get(),
              font=('Calibri', 20))
        self.l1.grid(row=1, column=2, sticky=E) 
        self.l2 = Label(self, text=self.sl2.get(),
              font=('Calibri', 20))
        self.l2.grid(row=1, column=1, sticky=SE)
        self.l3 = Label(self, text=self.sl3.get(),
              font=('Calibri', 20))
        self.l3.grid(row=1, column=1, sticky=SW)
        self.l4 = Label(self, text=self.sl4.get(),
              font=('Calibri', 20))
        self.l4.grid(row=1, column=0, sticky=W)
        self.l5 = Label(self, text=self.sl5.get(),
              font=('Calibri', 20))
        self.l5.grid(row=1, column=1, sticky=NW)
        self.l6 = Label(self, text=self.sl6.get(),
              font=('Calibri', 20))
        self.l6.grid(row=1, column=1, sticky=NE) #:)



        #put the person's name in here
        self.nameentry = Entry(self.sf)
        self.nameentry.grid(row=7, column=1)

        Label(self.sf, text='\n\nName of person\n\n').grid(row=7, column=0)
        
        
        self.namelabel = Label(self, text='Name', font=('Calibri', 20), fg='red')
        self.namelabel.grid(row=0, column=1)

        
        #6 lists of points
        self.listright = [(400+40*i, 200*2**0.5)
                          for i in range(10)]
        self.listrightdown = [(400+20*i, 200*2**0.5+i*20*2**0.5)
                              for i in range(10)]
        self.listleftdown = [(400-20*i, 200*2**0.5+i*20*2**0.5)
                              for i in range(10)]
        self.listleft = [(400-40*i, 200*2**0.5)
                         for i in range(10)]
        self.listleftup = [(400-20*i, 200*2**0.5-i*20*2**0.5)
                           for i in range(10)]
        self.listrightup = [(400+20*i, 200*2**0.5-i*20*2**0.5)
                            for i in range(10)]
        


        
        #Draw the 10 hexagons
        for i in range(10):
            self.canvas.create_polygon([self.listright[i][0],
                                        self.listright[i][1],
                                        self.listrightdown[i][0],
                                        self.listrightdown[i][1],
                                        self.listleftdown[i][0],
                                        self.listleftdown[i][1],
                                        self.listleft[i][0],
                                        self.listleft[i][1],
                                        self.listleftup[i][0],
                                        self.listleftup[i][1],
                                        self.listrightup[i][0],
                                        self.listrightup[i][1],],
                                        fill='', width=1, outline='black')
            
    def change_color(self):
        self.color = clr.askcolor(title='Choose a color for the shape')[1]

    def help(self):
        msg.showinfo(title='Help', message='''
How to use this app:
Move around the sliders and enter a name.
Type your 6 character traits in the 6 entries.
You can change the color of shape by clicking on the 'Change Color' menu option.
Then, take a snip of the part without the sliders.

Tutorial on judgy hexagons in real life:
First, draw like 8 nested hexagons.
Connect all the points with 6 lines.
Label each of the lines with a trait (should be the traits below).
For each of the traits, rank them from 1-8 and draw the point on the line.
The outer hexagons are higher.
Now, connect all 6 points, and color in the polygon made by them.''')

    def people(self):
        msg.showinfo(title='People', message='''
List of people related to this:

Ideas: Aileen Liang (probably more this person), Hanting Li
Python implementation: Owen Fei
Another app to check out: Owen Zhang''')

                                      
    def judge(self, t1, t2, t3, t4, t5, t6):
        '''
        Draws the filled-in polygon in blue.
        '''

        #Get which point each level of trait is
        t1 = self.listright[t1]
        t2 = self.listrightdown[t2]
        t3 = self.listleftdown[t3]
        t4 = self.listleft[t4]
        t5 = self.listleftup[t5]
        t6 = self.listrightup[t6]

        #REmove the last shape if possible
        try:
            self.canvas.delete(self.last_polygon)
        except:
            pass

        #Draw the new polygon
        self.last_polygon = self.canvas.create_polygon([t1[0],
                                                        t1[1],
                                                        t2[0],
                                                        t2[1],
                                                        t3[0],
                                                        t3[1],
                                                        t4[0],
                                                        t4[1],
                                                        t5[0],
                                                        t5[1],
                                                        t6[0],
                                                        t6[1],],
                                                        fill=self.color,
                                                        width=1,
                                                        outline=self.color)
        self.canvas.update()

    def main(self):
        '''
        Constantly draws the new polygon.
        Constantly updates the name.
        '''
        while True:
            #Update the name
            self.namelabel.config(text=self.nameentry.get())

            #Call judge() on the values of the sliders
            self.judge(self.t1scale.get(),
                       self.t2scale.get(),
                       self.t3scale.get(),
                       self.t4scale.get(),
                       self.t5scale.get(),
                       self.t6scale.get())

            #Updates the labels with trait names.
            self.l1.config(text=self.sl1.get())
            self.l2.config(text=self.sl2.get())
            self.l3.config(text=self.sl3.get())
            self.l4.config(text=self.sl4.get())
            self.l5.config(text=self.sl5.get())
            self.l6.config(text=self.sl6.get())
            

            
            self.update()
예제 #60
-1
 def __createWindowOnId(self, itemId, content):
     if self.currentlyRenderedWindow != None:
         self.currentlyRenderedWindow()
     # self.__remove(self.currentlyRenderedWindow)
     idtuple = self.localCanvas.coords(itemId)
     if idtuple:
         x = idtuple[0]
         y = idtuple[1]
         frm = Frame(self.localCanvas)
         frm.grid(row=0, column=0)
         canv = Canvas(frm)            
         
         vscroll = Scrollbar(frm, orient="vertical", command=canv.yview)
         vscroll.grid(row=0, column=1, sticky=N + S)
         
         canv.grid(row=0, column=0)
         
         canv["yscrollcommand"] = vscroll.set
         aframe = Frame(canv)
         aframe.grid(row=0, column=0)
         Label(aframe, text=content, anchor="center", background="#CCFFCC", borderwidth=6, relief="ridge", justify="left").grid(row=1, column=0)
         canvWindow = canv.create_window(x, y, window=aframe)
         canv.coords(canvWindow, x, y)
         self.localCanvas.update_idletasks()
         canv["scrollregion"] = canv.bbox("all")
         
         def destroyAll():
             self.__remove(canvWindow)
             canv.destroy()
             aframe.destroy()
             vscroll.destroy()
             frm.destroy()
             
         self.currentlyRenderedWindow = destroyAll 
         Button(frm, text="Close", command=lambda :  destroyAll()).grid(row=2, column=0)