Esempio n. 1
0
class SettingsFrame(Frame):
    '''
    Frame inheritance class for application settings and controls.
    '''

    def __init__(self, app, *args, **kwargs):
        '''
        Constructor.
        '''

        self.__app = app  # Reference to main application class
        self.__master = self.__app.get_master()  # Reference to root class (Tk)
        Frame.__init__(self, self.__master, *args, **kwargs)

        self._show_advanced = False
        self._settings = {}
        self._ports = ()
        self._port = StringVar()
        self._port_desc = StringVar()
        self._baudrate = IntVar()
        self._databits = IntVar()
        self._stopbits = DoubleVar()
        self._parity = StringVar()
        self._rtscts = IntVar()
        self._xonxoff = IntVar()
        self._protocol = IntVar()
        self._raw = IntVar()
        self._autoscroll = IntVar()
        self._maxlines = IntVar()
        self._webmap = IntVar()
        self._mapzoom = IntVar()
        self._units = StringVar()
        self._format = StringVar()
        self._datalog = IntVar()
        self._record_track = IntVar()
        self._noports = True
        self._validsettings = True
        self._logpath = None
        self._trackpath = None
        self._img_conn = ImageTk.PhotoImage(Image.open(ICON_CONN))
        self._img_disconn = ImageTk.PhotoImage(Image.open(ICON_DISCONN))
        self._img_ubxconfig = ImageTk.PhotoImage(Image.open(ICON_UBXCONFIG))
        self._img_dataread = ImageTk.PhotoImage(Image.open(ICON_LOGREAD))

        self._body()
        self._do_layout()
        self._get_ports()
        self._reset()

    def _body(self):
        '''
        Set up frame and widgets.
        '''

        for i in range(4):
            self.grid_columnconfigure(i, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self.option_add("*Font", self.__app.font_sm)

        # Serial port settings
        self._frm_basic = Frame(self)
        self._lbl_port = Label(self._frm_basic, text="Port")
        self._lbx_port = Listbox(self._frm_basic, border=2,
                                 relief="sunken", bg=ENTCOL,
                                 width=28, height=5, justify=LEFT,
                                 exportselection=False)
        self._scr_portv = Scrollbar(self._frm_basic, orient=VERTICAL)
        self._scr_porth = Scrollbar(self._frm_basic, orient=HORIZONTAL)
        self._lbx_port.config(yscrollcommand=self._scr_portv.set)
        self._lbx_port.config(xscrollcommand=self._scr_porth.set)
        self._scr_portv.config(command=self._lbx_port.yview)
        self._scr_porth.config(command=self._lbx_port.xview)
        self._lbx_port.bind("<<ListboxSelect>>", self._on_select_port)
        self._lbl_baudrate = Label(self._frm_basic, text="Baud rate")
        self._spn_baudrate = Spinbox(self._frm_basic,
                                     values=(BAUDRATES),
                                     width=8, state=READONLY, readonlybackground=ENTCOL,
                                     wrap=True, textvariable=self._baudrate)
        self._btn_toggle = Button(self._frm_basic, text=ADVOFF, width=3,
                                  command=self._toggle_advanced)

        self._frm_advanced = Frame(self)
        self._lbl_databits = Label(self._frm_advanced, text="Data Bits")
        self._spn_databits = Spinbox(self._frm_advanced, values=(8, 7, 6, 5),
                                     width=3, state=READONLY, readonlybackground=ENTCOL,
                                     wrap=True, textvariable=self._databits)
        self._lbl_stopbits = Label(self._frm_advanced, text="Stop Bits")
        self._spn_stopbits = Spinbox(self._frm_advanced, values=(2, 1.5, 1),
                                     width=3, state=READONLY, readonlybackground=ENTCOL,
                                     wrap=True, textvariable=self._stopbits)
        self._lbl_parity = Label(self._frm_advanced, text="Parity")
        self._spn_parity = Spinbox(self._frm_advanced,
                                   values=("None", "Even", "Odd", "Mark", "Space"),
                                   width=6, state=READONLY, readonlybackground=ENTCOL,
                                   wrap=True, textvariable=self._parity)
        self._chk_rts = Checkbutton(self._frm_advanced, text="RTS/CTS",
                                    variable=self._rtscts)
        self._chk_xon = Checkbutton(self._frm_advanced, text="Xon/Xoff",
                                    variable=self._xonxoff)

        self._frm_buttons = Frame(self)
        self._btn_connect = Button(self._frm_buttons, width=45, height=35,
                                  image=self._img_conn,
                                  command=lambda: self.__app.serial_handler.connect())
        self._btn_disconnect = Button(self._frm_buttons, width=45, height=35,
                                     image=self._img_disconn,
                                     command=lambda: self.__app.serial_handler.disconnect(),
                                     state=DISABLED)
        self._btn_connect_file = Button(self._frm_buttons, width=45, height=35,
                                     image=self._img_dataread,
                                     command=lambda: self._on_data_stream())
        self._lbl_status_preset = Label(self._frm_buttons, font=self.__app.font_md2, text='')

        # Other configuration options
        self._frm_options = Frame(self)
        self._lbl_protocol = Label(self._frm_options, text=LBLPROTDISP)
        self._rad_nmea = Radiobutton(self._frm_options, text="NMEA",
                                    variable=self._protocol, value=NMEA_PROTOCOL)
        self._rad_ubx = Radiobutton(self._frm_options, text="UBX",
                                    variable=self._protocol, value=UBX_PROTOCOL)
        self._rad_all = Radiobutton(self._frm_options, text="ALL",
                                    variable=self._protocol, value=MIXED_PROTOCOL)
        self._lbl_consoledisplay = Label(self._frm_options, text=LBLDATADISP)
        self._rad_parsed = Radiobutton(self._frm_options, text="Parsed",
                                    variable=self._raw, value=0)
        self._rad_raw = Radiobutton(self._frm_options, text="Raw",
                                   variable=self._raw, value=1)
        self._lbl_format = Label(self._frm_options, text="Degrees Format")
        self._spn_format = Spinbox(self._frm_options,
                                  values=(DDD, DMS, DMM),
                                  width=6, state=READONLY, readonlybackground=ENTCOL,
                                  wrap=True, textvariable=self._format)
        self._lbl_units = Label(self._frm_options, text="Units")
        self._spn_units = Spinbox(self._frm_options,
                                  values=(UMM, UIK, UI, UMK),
                                  width=13, state=READONLY, readonlybackground=ENTCOL,
                                  wrap=True, textvariable=self._units)
        self._chk_scroll = Checkbutton(self._frm_options, text="Autoscroll",
                                      variable=self._autoscroll)
        self._spn_maxlines = Spinbox(self._frm_options,
                                     values=("100", "200", "500", "1000", "2000"),
                                    width=6, readonlybackground=ENTCOL, wrap=True,
                                    textvariable=self._maxlines, state=READONLY)
        self._chk_webmap = Checkbutton(self._frm_options, text="Web Map  Zoom",
                                      variable=self._webmap)
        self._scl_mapzoom = Scale(self._frm_options, from_=1, to=20, orient=HORIZONTAL,
                                  relief="sunken", bg=ENTCOL, variable=self._mapzoom)
        self._chk_datalog = Checkbutton(self._frm_options, text=LBLDATALOG,
                                        variable=self._datalog,
                                        command=lambda: self._on_data_log())

        self._chk_recordtrack = Checkbutton(self._frm_options, text=LBLTRACKRECORD,
                                        variable=self._record_track,
                                        command=lambda: self._on_record_track())

        self._lbl_ubxconfig = Label(self._frm_options, text=LBLUBXCONFIG)
        self._btn_ubxconfig = Button(self._frm_options, width=45, height=35,
                                     text='UBX', image=self._img_ubxconfig,
                                     command=lambda: self._on_ubx_config(),
                                     state=DISABLED)

    def _do_layout(self):
        '''
        Position widgets in frame.
        '''

        self._frm_basic.grid(column=0, row=0, columnspan=4, sticky=(W, E))
        self._lbl_port.grid(column=0, row=0, sticky=(W))
        self._lbx_port.grid(column=1, row=0, sticky=(W, E), padx=3, pady=3)
        self._scr_portv.grid(column=2, row=0, sticky=(N, S))
        self._scr_porth.grid(column=1, row=1, sticky=(E, W))
        self._lbl_baudrate.grid(column=0, row=2, sticky=(W))
        self._spn_baudrate.grid(column=1, row=2, sticky=(W), padx=3, pady=3)
        self._btn_toggle.grid(column=2, row=2, sticky=(E))

        self._frm_advanced.grid_forget()
        self._lbl_databits.grid(column=0, row=0, sticky=(W))
        self._spn_databits.grid(column=1, row=0, sticky=(W), padx=3, pady=3)
        self._lbl_stopbits.grid(column=2, row=0, sticky=(W))
        self._spn_stopbits.grid(column=3, row=0, sticky=(W), padx=3, pady=3)
        self._lbl_parity.grid(column=0, row=1, sticky=(W))
        self._spn_parity.grid(column=1, row=1, sticky=(W), padx=3, pady=3)
        self._chk_rts.grid(column=2, row=1, sticky=(W))
        self._chk_xon.grid(column=3, row=1, sticky=(W), padx=3, pady=3)

        ttk.Separator(self).grid(column=0, row=2, columnspan=4,
                                            padx=3, pady=3, sticky=(W, E))

        self._frm_buttons.grid(column=0, row=3, columnspan=4, sticky=(W, E))
        self._btn_connect.grid(column=0, row=0, padx=3, pady=3)
        self._btn_connect_file.grid(column=1, row=0, padx=3, pady=3)
        self._btn_disconnect.grid(column=3, row=0, padx=3, pady=3)

        ttk.Separator(self).grid(column=0, row=7, columnspan=4,
                                            padx=3, pady=3, sticky=(W, E))

        self._frm_options.grid(column=0, row=8, columnspan=4, sticky=(W, E))
        self._lbl_protocol.grid(column=0, row=0, padx=3, pady=3, sticky=(W))
        self._rad_nmea.grid(column=1, row=0, padx=0, pady=0, sticky=(W))
        self._rad_ubx.grid(column=2, row=0, padx=0, pady=0, sticky=(W))
        self._rad_all.grid(column=3, row=0, padx=0, pady=0, sticky=(W))
        self._lbl_consoledisplay.grid(column=0, row=1, padx=2, pady=3, sticky=(W))
        self._rad_parsed.grid(column=1, row=1, padx=1, pady=3, sticky=(W))
        self._rad_raw.grid(column=2, row=1, padx=2, pady=3, sticky=(W))
        self._lbl_format.grid(column=0, row=2, padx=3, pady=3, sticky=(W))
        self._spn_format.grid(column=1, row=2, padx=2, pady=3, sticky=(W))
        self._lbl_units.grid(column=0, row=3, padx=3, pady=3, sticky=(W))
        self._spn_units.grid(column=1, row=3, columnspan=3, padx=2, pady=3, sticky=(W))
        self._chk_scroll.grid(column=0, row=4, padx=3, pady=3, sticky=(W))
        self._spn_maxlines.grid(column=1, row=4, columnspan=3, padx=3, pady=3, sticky=(W))
        self._chk_webmap.grid(column=0, row=5, sticky=(W))
        self._scl_mapzoom.grid(column=1, row=5, columnspan=3, sticky=(W))
        self._chk_datalog.grid(column=0, row=6, padx=3, pady=3, sticky=(W))
        self._chk_recordtrack.grid(column=0, row=7, padx=3, pady=3, sticky=(W))

        ttk.Separator(self._frm_options).grid(column=0, row=8, columnspan=4,
                                 padx=3, pady=3, sticky=(W, E))
        self._lbl_ubxconfig.grid(column=0, row=9, padx=3, pady=3, sticky=(W))
        self._btn_ubxconfig.grid(column=1, row=9, padx=3, pady=3, sticky=(W))

    def _on_select_port(self, *args, **kwargs):
        '''
        Get selected port from listbox and set global variable.
        '''

        idx = self._lbx_port.curselection()
        if  idx == "":
            idx = 0
        port_orig = self._lbx_port.get(idx)
        port = port_orig[0:port_orig.find(":")]
        desc = port_orig[port_orig.find(":") + 1:]
        if desc == '':
            desc = "device"
        self._port.set(port)
        self._port_desc.set(desc)

    def _on_ubx_config(self, *args, **kwargs):
        '''
        Open UBX configuration dialog panel.
        '''

        self.__app.ubxconfig()

    def _on_data_log(self):
        '''
        Start or stop data logger
        '''

        if self._datalog.get() == 1:
            self._logpath = self.__app.file_handler.set_logfile_path()
            if self._logpath is not None:
                self.__app.set_status("Data logging enabled: " + self._logpath, "green")
            else:
                self._datalog.set(False)
        else:
            self._logpath = None
            self._datalog.set(False)
#             self.__app.file_handler.close_logfile()
            self.__app.set_status("Data logging disabled", "blue")

    def _on_record_track(self):
        '''
        Start or stop track recorder
        '''

        if self._record_track.get() == 1:
            self._trackpath = self.__app.file_handler.set_trackfile_path()
            if self._trackpath is not None:
                self.__app.set_status("Track recording enabled: " + self._trackpath, "green")
            else:
                self._record_track.set(False)
        else:
            self._trackpath = None
            self._record_track.set(False)
#             self.__app.file_handler.close_trackfile()
            self.__app.set_status("Track recording disabled", "blue")

    def _on_data_stream(self):
        '''
        Start data file streamer
        '''

        self._logpath = self.__app.file_handler.open_logfile_input()
        if self._logpath is not None:
            self.__app.set_status("")
            self.__app.serial_handler.connect_file()

    def _toggle_advanced(self):
        '''
        Toggle advanced serial port settings panel on or off
        '''

        self._show_advanced = not self._show_advanced
        if self._show_advanced:
            self._frm_advanced.grid(column=0, row=1, columnspan=3, sticky=(W, E))
            self._btn_toggle.config(text=ADVON)
        else:
            self._frm_advanced.grid_forget()
            self._btn_toggle.config(text=ADVOFF)

    def _get_ports(self):
        '''
        Populate list of available serial ports using pyserial comports tool.
        If no ports found, disable all connection-dependent widgets.

        Attempt to preselect the first port that has a recognisable
        GPS designation in its description (usually only works on
        Posix platforms - Windows doesn't parse UART device desc or HWID)
        '''

        self._ports = sorted(comports())
        init_idx = 0
        port = ''
        desc = ''
        if len(self._ports) > 0:
            for idx, (port, desc, _) in enumerate(self._ports, 1):
                self._lbx_port.insert(idx, port + ": " + desc)
                for kgp in KNOWNGPS:
                    if kgp in desc:
                        init_idx = idx
                        break
            self._noports = False
        else:
            self._noports = True
            self.set_controls(NOPORTS)
        self._lbx_port.activate(init_idx)
        self._port.set(port)
        self._port_desc.set(desc)

    def _reset(self):
        '''
        Reset settings to defaults.
        '''

        self._baudrate.set(BAUDRATES[4])  # 9600
        self._databits.set(8)
        self._stopbits.set(1)
        self._parity.set("None")
        self._rtscts.set(False)
        self._xonxoff.set(False)
        self._protocol.set(MIXED_PROTOCOL)
        self._format.set(DDD)
        self._units.set(UMM)
        self._autoscroll.set(1)
        self._maxlines.set(300)
        self._raw.set(False)
        self._webmap.set(False)
        self._mapzoom.set(10)
        self._datalog.set(False)
        self._record_track.set(False)

    def set_controls(self, status):
        '''
        ...for the heart of the sun.
        Public method to enable and disable serial port controls
        depending on connection status.
        '''

        self._lbl_port.configure(state=(NORMAL if status == DISCONNECTED else DISABLED))
        self._lbx_port.configure(state=(NORMAL if status == DISCONNECTED else DISABLED))
        self._lbl_baudrate.configure(state=(NORMAL if status == DISCONNECTED else DISABLED))
        self._spn_baudrate.configure(state=(READONLY if status == DISCONNECTED else DISABLED))
        self._lbl_databits.configure(state=(NORMAL if status == DISCONNECTED else DISABLED))
        self._spn_databits.configure(state=(READONLY if status == DISCONNECTED else DISABLED))
        self._lbl_stopbits.configure(state=(NORMAL if status == DISCONNECTED else DISABLED))
        self._spn_stopbits.configure(state=(READONLY if status == DISCONNECTED else DISABLED))
        self._lbl_parity.configure(state=(NORMAL if status == DISCONNECTED else DISABLED))
        self._spn_parity.configure(state=(READONLY if status == DISCONNECTED else DISABLED))
        self._chk_rts.configure(state=(NORMAL if status == DISCONNECTED else DISABLED))
        self._chk_xon.configure(state=(NORMAL if status == DISCONNECTED else DISABLED))
        self._btn_connect.config(state=(DISABLED if status in \
                                        (CONNECTED, CONNECTED_FILE, NOPORTS) \
                                        else NORMAL))
        self._btn_disconnect.config(state=(DISABLED if status in \
                                           (DISCONNECTED, NOPORTS) else NORMAL))
        self._chk_datalog.config(state=(DISABLED if status in \
                                        (CONNECTED, CONNECTED_FILE, NOPORTS) \
                                        else NORMAL))
        self._chk_recordtrack.config(state=(DISABLED if status in \
                                        (CONNECTED, CONNECTED_FILE) \
                                        else NORMAL))
        self._btn_connect_file.config(state=(DISABLED if status in \
                                             (CONNECTED, CONNECTED_FILE) \
                                             else NORMAL))
        self._btn_ubxconfig.config(state=(DISABLED if status in \
                                          (DISCONNECTED, CONNECTED_FILE, NOPORTS) \
                                          else NORMAL))
        self.__app.menu.options_menu.entryconfig(0, state=(DISABLED if status in \
                                          (CONNECTED_FILE, DISCONNECTED, NOPORTS) \
                                          else NORMAL))

    def get_settings(self):
        '''
        Public method returns all settings as a dict.
        '''

        self._settings['port'] = self._port.get()
        self._settings['noports'] = self._noports
        self._settings['port_desc'] = self._port_desc.get()
        self._settings['baudrate'] = self._baudrate.get()
        self._settings['databits'] = self._databits.get()
        self._settings['stopbits'] = self._stopbits.get()
        self._settings['parity'] = self._parity.get()
        self._settings['rtscts'] = self._rtscts.get()
        self._settings['xonxoff'] = self._xonxoff.get()
        self._settings['protocol'] = self._protocol.get()
        self._settings['raw'] = self._raw.get()
        self._settings['autoscroll'] = self._autoscroll.get()
        self._settings['maxlines'] = self._maxlines.get()
        self._settings['webmap'] = self._webmap.get()
        self._settings['mapzoom'] = self._mapzoom.get()
        self._settings['units'] = self._units.get()
        self._settings['format'] = self._format.get()
        self._settings['logpath'] = self._logpath
        self._settings['datalogging'] = self._datalog.get()
        self._settings['recordtrack'] = self._record_track.get()

        return self._settings

    def get_size(self):
        '''
        Get current frame size.
        '''

        self.update_idletasks()  # Make sure we know about any resizing
        return (self.winfo_width(), self.winfo_height())
Esempio n. 2
0
    def init_ui(self):
        self.parent.title("Hormiga de Lagnton")
        self.pack(fill=tk.BOTH, expand=1)

        self.canvas = Canvas(self, relief='raised', width=1000, height=1000)
        scroll = Scrollbar(self, orient=tk.VERTICAL)
        scroll.pack(side=tk.RIGHT, fill=tk.Y)
        scroll.config(command=self.canvas.yview)

        self.canvas.config(yscrollcommand=scroll.set)
        self.canvas.pack(side=tk.LEFT)

        Label(self, text="Tamaño:", font=(20, )).pack(side=tk.TOP)
        self.input_tam = Entry(self, fg="black", bg="white")
        self.input_tam.insert(10, "100")
        self.input_tam.pack(side=tk.TOP)

        Label(self, text="Porcentaje de hormigas",
              font=(20, )).pack(side=tk.TOP)
        self.barra = Scale(self,
                           from_=0,
                           to=100,
                           orient=tk.HORIZONTAL,
                           tickinterval=50)
        self.barra.set(5)
        self.barra.pack(side=tk.TOP)

        Label(self, text="Tipo de hormiga:", font=(20, )).pack(side=tk.TOP)
        self.radio1 = Radiobutton(self,
                                  text="Obrera",
                                  variable=self.mi_var,
                                  value=1,
                                  command=self.seleccion,
                                  indicatoron=False,
                                  selectcolor="white",
                                  font=(20, ),
                                  fg="black")
        self.radio2 = Radiobutton(self,
                                  text="Soldado",
                                  variable=self.mi_var,
                                  value=2,
                                  command=self.seleccion,
                                  indicatoron=False,
                                  selectcolor="orange",
                                  font=(20, ),
                                  fg="black")
        self.radio3 = Radiobutton(self,
                                  text="Reina",
                                  variable=self.mi_var,
                                  value=3,
                                  command=self.seleccion,
                                  indicatoron=False,
                                  selectcolor="purple",
                                  font=(20, ),
                                  fg="black")
        self.radio1.pack(side=tk.TOP)
        self.radio2.pack(side=tk.TOP)
        self.radio3.pack(side=tk.TOP)
        self.radio1.select()
        self.radio2.deselect()
        self.radio3.deselect()

        self.label_probabilidades = Label(self,
                                          text="Suma de probailidades: 100%",
                                          font=(20, ))
        self.label_probabilidades.pack(side=tk.TOP)

        Label(self, text="Probabilidad de hormigas normales:",
              font=(20, )).pack(side=tk.TOP)
        valor1 = StringVar(self)
        valor1.set("90")
        self.barra_normal = Spinbox(self,
                                    from_=0,
                                    to=100,
                                    command=self.mover_spinner,
                                    textvariable=valor1)
        self.barra_normal.pack(side=tk.TOP)

        Label(self, text="Probabilidad de hormigas soldado:",
              font=(20, )).pack(side=tk.TOP)
        valor2 = StringVar(self)
        valor2.set("8")
        self.barra_soldado = Spinbox(self,
                                     from_=0,
                                     to=100,
                                     command=self.mover_spinner,
                                     textvariable=valor2)
        self.barra_soldado.pack(side=tk.TOP)

        Label(self, text="Probabilidad de hormigas reina:",
              font=(20, )).pack(side=tk.TOP)
        valor3 = StringVar(self)
        valor3.set("2")
        self.barra_reina = Spinbox(self,
                                   from_=0,
                                   to=100,
                                   command=self.mover_spinner,
                                   textvariable=valor3)
        self.barra_reina.pack(side=tk.TOP)

        btn_iniciar = Button(self,
                             text="Iniciar/Reiniciar",
                             command=self.iniciar,
                             font=(20, ))
        btn_iniciar.pack(side=tk.TOP)

        btn_pausa = Button(self,
                           text="Reanudar/Pausa",
                           command=self.empezar_detener,
                           font=(20, ))
        btn_pausa.pack(side=tk.TOP)

        Label(self,
              text="Relación de colores y \n posicion de las hormiga:",
              font=(20, )).pack(side=tk.TOP)
        Label(self, text="Abajo", bg="blue", font=(20, )).pack(side=tk.TOP)
        Label(self, text="Arriba", bg="red", font=(20, )).pack(side=tk.TOP)
        Label(self, text="Izquierda", bg="green",
              font=(20, )).pack(side=tk.TOP)
        Label(self, text="Derecha", bg="yellow", fg="black",
              font=(20, )).pack(side=tk.TOP)
Esempio n. 3
0
    def __init__(self):
        print("Démarrage de l'interface graphique...")
        #Récupération des données
        fichier = open("Data/base_lexicale.pickle", "rb")
        self.base_lexicale = pickle.load(fichier)
        fenetre = fenetre_freqlex()
        #Cet objet contient l'énoncé enrichi par l'analyse lexicale
        self.enonce = ensemble_mots(self.base_lexicale)

        self.lecteur = donnees_lecteur()
        #On crée les  polices
        police_mots = font.Font(fenetre, size=16, family='Courier')
        police_enonce = font.Font(fenetre, size=12, family='Courier')
        #Definition de l'interface graphique
        #Ce cadre contient le texte à analyser
        cadre_enonce = LabelFrame(fenetre,
                                  borderwidth=2,
                                  relief=GROOVE,
                                  text="Enoncé")
        asc_enonce = Scrollbar(cadre_enonce, orient=VERTICAL)
        #L'attribut texte_enonce est utilisé par la méthode recupere_texte
        self.texte_enonce = Text(cadre_enonce,
                                 wrap=WORD,
                                 font=police_enonce,
                                 width=LARGEUR_CADRE_ENONCE)
        self.texte_enonce.bind("<Key>", self.ecoute_clavier)
        self.texte_enonce.insert(
            END,
            "Dans ce cadre, collez n'importe quel texte pour en obtenir une analyse lexicale."
        )

        ## association du déplacement de la glissière des scrollbar avec la position visible dans
        ## le widget Text et inversement.
        asc_enonce.config(command=self.texte_enonce.yview)
        self.texte_enonce.config(yscrollcommand=asc_enonce.set)
        ## Placement du widget Text et des Scrollbar associés
        self.texte_enonce.grid(column=0, row=0)
        asc_enonce.grid(column=1, row=0, sticky=S + N)

        #Ce cadre contient le choix du profil de lecteur
        cadre_lecteur = LabelFrame(fenetre,
                                   text="Profil de lecteur",
                                   height=1,
                                   borderwidth=2,
                                   relief=GROOVE)
        bouton_profil_precedent = Button(cadre_lecteur,
                                         text="<",
                                         command=self.profil_precedent)
        bouton_profil_precedent.grid(column=0, row=0)
        self.affichage_profil_actuel = Text(cadre_lecteur,
                                            height=1,
                                            width=LARGEUR_LISTE_MOTS)
        self.affichage_profil_actuel.insert(END, self.lecteur.profil_actuel)
        self.affichage_profil_actuel.grid(column=1, row=0)
        bouton_profil_suivant = Button(cadre_lecteur,
                                       text=">",
                                       command=self.profil_suivant)
        bouton_profil_suivant.grid(column=2, row=0)

        #Le cadre de comparaison des deux mots
        self.cadre_compare = LabelFrame(fenetre,
                                        borderwidth=2,
                                        relief=GROOVE,
                                        text="Comparaison de deux mots")
        self.cadre_compare.parent = self
        self.compare = cadre_cp(self.cadre_compare, self.base_lexicale,
                                self.lecteur)

        #Ce cadre contient les mots du lexique classés
        self.zone_mots_lexique = liste_mots(
            fenetre, "Classement par difficulté lexicale:", self.compare)
        self.zone_mots_lexique.parent = self
        #Ce cadre contient les mots absents des lexiques
        self.zone_mots_absents = liste_mots(fenetre, "Mots absents des bases",
                                            self.compare)
        self.zone_mots_absents.mots.configure(height=3)
        #Ce cadre contiendra des explications sur les objets de la fenêtre
        largeur_infos = LARGEUR_CADRE_ENONCE + LARGEUR_LISTE_MOTS
        cadre_infos = LabelFrame(fenetre,
                                 text="Infos",
                                 height=2,
                                 borderwidth=2,
                                 relief=GROOVE)
        self.infos = Text(cadre_infos,
                          bg="grey",
                          height=3,
                          width=largeur_infos)
        self.infos.insert(
            END,
            "Survolez les noms des bases de données pour obtenir des explications, clqiuez sur les mots de la liste pour obtenir des détails."
        )
        self.infos.grid(column=0, row=0)
        #Ce cadre contient le texte des crédits
        cadre_credits = cree_cadre_credits(fenetre)

        #On place les cadres de premier niveau
        cadre_lecteur.grid(column=1, row=0)
        self.zone_mots_lexique.cadre.grid(column=1, row=1)
        self.cadre_compare.grid(column=1, row=2)
        self.zone_mots_absents.cadre.grid(column=1, row=3)
        cadre_enonce.grid(column=0, row=0, rowspan=3)
        cadre_credits.grid(column=0, row=3)
        cadre_infos.grid(column=0, row=4, columnspan=2)

        self.fenetre = fenetre
        self.analyse()
        # On démarre la boucle Tkinter qui s'interrompt quand on ferme la fenêtre
        fenetre.mainloop()
Esempio n. 4
0
    def __init__(self,master,dataName,filename):
        self.master = master
        # save creation options
        self.dataName = dataName
        self.filename = filename
        # set title
        self.master.title("Data Viewer")
        # current colormap, default
        self.curr_cmap = getattr(matplotlib.cm,matplotlib.rcParams['image.cmap'])
        # currnt line color
        self.curr_lcol = matplotlib.rcParams['axes.prop_cycle'].by_key()['color'][0]
        ## menu bar for customisation
        # root menu
        menu = Menu(master)
        # options menu
        optsmenu = Menu(menu,tearoff=0)
        # label for graph
        self.title = StringVar()
        self.title.set(f'Displaying {dataName}')
        self.graph_title = Label(master,textvariable=self.title)
        self.graph_title.pack(side=TOP,pady=10,padx=10)
        # create figure
        self.fig = Figure(figsize=(5,5),dpi=100)
        self.axes = self.fig.add_subplot(111)
        # get data from dataset and plot data
        with h5py.File(filename,mode='r') as f:
            self.data_shape = f[dataName].shape
            # if the data is 1D, plot as line
            if len(self.data_shape)==1:
                self.axes.plot(f[dataName][()],self.curr_lcol)
                optsmenu.add_command(label="Set color",command=self.set_color)
            # if data is 2D, plot as filled contour
            elif len(self.data_shape)==2:
                self.axes.contourf(f[dataName][()],cmap=self.curr_cmap)
                optsmenu.add_command(label="Set colormap",command=self.set_colormap)
            # if data is 3D plot as contourf, but also add a scrollbar for navigation
            elif len(self.data_shape)==3:
                optsmenu.add_command(label="Set colormap",command=self.set_colormap)
                # create scroll bar for viewing different slices
                self.plot_scroll=Scrollbar(master,orient="horizontal",command=self.scroll_data)
                # add too gui
                self.plot_scroll.pack(side=TOP,fill=BOTH,expand=True)
                # plot first slice of data
                self.axes.contourf(f[dataName][:,:,0],cmap=self.curr_cmap)
                # create index for current depth index
                self.depth_index = 0
                self.title.set(f"Displaying {dataName} [{self.depth_index}]")
        # add to root menu
        menu.add_cascade(label="Options",menu=optsmenu)
        self.master.config(menu=menu)
        # create canvas to render figure
        self.fig_canvas = FigureCanvasTkAgg(self.fig,self.master)
        # update result
        self.fig_canvas.draw()
        # update canvas to set position and expansion options
        self.fig_canvas.get_tk_widget().pack(side=TOP,fill=BOTH,expand=True)

        ## add matplotlib toolbar
        self.fig_toolbar = NavigationToolbar2Tk(self.fig_canvas,self.master)
        self.fig_toolbar.update()
        # add to gui. always one row below the canvas
        self.fig_canvas._tkcanvas.pack(side=TOP,fill=BOTH,expand=True)
        ## add key press handlers
        self.fig_canvas.mpl_connect("key_press_event",self.on_key_press)
        # ensure elements are expandable in grid
        num_cols,num_rows = master.grid_size()
        for c in range(num_cols):
            master.columnconfigure(c,weight=1)
        for r in range(num_rows):
            master.rowconfigure(r,weight=1)
        # finish any idle tasks and set the minimum size of the window to cur
        master.update_idletasks()
        master.after_idle(lambda: master.minsize(master.winfo_width(), master.winfo_height()))
Esempio n. 5
0
    def __init__(self,master):
        self.master = master
        # set title of image
        master.title("HDF5 File Viewer")

        ## initialize internal variables used
        # set current file as blank
        self.curr_file = "/"
        self.status = StringVar()
        
        ## initialize widgets
        # status label indicating progress or errors
        self.status_label = Label(master,textvariable=self.status)
        self.status.set("Waiting for filename...")
        # button to scan target HDF5 file
        self.scan_button = Button(master,text="Scan File",command=self.scan_file,padx=2)
        # button to chose hdf5 file
        self.openfile_button = Button(master,text="Open File",command=self.open_file,padx=2)
        # box to display current filename
        self.name_display = Entry(master,text="Current filename")
        ## setup tree headings
        # tree view for file layout
        self.file_tree = Treeview(master,columns=("htype","shape","dtype"),show="tree")
        # add double click handler
        # <Double-1> double left click handler
        self.file_tree.bind("<Double-1>",self.create_viewer)
        # dimensions of the columns
        self.file_tree.column("htype",width=200,anchor=CENTER)
        self.file_tree.column("shape",width=200,anchor=CENTER)
        self.file_tree.column("dtype",width=200,anchor=CENTER)
        # text to display in headings
        self.file_tree.heading("htype",text="Item Type")
        self.file_tree.heading("shape",text="Shape")
        self.file_tree.heading("dtype",text="Data Type")
        self.file_tree['show']='headings'
        
        ## add scrollbar for treeview
        # define scrollbar and set the action associated with moving the scrollbar to changing
        # the yview of the tree
        self.tree_scroll=Scrollbar(master,orient="vertical",command=self.file_tree.yview)
        self.file_tree.configure(yscrollcommand=self.tree_scroll)
        
        # set grid layout for widgets using grid
        self.status_label.grid(columnspan=3,row=0)
        self.file_tree.grid(column=0,row=2,columnspan=3,sticky='nswe')
        self.scan_button.grid(column=0,row=1,sticky='we',padx=10)
        self.openfile_button.grid(column=1,row=1,sticky='we',padx=10)
        self.name_display.grid(column=2,row=1,sticky='we',padx=10)
        self.tree_scroll.grid(column=3,row=2,sticky='ns')
        # set weight parameters for control how the elements are resized when the user changes the window size
        master.columnconfigure(0,weight=1)
        master.columnconfigure(1,weight=1)
        master.columnconfigure(2,weight=1)
        master.columnconfigure(3,weight=1)
        master.rowconfigure(0,weight=1)
        master.rowconfigure(1,weight=1)
        master.rowconfigure(2,weight=1)
        master.rowconfigure(3,weight=1)
        # finish any idle tasks and set the minimum size of the window to cur
        master.update_idletasks()
        master.after_idle(lambda: master.minsize(master.winfo_width(), master.winfo_height()))
Esempio n. 6
0
    def build(self):
        """
        mwethod for interface do program.
        """

        # text.
        Label(self.__root,
              bg=self.window_bg,
              font=self.__label_font,
              fg=self.__label_fg,
              text="Input:",
              pady=10).pack()

        # frame paracolor to the input.
        input_frame = Frame(self.__root, bg=self.window_bg)
        input_frame.pack()

        # text of input height and width.
        self.__inputText = Text(input_frame,
                                width=self.__text_width,
                                height=self.__inputText_height,
                                bg=self.__text_bg,
                                fg=self.__text_fg,
                                font=self.__text_font,
                                wrap="word")
        self.__inputText.insert(0.0, " ")

        # adding scrollbar to the input.
        scrollbar = Scrollbar(input_frame)
        scrollbar.pack(side="right", fill="y")
        self.__inputText.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.__inputText.yview)

        self.__inputText.pack()

        # label output screen for text.
        Label(self.__root,
              bg=self.window_bg,
              font=self.__label_font,
              fg=self.__label_fg,
              text="Output:",
              pady=10).pack()

        # frame for the output.
        output_frame = Frame(self.__root, bg=self.window_bg)
        output_frame.pack()

        # paracolor text for the output.
        self.__outputText = Text(output_frame,
                                 width=self.__text_width,
                                 height=self.__outputText_height,
                                 bg=self.__text_bg,
                                 fg=self.__text_fg,
                                 font=self.__text_font,
                                 wrap="word")
        self.__outputText.insert(0.0, " ")

        # scrollbar for the out put screen.
        scrollbar = Scrollbar(output_frame)
        scrollbar.pack(side="right", fill="y")
        self.__outputText.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.__outputText.yview)

        self.__outputText.pack()

        # frame for the insert.
        buttons_frame = Frame(self.__root, bg=self.window_bg, pady=20)
        buttons_frame.pack()

        # buttons for the left side color is black.
        button1_frame = Frame(buttons_frame, bg="black", padx=2, pady=2)
        button1_frame.pack(side="left")

        # button text ,color.
        self.__button1 = Button(button1_frame,
                                width=self.__button_width,
                                height=self.__button_height,
                                relief=self.__button_relief,
                                bg=self.__button_bg,
                                fg=self.__button_fg,
                                font=self.__button_font,
                                text="Translate",
                                command=self.translate)
        self.__button1.pack()

        #operating system
        if "win" in sys.platform:

            Label(buttons_frame, bg=self.window_bg, padx=5).pack(side="left")

            # Cria uma "borda" para o botão.
            button2_frame = Frame(buttons_frame, bg="black", padx=2, pady=2)
            button2_frame.pack(side="left")

            # Cria botão para reproduzir som do código morse.
            self.__button2 = Button(button2_frame,
                                    width=self.__button_width,
                                    height=self.__button_height,
                                    relief=self.__button_relief,
                                    bg=self.__button_bg,
                                    fg=self.__button_fg,
                                    font=self.__button_font,
                                    text="Play",
                                    command=self.play)
            self.__button2.pack()

        self.__root.mainloop()
Esempio n. 7
0
class Grapfics():
    def __init__(self):
        self.aut = ''
        self.root = Tk()
        self.root.state('zoomed')
        self.root.geometry(
            str(self.root.winfo_screenwidth() - 200) + 'x' +
            str(self.root.winfo_screenheight() - 200))

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

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

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

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

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

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

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

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

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

        self.splitter.add(self.frame_2)

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

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

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

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

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

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

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

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

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

        self.root.mainloop()

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

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

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

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

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

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

        self.pr.mainloop()
    class SettingsWindow:
        def __init__(self, parent):
            self.parent = parent
            self.settings = Settings(self.parent.settings)
            self.settings.edit_flag = False
            self.frame0 = Frame(self.parent)
            self.title = Label(self.frame0, text='Settings', font='arial 20')
            self.BackButton = Button(self.title,
                                     text='<< Back',
                                     background='#888',
                                     foreground='#000',
                                     padx='0',
                                     width='8',
                                     pady='0',
                                     command=self.back)
            self.frame1 = Frame(self.parent,
                                relief='groove',
                                bd=1,
                                height=150,
                                width=480)
            self.frame1.pack_propagate(0)
            self.canvas = Canvas(self.frame1)
            self.frame_keys = Frame(self.canvas)
            self.scrollbar_keys = Scrollbar(self.frame1,
                                            orient="vertical",
                                            command=self.canvas.yview)
            self.canvas.configure(yscrollcommand=self.scrollbar_keys.set)
            self.frame_keys.bind("<Configure>", self.scrolling)
            self.frame_keys.bind_all("<MouseWheel>", self._on_mousewheel)
            self.frame_actions = Frame(self.parent)
            self.AddButton = Button(
                self.frame_actions,
                text='Add key',
                background='#888',
                foreground='#000',
                padx='2',
                pady='0',
                width='10',
                command=lambda: self.add_key(self.frame_keys))
            self.ClearButton = Button(
                self.frame_actions,
                text='Clear keys',
                background='#888',
                foreground='#000',
                padx='2',
                pady='0',
                width='10',
                command=lambda: self.delete_key('all', self.frame_keys))
            self.GetKeyButton = Button(self.frame_actions,
                                       text='Get API key',
                                       background='#888',
                                       foreground='#000',
                                       padx='2',
                                       pady='0',
                                       width='10',
                                       command=lambda: webbrowser.open_new_tab(
                                           'https://tinypng.com/developers'))
            self.SaveButton = Button(
                self.parent,
                text='Save',
                background='#888',
                foreground='#000',
                padx='2',
                pady='0',
                width='10',
                font='arial 12',
                command=lambda: self.parent.settings.save_settings(
                    self.settings, self.parent.init_menu_window))

        def show(self):
            self.frame0.pack(fill='x')
            self.title.pack(fill='x',
                            pady=5,
                            side='left',
                            expand=True,
                            ipady=4)
            self.BackButton.pack(side='left')
            self.frame1.pack(fill='x', ipadx=1)
            self.frame_keys.pack(ipadx=3)
            self.scrollbar_keys.pack(side='right', fill='y')
            self.canvas.pack()
            self.canvas.create_window((0, 0),
                                      window=self.frame_keys,
                                      anchor='nw')
            self.frame_keys.rowconfigure(0, pad=2)
            self.frame_keys.columnconfigure(0, pad=2)
            self.frame_keys.columnconfigure(1, pad=1)
            self.frame_keys.columnconfigure(2, pad=1)
            self.frame_keys.columnconfigure(3, pad=1)
            self.frame_actions.pack(fill='x', pady=10)
            self.AddButton.pack(side='left', padx=4)
            self.ClearButton.pack(side='left', padx=4)
            self.GetKeyButton.pack(side='right', padx=4)
            self.SaveButton.pack(pady=10)
            self.show_keys(self.frame_keys)

        def show_keys(self, target_frame):
            if len(self.settings.keys):
                target_frame.config(background='BLACK')
                Label(target_frame, text='№', width=3).grid(row=0, column=0)
                Label(target_frame, text='API key', width=30).grid(row=0,
                                                                   column=1)
                Label(target_frame, text="Compression count",
                      width=15).grid(row=0, column=2)
                Label(target_frame, text="Action", width=11).grid(row=0,
                                                                  column=3)
                i = 1
                for key in self.settings.keys:
                    target_frame.rowconfigure(i, pad=1)
                    Label(target_frame, text=i, width=3,
                          height=2).grid(row=i, column=0)
                    Label(target_frame, text=key, width=30,
                          height=2).grid(row=i, column=1)
                    Label(target_frame,
                          text=self.settings.keys[key],
                          width=15,
                          height=2).grid(row=i, column=2)
                    button_frame = Frame(target_frame, width=83, height=36)
                    button_frame.pack_propagate(0)
                    button_frame.grid(row=i, column=3)
                    Button(button_frame,
                           text='Edit',
                           background='#888',
                           foreground='#000',
                           width=4,
                           height=1,
                           bd=1,
                           command=lambda arg=key: self.edit_key(
                               arg, target_frame)).pack(pady=5, side='left')
                    Button(button_frame,
                           text='Delete',
                           background='#888',
                           foreground='#000',
                           width=6,
                           height=1,
                           bd=1,
                           command=lambda arg=key: self.delete_key(
                               arg, target_frame)).pack(pady=5, side='left')
                    i += 1
            else:
                target_frame.config(background='')
                Label(target_frame,
                      text='Please add your TinyPNG API key',
                      font='arial 15').pack(fill='x', padx=70, pady=4)
                Button(target_frame,
                       text='Get API key',
                       background='#888',
                       foreground='#000',
                       padx='2',
                       pady='0',
                       width='10',
                       font='arial 15',
                       command=lambda: webbrowser.open_new_tab(
                           'https://tinypng.com/developers')).pack()

        def scrolling(self, event):
            height = event.height
            if height > 150:
                height = 150
            self.canvas.configure(scrollregion=self.canvas.bbox("all"),
                                  width=440,
                                  height=height)

        def _on_mousewheel(self, event):
            self.canvas.yview_scroll(int((-1 * (event.delta / 120))), "units")

        def add_key(self, target_frame=None):
            self.AddEditWindow(self.parent, self.settings)
            if target_frame:
                Window.destroy_elements(target_frame)
                self.show_keys(target_frame)

        def edit_key(self, key, target_frame=None):
            self.AddEditWindow(self.parent, self.settings, key)
            if target_frame:
                Window.destroy_elements(target_frame)
                self.show_keys(target_frame)

        def delete_key(self, key, target_frame=None):
            if key == 'all':
                if messagebox.askyesno(title='Delete?',
                                       message='Delete all keys?'):
                    self.settings.keys.clear()
            else:
                del self.settings.keys[key]
            self.settings.edit_flag = True
            if target_frame:
                Window.destroy_elements(target_frame)
                self.show_keys(target_frame)

        def back(self):
            if self.settings.edit_flag:
                if messagebox.askyesno(title='Exit?',
                                       message='Exit without saving?'):
                    self.parent.init_menu_window()
            else:
                self.parent.init_menu_window()

        class AddEditWindow:
            def __init__(self, root, settings, key=None):
                self.window = Toplevel(root)
                key_val = StringVar()
                self.window.transient(root)
                self.window.grab_set()
                self.window.focus_set()
                if key:
                    button_text = 'Edit'
                    key_val.set(key)
                else:
                    button_text = 'Add'
                self.window.title(button_text +
                                  ' key (Transform Image TinyPNG)')
                key_entry = Entry(self.window, textvariable=key_val, width=50)
                key_entry.pack(pady=5)
                key_entry.focus_set()
                frame = Frame(self.window)
                frame.pack()
                Button(frame,
                       text=button_text,
                       width=10,
                       background='#888',
                       foreground='#000',
                       command=lambda: self.add_or_edit_key(
                           settings, key_val, key)).pack(side='left', padx=5)
                Button(frame,
                       text='Cancel',
                       width=10,
                       background='#888',
                       foreground='#000',
                       command=self.window.destroy).pack(side='left', padx=5)
                Window.center_window(self.window)

                self.window.wait_window()

            def add_or_edit_key(self, settings, key_val, key):
                if tPNG.validate_key(key_val.get()):
                    old_keys = settings.keys
                    new_keys = {}
                    if key:
                        for old_key in old_keys:
                            if old_key == key:
                                new_keys.update({key_val.get(): ''})
                            else:
                                new_keys.update({old_key: old_keys[old_key]})
                        old_keys.clear()
                        old_keys.update(new_keys)
                    else:
                        old_keys.update({key_val.get(): ''})
                    settings.edit_flag = True
                    self.window.destroy()
                else:
                    Window.error_message('invalid_key')
 def __init__(self, parent):
     self.parent = parent
     self.settings = Settings(self.parent.settings)
     self.settings.edit_flag = False
     self.frame0 = Frame(self.parent)
     self.title = Label(self.frame0, text='Settings', font='arial 20')
     self.BackButton = Button(self.title,
                              text='<< Back',
                              background='#888',
                              foreground='#000',
                              padx='0',
                              width='8',
                              pady='0',
                              command=self.back)
     self.frame1 = Frame(self.parent,
                         relief='groove',
                         bd=1,
                         height=150,
                         width=480)
     self.frame1.pack_propagate(0)
     self.canvas = Canvas(self.frame1)
     self.frame_keys = Frame(self.canvas)
     self.scrollbar_keys = Scrollbar(self.frame1,
                                     orient="vertical",
                                     command=self.canvas.yview)
     self.canvas.configure(yscrollcommand=self.scrollbar_keys.set)
     self.frame_keys.bind("<Configure>", self.scrolling)
     self.frame_keys.bind_all("<MouseWheel>", self._on_mousewheel)
     self.frame_actions = Frame(self.parent)
     self.AddButton = Button(
         self.frame_actions,
         text='Add key',
         background='#888',
         foreground='#000',
         padx='2',
         pady='0',
         width='10',
         command=lambda: self.add_key(self.frame_keys))
     self.ClearButton = Button(
         self.frame_actions,
         text='Clear keys',
         background='#888',
         foreground='#000',
         padx='2',
         pady='0',
         width='10',
         command=lambda: self.delete_key('all', self.frame_keys))
     self.GetKeyButton = Button(self.frame_actions,
                                text='Get API key',
                                background='#888',
                                foreground='#000',
                                padx='2',
                                pady='0',
                                width='10',
                                command=lambda: webbrowser.open_new_tab(
                                    'https://tinypng.com/developers'))
     self.SaveButton = Button(
         self.parent,
         text='Save',
         background='#888',
         foreground='#000',
         padx='2',
         pady='0',
         width='10',
         font='arial 12',
         command=lambda: self.parent.settings.save_settings(
             self.settings, self.parent.init_menu_window))
Esempio n. 10
0
class App(Frame):
    def log(self, value):
        self.text.configure(state="normal")
        self.text.insert(END, value + "\n")
        self.text.see(END)
        self.text.configure(state="disabled")

    def _set_download_buttons(self, state):
        if state:
            self.btn_download.configure(state="normal")
            self.btn_download_txt.configure(state="normal")
        else:
            self.btn_download.configure(state="disabled")
            self.btn_download_txt.configure(state="disabled")

    def download(self):
        username_text = self.entry_filename.get()
        if not username_text:
            messagebox.showinfo(title="Warning", message="Please input usernames")
            return
        self._set_download_buttons(False)
        usernames = username_text.split(",")
        self.core.root_path = self.root_path.get()
        self.core.download_by_usernames(usernames, self.combobox_type.current())
        self._set_download_buttons(True)

    def download_txt(self):
        self.btn_download.configure(state="disabled")
        self.btn_download_txt.configure(state="disabled")
        filename = os.path.normpath(
            filedialog.askopenfilename(
                filetypes=(("text files", "*.txt"), ("all files", "*.*"))
            )
        )
        if filename != ".":
            with open(filename, "r", encoding="utf-8") as f:
                usernames = []
                # 预处理,去掉注释与空白符
                for username in f.readlines():
                    username = username.strip()
                    if not username:
                        continue
                    sharp_at = username.find("#")
                    if sharp_at == 0:
                        continue
                    if sharp_at != -1:
                        username = username[:sharp_at]
                    usernames.append(username.strip())
            self.core.root_path = self.root_path.get()
            self.core.download_by_usernames(usernames, self.combobox_type.current())
        self.btn_download.configure(state="normal")
        self.btn_download_txt.configure(state="normal")

    def load_root_path(self):
        return config.read_config("config.ini", "Paths", "root_path")

    def save_root_path(self, root_path):
        config.write_config("config.ini", "Paths", "root_path", root_path)

    def browse_directory(self):
        root_path = os.path.normpath(filedialog.askdirectory())
        if root_path:
            self.root_path.set(root_path)
            self.save_root_path(root_path)

    def createWidgets(self):
        frame_tool = Frame(self.window)
        frame_path = Frame(self.window)
        frame_log = Frame(self.window)
        self.lbl_username = Label(frame_tool, text="Usernames(split by ','):")
        self.entry_filename = Entry(frame_tool)
        self.btn_download = Button(
            frame_tool,
            text="Download",
            command=lambda: self.invoke(self.download),
        )
        self.btn_download_txt = Button(
            frame_tool,
            text="Download txt",
            command=lambda: self.invoke(self.download_txt),
        )
        self.lbl_type = Label(frame_path, text="Type:")
        self.combobox_type = ttk.Combobox(frame_path, state="readonly")
        self.combobox_type["values"] = ("all", "image", "video")
        self.combobox_type.current(0)
        self.lbl_path = Label(frame_path, text="Path:")
        self.entry_path = Entry(frame_path, textvariable=self.root_path)
        self.btn_path_dialog = Button(
            frame_path, text="Browse", command=self.browse_directory
        )
        self.scrollbar = Scrollbar(frame_log)
        self.text = Text(frame_log)
        self.text.configure(state="disabled")
        self.lbl_status = Label(
            self.window,
            text="Feel free to use! Support: Sean Feng([email protected])",
        )

        frame_tool.pack(side=TOP, fill=X)
        self.lbl_username.pack(side=LEFT)
        self.entry_filename.pack(side=LEFT, fill=X, expand=True)
        self.btn_download.pack(side=LEFT)
        self.btn_download_txt.pack(side=LEFT)
        frame_path.pack(side=TOP, fill=X)
        self.lbl_type.pack(side=LEFT)
        self.combobox_type.pack(side=LEFT)
        self.lbl_path.pack(side=LEFT)
        self.entry_path.pack(side=LEFT, fill=X, expand=True)
        self.btn_path_dialog.pack(side=LEFT)
        self.text.pack(side=LEFT, fill=BOTH, expand=True)
        self.scrollbar.pack(side=LEFT, fill=Y)
        frame_log.pack(side=TOP, fill=BOTH, expand=True)
        self.scrollbar.config(command=self.text.yview)
        self.text.config(yscrollcommand=self.scrollbar.set)
        self.text.focus()
        self.lbl_status.pack(side=LEFT, fill=X, expand=True)

    def invoke(self, func):
        def done_callback(worker):
            worker_exception = worker.exception()
            if worker_exception:
                self.log(str(worker_exception))
                self._set_download_buttons(True)
                raise(worker_exception)
        return self.executor_ui.submit(func).add_done_callback(done_callback)

    def __init__(self, version):
        self.core = Core(self.log)
        master = Tk()
        Frame.__init__(self, master)
        master.title("ArtStation Downloader " + version)  # 定义窗体标题
        self.root_path = StringVar()
        self.root_path.trace_add(
            "write", lambda name, index, mode: self.save_root_path(self.root_path.get())
        )
        root_path_config = self.load_root_path()
        self.root_path.set(
            root_path_config or os.path.join(os.path.expanduser("~"), "ArtStation")
        )
        self.executor_ui = futures.ThreadPoolExecutor(1)
        self.window = master
        self.pack()
        self.createWidgets()
Esempio n. 11
0
    menu_bar.add_cascade(label="Tentang", menu=about_menu)


menuBarConstruct()  # Untuk menampilkan menu bar
root.config(menu=menu_bar)

lbl_welcome = Label(root,
                    text="Selamat datang di program pembaca teks dari gambar")
btn_input = Button(root, text="Masukkan gambar", command=openImage)

lbl_welcome.config(font=("Arial", 20))
lbl_welcome.pack()

btn_input.config(font=("Arial", 12))
btn_input.pack()

imgPanel = Label(root, image="")
imgPanel.pack()

lbl_OCR = Label(root, text="")
lbl_OCR.pack()

content_text = Text(root, wrap="word", undo=1)
content_text.pack(expand="yes", fill="both")
scroll_bar = Scrollbar(content_text)
content_text.configure(yscrollcommand=scroll_bar.set)
scroll_bar.config(command=content_text.yview)
scroll_bar.pack(side="right", fill="y")

root.mainloop()
Esempio n. 12
0
    def __init__(self, root, lexer):

        self.root = root
        self.TITLE = "Simple IO"
        self.file_path = None
        self.set_title()

        self.fontSize = 12

        self.lexer = lexer
        self.bootstrap = [self.recolorize]

        frame = Frame(root)
        # Scroll Bar [X and Y]
        self.xscrollbar = Scrollbar(root, orient="horizontal")
        self.yscrollbar = Scrollbar(root, orient="vertical")

        # Textbox (The main text input area)
        self.editor = Text(frame,
                           yscrollcommand=self.yscrollbar.set,
                           xscrollcommand=self.xscrollbar.set,
                           bg="#FFFFFF",
                           fg="#000000",
                           insertbackground="#000000")
        self.editor.pack(side="left", fill="both", expand=1)
        self.editor.config(wrap="none",
                           undo=True,
                           width=self.windowWidth,
                           height=self.windowHeight,
                           font=("Consolas", self.fontSize),
                           tabs=('1c'))
        self.editor.focus()
        self.create_tags()

        # Scroll Bars packing
        self.xscrollbar.pack(side="bottom", fill="x")  # Horizontal Scroll Bar
        self.xscrollbar.config(command=self.editor.xview)
        self.yscrollbar.pack(side="right", fill="y")  # Vertial Scroll Bar
        self.yscrollbar.config(command=self.editor.yview)

        # ## Status Bar ## #
        self.statusText = (("Font Size: " + str(self.fontSize)) + " | " +
                           "Langauge: " + self.currentLanguageName)
        self.status = Label(root,
                            text=self.statusText,
                            relief=tkinter.SUNKEN,
                            anchor='w')
        self.status.pack(side=tkinter.BOTTOM, fill=tkinter.X)

        frame.pack(fill="both", expand=1)

        #instead of closing the window, execute a function. Call file_quit
        root.protocol("WM_DELETE_WINDOW", self.file_quit)

        #create a top level menu
        self.menubar = Menu(root)

        #Menu item: File
        filemenu = Menu(
            self.menubar,
            tearoff=0)  # tearoff = 0 => can't be seperated from window
        filemenu.add_command(label="New",
                             command=self.file_new,
                             accelerator="Ctrl+N")
        filemenu.add_command(label="Open",
                             command=self.file_open,
                             accelerator="Ctrl+O")
        filemenu.add_command(label="Save",
                             command=self.file_save,
                             accelerator="Ctrl+S")
        filemenu.add_command(label="Save As",
                             command=self.file_save_as,
                             accelerator="Ctrl+Alt+S")
        filemenu.add_separator()  # Adds a lines between the above elements
        filemenu.add_command(label="Exit",
                             command=self.file_quit,
                             accelerator="Ctrl+Q")
        self.menubar.add_cascade(label="File", menu=filemenu)

        # Menu item: View
        viewMenu = Menu(self.menubar, tearoff=0)
        viewMenu.add_command(label="Zoom In",
                             command=self.zoom_In,
                             accelerator="Ctrl+")
        viewMenu.add_command(label="Zoom Out",
                             command=self.zoom_Out,
                             accelerator="Ctrl-")
        self.menubar.add_cascade(label="View", menu=viewMenu)

        # Menu item: Color Scheme
        colorMenu = Menu(self.menubar, tearoff=0)
        colorMenu.add_command(
            label="Default", command=lambda: self.changeColorScheme("default"))
        colorMenu.add_command(
            label="Monokai", command=lambda: self.changeColorScheme("monokai"))
        self.menubar.add_cascade(label="Color Scheme", menu=colorMenu)

        # Menu item: Languages
        languageMenu = Menu(self.menubar, tearoff=0)
        languageMenu.add_command(label="Plain Text",
                                 command=self.languageLexerToPlain)
        languageMenu.add_command(label="Python",
                                 command=self.languageLexerToPython)
        self.menubar.add_cascade(label="Language", menu=languageMenu)

        # display the menu
        root.config(menu=self.menubar)
Esempio n. 13
0
class Editor(object):
    currentLanguageName = "Plain Text"
    currentStyleName = "default"
    windowWidth = 100
    windowHeight = 25

    def __init__(self, root, lexer):

        self.root = root
        self.TITLE = "Simple IO"
        self.file_path = None
        self.set_title()

        self.fontSize = 12

        self.lexer = lexer
        self.bootstrap = [self.recolorize]

        frame = Frame(root)
        # Scroll Bar [X and Y]
        self.xscrollbar = Scrollbar(root, orient="horizontal")
        self.yscrollbar = Scrollbar(root, orient="vertical")

        # Textbox (The main text input area)
        self.editor = Text(frame,
                           yscrollcommand=self.yscrollbar.set,
                           xscrollcommand=self.xscrollbar.set,
                           bg="#FFFFFF",
                           fg="#000000",
                           insertbackground="#000000")
        self.editor.pack(side="left", fill="both", expand=1)
        self.editor.config(wrap="none",
                           undo=True,
                           width=self.windowWidth,
                           height=self.windowHeight,
                           font=("Consolas", self.fontSize),
                           tabs=('1c'))
        self.editor.focus()
        self.create_tags()

        # Scroll Bars packing
        self.xscrollbar.pack(side="bottom", fill="x")  # Horizontal Scroll Bar
        self.xscrollbar.config(command=self.editor.xview)
        self.yscrollbar.pack(side="right", fill="y")  # Vertial Scroll Bar
        self.yscrollbar.config(command=self.editor.yview)

        # ## Status Bar ## #
        self.statusText = (("Font Size: " + str(self.fontSize)) + " | " +
                           "Langauge: " + self.currentLanguageName)
        self.status = Label(root,
                            text=self.statusText,
                            relief=tkinter.SUNKEN,
                            anchor='w')
        self.status.pack(side=tkinter.BOTTOM, fill=tkinter.X)

        frame.pack(fill="both", expand=1)

        #instead of closing the window, execute a function. Call file_quit
        root.protocol("WM_DELETE_WINDOW", self.file_quit)

        #create a top level menu
        self.menubar = Menu(root)

        #Menu item: File
        filemenu = Menu(
            self.menubar,
            tearoff=0)  # tearoff = 0 => can't be seperated from window
        filemenu.add_command(label="New",
                             command=self.file_new,
                             accelerator="Ctrl+N")
        filemenu.add_command(label="Open",
                             command=self.file_open,
                             accelerator="Ctrl+O")
        filemenu.add_command(label="Save",
                             command=self.file_save,
                             accelerator="Ctrl+S")
        filemenu.add_command(label="Save As",
                             command=self.file_save_as,
                             accelerator="Ctrl+Alt+S")
        filemenu.add_separator()  # Adds a lines between the above elements
        filemenu.add_command(label="Exit",
                             command=self.file_quit,
                             accelerator="Ctrl+Q")
        self.menubar.add_cascade(label="File", menu=filemenu)

        # Menu item: View
        viewMenu = Menu(self.menubar, tearoff=0)
        viewMenu.add_command(label="Zoom In",
                             command=self.zoom_In,
                             accelerator="Ctrl+")
        viewMenu.add_command(label="Zoom Out",
                             command=self.zoom_Out,
                             accelerator="Ctrl-")
        self.menubar.add_cascade(label="View", menu=viewMenu)

        # Menu item: Color Scheme
        colorMenu = Menu(self.menubar, tearoff=0)
        colorMenu.add_command(
            label="Default", command=lambda: self.changeColorScheme("default"))
        colorMenu.add_command(
            label="Monokai", command=lambda: self.changeColorScheme("monokai"))
        self.menubar.add_cascade(label="Color Scheme", menu=colorMenu)

        # Menu item: Languages
        languageMenu = Menu(self.menubar, tearoff=0)
        languageMenu.add_command(label="Plain Text",
                                 command=self.languageLexerToPlain)
        languageMenu.add_command(label="Python",
                                 command=self.languageLexerToPython)
        self.menubar.add_cascade(label="Language", menu=languageMenu)

        # display the menu
        root.config(menu=self.menubar)

    # If user trys to quit while there is unsaved content
    def save_if_modified(self, event=None):
        print("Checking if current save is modified...")
        if self.editor.edit_modified():  #modified
            print("Current save is modified")
            response = messagebox.askyesnocancel(
                "Save?",
                "This document has been modified. Do you want to save changes?"
            )  #yes = True, no = False, cancel = None
            if response:  #yes/save
                result = self.file_save()
                if result == "saved":  #saved
                    print("Saved")
                    return True
                else:  #save cancelled
                    return None
            else:
                return response  #None = cancel/abort, False = no/discard
        else:  #not modified
            return True

    def updateStatusBar(self, event=None):
        self.statusText = (("Font Size: " + str(self.fontSize)) + " | " +
                           "Langauge: " + self.currentLanguageName)
        self.status.config(text=self.statusText)

# FILE MENU FUNCTIONS
##############################################################################################

# NEW FILE

    def file_new(self, event=None):
        result = self.save_if_modified()
        if result != None:  #None => Aborted or Save cancelled, False => Discarded, True = Saved or Not modified
            self.editor.delete(1.0, "end")
            self.editor.edit_modified(False)
            self.editor.edit_reset()
            self.file_path = None
            self.set_title()

    # OPEN FILE
    def file_open(self, event=None, filepath=None):
        result = self.save_if_modified()
        if result != None:  #None => Aborted or Save cancelled, False => Discarded, True = Saved or Not modified
            if filepath == None:
                filepath = filedialog.askopenfilename()
            if filepath != None and filepath != '':
                with open(filepath, encoding="utf-8") as f:
                    fileContents = f.read()  # Get all the text from file.
                # Set current text to file contents
                self.editor.delete(1.0, "end")
                self.editor.insert(1.0, fileContents)
                self.editor.edit_modified(False)
                self.file_path = filepath

    # SAVE FILE
    def file_save(self, event=None):
        if self.file_path == None:
            result = self.file_save_as()
        else:
            result = self.file_save_as(filepath=self.file_path)
        return result

    # SAVE AS
    def file_save_as(self, event=None, filepath=None):
        if filepath == None:
            filepath = tkinter.filedialog.asksaveasfilename(
                filetypes=(('Text files', '*.txt'), ('Python files',
                                                     '*.py *.pyw'),
                           ('All files', '*.*')))  #defaultextension='.txt'
        try:
            with open(filepath, 'wb') as f:
                text = self.editor.get(1.0, "end-1c")
                f.write(bytes(text, 'UTF-8'))
                self.editor.edit_modified(False)
                self.file_path = filepath
                self.set_title()
                return "saved"
        except FileNotFoundError:
            print('FileNotFoundError')
            return "cancelled"

    # QUIT
    def file_quit(self, event=None):
        result = self.save_if_modified()
        if result != None:  #None => Aborted or Save cancelled, False => Discarded, True = Saved or Not modified
            print("Exiting with code: 0")
            self.root.destroy()  #sys.exit(0)

    # Show the file name on the top of the window
    def set_title(self, event=None):
        if self.file_path != None:
            title = os.path.basename(self.file_path)
        else:
            title = "Untitled"
        self.root.title(title + " - " + self.TITLE)

    def undo(self, event=None):
        self.editor.edit_undo()

    def redo(self, event=None):
        self.editor.edit_redo()

# VIEW MENU FUNCTIONS
###############################################################################################

    def zoom_Out(self, event=None):
        print("Zooming Out")
        if self.fontSize > 9:
            self.fontSize -= 1
            self.editor.config(font=("Helvetica", self.fontSize))
            self.updateStatusBar()

    def zoom_In(self, event=None):
        print("Zooming In")
        if self.fontSize < 50:
            self.fontSize += 1
            self.editor.config(font=("Helvetica", self.fontSize))
            self.updateStatusBar()

# LANGUAGE MENU FUNCTIONS
###############################################################################################

    def languageLexerToPlain(self, event=None):
        print("Setting language to: Plain Text")
        self.lexer = TextLexer()
        self.currentLanguageName = "Plain Text"
        self.create_tags()
        self.recolorize()
        self.updateStatusBar()

    def languageLexerToPython(self, event=None):
        print("Setting language to: Python")
        self.lexer = PythonLexer()
        self.currentLanguageName = "Python"
        self.create_tags()
        self.recolorize()
        self.updateStatusBar()

# COLOR SCHEME MENU FUNCTIONS
###############################################################################################

    def changeColorScheme(self, styleParam):
        self.currentStyleName = styleParam
        print("Changing style to: " + styleParam)
        self.create_tags()
        self.recolorize()

        # Changing the background color
        if styleParam == "default":
            self.editor.config(bg="#FFFFFF",
                               fg="#000000",
                               insertbackground="#000000")
        elif styleParam == "monokai":
            self.editor.config(bg="#272822",
                               fg="#FFFFFF",
                               insertbackground="#FFFFFF")


# EVENTS
###############################################################################################

    def event_KeyPressed(self, event=None):
        self.recolorize()

    def create_tags(self):
        """
            this method creates the tags associated with each distinct style element of the 
            source code 'dressing'
        """
        bold_font = font.Font(self.editor, self.editor.cget("font"))
        bold_font.configure(weight=font.BOLD)
        italic_font = font.Font(self.editor, self.editor.cget("font"))
        italic_font.configure(slant=font.ITALIC)
        bold_italic_font = font.Font(self.editor, self.editor.cget("font"))
        bold_italic_font.configure(weight=font.BOLD, slant=font.ITALIC)
        style = get_style_by_name(self.currentStyleName)

        for ttype, ndef in style:
            tag_font = None

            if ndef['bold'] and ndef['italic']:
                tag_font = bold_italic_font
            elif ndef['bold']:
                tag_font = bold_font
            elif ndef['italic']:
                tag_font = italic_font

            if ndef['color']:
                foreground = "#%s" % ndef['color']
            else:
                foreground = None

            self.editor.tag_configure(str(ttype),
                                      foreground=foreground,
                                      font=tag_font)

    # This methd colors the text by using the tokens in the lexer
    def recolorize(self):
        code = self.editor.get("1.0", "end-1c")
        tokensource = self.lexer.get_tokens(code)
        start_line = 1
        start_index = 0
        end_line = 1
        end_index = 0

        for ttype, value in tokensource:
            if "\n" in value:
                end_line += value.count("\n")
                end_index = len(value.rsplit("\n", 1)[1])
            else:
                end_index += len(value)

            if value not in (" ", "\n"):
                index1 = "%s.%s" % (start_line, start_index)
                index2 = "%s.%s" % (end_line, end_index)

                for tagname in self.editor.tag_names(index1):  # FIXME
                    self.editor.tag_remove(tagname, index1, index2)

                self.editor.tag_add(str(ttype), index1, index2)

            start_line = end_line
            start_index = end_index

    def main(self, event=None):
        # Key bindings
        self.editor.bind("<Control-o>", self.file_open)  # Open File
        self.editor.bind("<Control-O>", self.file_open)  # ^
        self.editor.bind("<Control-S>", self.file_save)  # Save File
        self.editor.bind("<Control-s>", self.file_save)  # ^
        self.editor.bind("<Control-q>", self.file_quit)  # Quit Application
        self.editor.bind("<Control-Q>", self.file_quit)  # ^
        self.editor.bind("<Control-y>", self.redo)  # Redo Action
        self.editor.bind("<Control-Y>", self.redo)  # ^
        self.editor.bind("<Control-Z>", self.undo)  # Undo Action
        self.editor.bind("<Control-z>", self.undo)  # ^
        self.editor.bind("<Control-minus>", self.zoom_Out)
        self.editor.bind("<Control-plus>", self.zoom_In)
        self.editor.bind("<Key>", self.event_KeyPressed)
Esempio n. 14
0
    def _body(self):
        '''
        Set up frame and widgets.
        '''

        for i in range(4):
            self.grid_columnconfigure(i, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self.option_add("*Font", self.__app.font_sm)

        # Serial port settings
        self._frm_basic = Frame(self)
        self._lbl_port = Label(self._frm_basic, text="Port")
        self._lbx_port = Listbox(self._frm_basic, border=2,
                                 relief="sunken", bg=ENTCOL,
                                 width=28, height=5, justify=LEFT,
                                 exportselection=False)
        self._scr_portv = Scrollbar(self._frm_basic, orient=VERTICAL)
        self._scr_porth = Scrollbar(self._frm_basic, orient=HORIZONTAL)
        self._lbx_port.config(yscrollcommand=self._scr_portv.set)
        self._lbx_port.config(xscrollcommand=self._scr_porth.set)
        self._scr_portv.config(command=self._lbx_port.yview)
        self._scr_porth.config(command=self._lbx_port.xview)
        self._lbx_port.bind("<<ListboxSelect>>", self._on_select_port)
        self._lbl_baudrate = Label(self._frm_basic, text="Baud rate")
        self._spn_baudrate = Spinbox(self._frm_basic,
                                     values=(BAUDRATES),
                                     width=8, state=READONLY, readonlybackground=ENTCOL,
                                     wrap=True, textvariable=self._baudrate)
        self._btn_toggle = Button(self._frm_basic, text=ADVOFF, width=3,
                                  command=self._toggle_advanced)

        self._frm_advanced = Frame(self)
        self._lbl_databits = Label(self._frm_advanced, text="Data Bits")
        self._spn_databits = Spinbox(self._frm_advanced, values=(8, 7, 6, 5),
                                     width=3, state=READONLY, readonlybackground=ENTCOL,
                                     wrap=True, textvariable=self._databits)
        self._lbl_stopbits = Label(self._frm_advanced, text="Stop Bits")
        self._spn_stopbits = Spinbox(self._frm_advanced, values=(2, 1.5, 1),
                                     width=3, state=READONLY, readonlybackground=ENTCOL,
                                     wrap=True, textvariable=self._stopbits)
        self._lbl_parity = Label(self._frm_advanced, text="Parity")
        self._spn_parity = Spinbox(self._frm_advanced,
                                   values=("None", "Even", "Odd", "Mark", "Space"),
                                   width=6, state=READONLY, readonlybackground=ENTCOL,
                                   wrap=True, textvariable=self._parity)
        self._chk_rts = Checkbutton(self._frm_advanced, text="RTS/CTS",
                                    variable=self._rtscts)
        self._chk_xon = Checkbutton(self._frm_advanced, text="Xon/Xoff",
                                    variable=self._xonxoff)

        self._frm_buttons = Frame(self)
        self._btn_connect = Button(self._frm_buttons, width=45, height=35,
                                  image=self._img_conn,
                                  command=lambda: self.__app.serial_handler.connect())
        self._btn_disconnect = Button(self._frm_buttons, width=45, height=35,
                                     image=self._img_disconn,
                                     command=lambda: self.__app.serial_handler.disconnect(),
                                     state=DISABLED)
        self._btn_connect_file = Button(self._frm_buttons, width=45, height=35,
                                     image=self._img_dataread,
                                     command=lambda: self._on_data_stream())
        self._lbl_status_preset = Label(self._frm_buttons, font=self.__app.font_md2, text='')

        # Other configuration options
        self._frm_options = Frame(self)
        self._lbl_protocol = Label(self._frm_options, text=LBLPROTDISP)
        self._rad_nmea = Radiobutton(self._frm_options, text="NMEA",
                                    variable=self._protocol, value=NMEA_PROTOCOL)
        self._rad_ubx = Radiobutton(self._frm_options, text="UBX",
                                    variable=self._protocol, value=UBX_PROTOCOL)
        self._rad_all = Radiobutton(self._frm_options, text="ALL",
                                    variable=self._protocol, value=MIXED_PROTOCOL)
        self._lbl_consoledisplay = Label(self._frm_options, text=LBLDATADISP)
        self._rad_parsed = Radiobutton(self._frm_options, text="Parsed",
                                    variable=self._raw, value=0)
        self._rad_raw = Radiobutton(self._frm_options, text="Raw",
                                   variable=self._raw, value=1)
        self._lbl_format = Label(self._frm_options, text="Degrees Format")
        self._spn_format = Spinbox(self._frm_options,
                                  values=(DDD, DMS, DMM),
                                  width=6, state=READONLY, readonlybackground=ENTCOL,
                                  wrap=True, textvariable=self._format)
        self._lbl_units = Label(self._frm_options, text="Units")
        self._spn_units = Spinbox(self._frm_options,
                                  values=(UMM, UIK, UI, UMK),
                                  width=13, state=READONLY, readonlybackground=ENTCOL,
                                  wrap=True, textvariable=self._units)
        self._chk_scroll = Checkbutton(self._frm_options, text="Autoscroll",
                                      variable=self._autoscroll)
        self._spn_maxlines = Spinbox(self._frm_options,
                                     values=("100", "200", "500", "1000", "2000"),
                                    width=6, readonlybackground=ENTCOL, wrap=True,
                                    textvariable=self._maxlines, state=READONLY)
        self._chk_webmap = Checkbutton(self._frm_options, text="Web Map  Zoom",
                                      variable=self._webmap)
        self._scl_mapzoom = Scale(self._frm_options, from_=1, to=20, orient=HORIZONTAL,
                                  relief="sunken", bg=ENTCOL, variable=self._mapzoom)
        self._chk_datalog = Checkbutton(self._frm_options, text=LBLDATALOG,
                                        variable=self._datalog,
                                        command=lambda: self._on_data_log())

        self._chk_recordtrack = Checkbutton(self._frm_options, text=LBLTRACKRECORD,
                                        variable=self._record_track,
                                        command=lambda: self._on_record_track())

        self._lbl_ubxconfig = Label(self._frm_options, text=LBLUBXCONFIG)
        self._btn_ubxconfig = Button(self._frm_options, width=45, height=35,
                                     text='UBX', image=self._img_ubxconfig,
                                     command=lambda: self._on_ubx_config(),
                                     state=DISABLED)
Esempio n. 15
0
    def __init__(self, master):
        ## High-level Layout
        input_frame = Frame(master)
        notes_frame = Frame(master)

        input_frame.pack(fill=X, padx=15)
        notes_frame.pack(fill=BOTH, expand=True, padx=10, pady=10)

        ## Input Frame Setup
        note_name_label = Label(input_frame, text="Note Name: ")
        note_name_label.pack(side=LEFT)

        self.note_name_entry_strvar = StringVar()
        self.note_name_entry_strvar.set("")
        self.note_name_entry_strvar.trace("w", self.note_name_entry_changed)
        self.note_name_entry = Entry(input_frame,
                                     textvariable=self.note_name_entry_strvar)
        note_name_entry = self.note_name_entry
        note_name_entry.pack(side=LEFT, fill=X, expand=True)
        note_name_entry.focus_set()
        note_name_entry.bind("<Return>", self.note_name_action_callback)
        note_name_entry.bind("<KP_Enter>", self.note_name_action_callback)

        self.note_name_action_strvar = StringVar()
        note_name_action_strvar = self.note_name_action_strvar
        note_name_action_strvar.set("Add")
        note_name_action_button = Button(
            input_frame,
            textvar=note_name_action_strvar,
            command=self.note_name_action_callback)
        note_name_action_button.pack(side=LEFT)
        clear_note_name_button = Button(input_frame,
                                        text="Clear",
                                        command=self.clear_note_name_entry)
        clear_note_name_button.pack(side=LEFT)

        ## Notes Frame Setup
        # List of existing notes
        self.note_names_label_strvar = StringVar()
        note_names_label_strvar = self.note_names_label_strvar
        note_names_label = Label(notes_frame, textvar=note_names_label_strvar)
        note_names_label.pack(anchor=W)

        note_names_listbox = self.note_names_listbox = Listbox(notes_frame)
        note_names_listbox.pack(side=LEFT, fill=BOTH, expand=True)
        note_names_listbox.bind("<Return>", self.open_note_from_listbox)
        note_names_listbox.bind("<KP_Enter>", self.open_note_from_listbox)
        note_names_listbox.bind("<Double-Button-1>",
                                self.open_note_from_listbox)

        # Add scrollbar to list of notes
        notes_scrollbar = Scrollbar(notes_frame)
        notes_scrollbar.pack(side=LEFT, fill=Y)
        note_names_listbox.config(yscrollcommand=notes_scrollbar.set)
        notes_scrollbar.config(command=note_names_listbox.yview)

        ## Controls
        note_controls = Frame(notes_frame)
        note_controls.pack(side=LEFT, fill=Y)

        open_note_button = Button(note_controls,
                                  text="Open",
                                  command=self.open_note_from_listbox)
        open_note_button.pack(fill=X)

        delete_note_button = Button(note_controls,
                                    text="Delete",
                                    command=self.delete_note_from_listbox)
        delete_note_button.pack(fill=X)

        ## Final Initialization
        self.load_config()
        self.load_notes_list()
        self.update_note_names_list()
Esempio n. 16
0
def draw_window():
    global root
    global text
    global label_design_file
    # initialize tkinter
    root = Tk()

    # set window props
    root.wm_title("Swimlanes Diagram")
    root.resizable(True, True)
    root.geometry('800x600')

    # Textarea
    editor_frame = Frame(root)
    editor_frame.pack(fill=BOTH, expand=True)

    # Horizontal (x) Scroll bar
    x_scrollbar = Scrollbar(editor_frame, orient=HORIZONTAL)
    x_scrollbar.pack(side=BOTTOM, fill=X)

    # Vertical (y) Scroll Bar
    y_scrollbar = Scrollbar(editor_frame)
    y_scrollbar.pack(side=RIGHT, fill=Y)

    # Text Widget
    text = Text(editor_frame, wrap=NONE, undo=True, xscrollcommand=x_scrollbar.set, yscrollcommand=y_scrollbar.set,
                borderwidth=3)
    text.pack(expand=True, fill='both')

    # Configure the scrollbars
    x_scrollbar.config(command=text.xview)
    y_scrollbar.config(command=text.yview)

    button_frame = Frame(root)
    button_frame.pack(fill=X)

    generate_svg_button = Button(button_frame, text="Generate and View SVG", command=generate_and_view)
    generate_svg_button.pack(side=RIGHT, padx=5, pady=5)

    label_design_file = Label(button_frame)
    label_design_file.pack(side=LEFT, padx=5, pady=5)

    # Menu
    menu_bar = Menu(root)
    file_menu = Menu(menu_bar, tearoff=0)
    file_menu.add_command(label="New", command=lambda: text.delete(1.0, END))
    file_menu.add_command(label="Open", command=select_and_load_file)
    file_menu.add_command(label="Save", command=donothing)
    file_menu.add_command(label="Save as...", command=save_file_as)
    file_menu.add_command(label="Close", command=on_closing)

    menu_bar.add_cascade(label="File", menu=file_menu)

    create_settings_dir_if_needed()

    # show window
    root.config(menu=menu_bar)
    root.protocol("WM_DELETE_WINDOW", on_closing)
    root.mainloop()
Esempio n. 17
0
    def __init__(
        self,
        master,
        column_names,
        rows=None,
        column_weights=None,
        scrollbar=True,
        click_to_sort=True,
        reprfunc=None,
        cnf={},
        **kw
    ):
        """
        Construct a new Table widget.

        :type master: Tkinter.Widget
        :param master: The widget that should contain the new table.
        :type column_names: list(str)
        :param column_names: A list of names for the columns; these
            names will be used to create labels for each column;
            and can be used as an index when reading or writing
            cell values from the table.
        :type rows: list(list)
        :param rows: A list of row values used to initialze the table.
            Each row value should be a tuple of cell values, one for
            each column in the row.
        :type scrollbar: bool
        :param scrollbar: If true, then create a scrollbar for the
            new table widget.
        :type click_to_sort: bool
        :param click_to_sort: If true, then create bindings that will
            sort the table's rows by a given column's values if the
            user clicks on that colum's label.
        :type reprfunc: function
        :param reprfunc: If specified, then use this function to
            convert each table cell value to a string suitable for
            display.  ``reprfunc`` has the following signature:
            reprfunc(row_index, col_index, cell_value) -> str
            (Note that the column is specified by index, not by name.)
        :param cnf, kw: Configuration parameters for this widget's
            contained ``MultiListbox``.  See ``MultiListbox.__init__()``
            for details.
        """
        self._num_columns = len(column_names)
        self._reprfunc = reprfunc
        self._frame = Frame(master)

        self._column_name_to_index = dict((c, i) for (i, c) in enumerate(column_names))

        # Make a copy of the rows & check that it's valid.
        if rows is None:
            self._rows = []
        else:
            self._rows = [[v for v in row] for row in rows]
        for row in self._rows:
            self._checkrow(row)

        # Create our multi-list box.
        self._mlb = MultiListbox(self._frame, column_names, column_weights, cnf, **kw)
        self._mlb.pack(side="left", expand=True, fill="both")

        # Optional scrollbar
        if scrollbar:
            sb = Scrollbar(self._frame, orient="vertical", command=self._mlb.yview)
            self._mlb.listboxes[0]["yscrollcommand"] = sb.set
            # for listbox in self._mlb.listboxes:
            #    listbox['yscrollcommand'] = sb.set
            sb.pack(side="right", fill="y")
            self._scrollbar = sb

        # Set up sorting
        self._sortkey = None
        if click_to_sort:
            for i, l in enumerate(self._mlb.column_labels):
                l.bind("<Button-1>", self._sort)

        # Fill in our multi-list box.
        self._fill_table()
Esempio n. 18
0
class Display(Canvas):
    """This is a class that manages the display of the GUI.

    The display of the GUI implements a canvas where the user can visually
    see the states of the machine and the transitions between them. The user
    is able to freely move around the states for a better view and select
    transitions to view their information.

    Attributes:
        machine (utils.Machine): The machine of the user.
        info_manager (InfoManager): THe object that handles the info section
            of the GUI.
    """
    def __init__(self, master, machine):
        """Initialize this display with the user's machine.

        Parameters:
            machine (utils.Machine): The machine of the user.
        """
        super().__init__(master=master, bg='light gray')
        self.machine = machine
        self.info_manager = InfoManager(self, machine)
        self.pack(fill='both', expand=True)
        # scrollbars for the canvas
        self._xsb = Scrollbar(self, orient='horizontal', command=self.xview)
        self._ysb = Scrollbar(self, orient='vertical', command=self.yview)
        self.config(xscrollcommand=self._xsb.set,
                    yscrollcommand=self._ysb.set,
                    scrollregion=(0, 0, 1000, 1000))
        self._xsb.pack(side='bottom', fill='x')
        self._ysb.pack(side='right', fill='y')
        # bindings to allow a pannable canvas
        self.bind('<ButtonPress-1>', self._pan_start)
        self.bind('<B1-Motion>', self._pan_exec)
        # boolean to indicate the user is moving a state instead of panning the canvas
        self._moving_obj = False
        # maps state_num to state_id
        self._id_map = {}
        # set of line_ids of lines between two states close to each other
        self._mini_lines = set([])
        # set of all loop transitions
        self._loops = set([])
        # id of init state
        self._init_id = None
        # config used by lines/transitions in the canvas
        self._lines_config = {
            'arrow': 'last',
            'width': 2,
            'activewidth': 4,
            'activefill': 'gray40'
        }
        # id of highlighted state, for sequential tests
        self._highlighted_state_id = None
        # default color of states
        self._default_state_fill = 'linen'
        # color of a highlighted state
        self._highlight_fill = 'gold'
        # lines less than threshold are mini lines, connecting states center to center
        self._line_thrshld = 35

    def _pan_start(self, event):
        # start the panning of the canvas if the user is not moving a state
        if not self._moving_obj:
            self.scan_mark(event.x, event.y)

    def _pan_exec(self, event):
        # execute the panning of the canvas is the user is not moving a state
        if not self._moving_obj:
            self.scan_dragto(event.x, event.y, gain=1)

    def _get_line_dist(self, x1, y1, x2, y2):
        # return the distance between two points
        return sqrt((x2 - x1)**2 + (y2 - y1)**2)

    def _get_raw_linecoords(self, *coords):
        # return the centers of the circles the coordinates pertain to;
        # lines drawn on the canvas do not overlap the circles/states, so
        # this function returns the coordinates as if they were center to center
        head = (coords[2], coords[3])
        tail = (coords[0], coords[1])
        y = head[1] - tail[1]
        y_sgn = -1 if y < 0 else 1
        x = head[0] - tail[0]
        x_sgn = -1 if x < 0 else 1
        try:
            theta = atan(abs(y) / abs(x))
            # circle radius = 13
            x_offset = x_sgn * 13 * cos(theta)
            y_offset = y_sgn * 13 * sin(theta)
        except ZeroDivisionError:
            x_offset = 0
            y_offset = y_sgn * 13
        return (tail[0] - x_offset, tail[1] - y_offset, head[0] + x_offset,
                head[1] + y_offset)

    def _get_mod_linecoords(self, *coords):
        # return the modified line coordinates to draw on the canvas,
        # pertaining to the two circles/states specified by the given coords
        head = (coords[2], coords[3])
        tail = (coords[0], coords[1])
        dist = sqrt((head[0] - tail[0])**2 + (head[1] - tail[1])**2)
        if dist <= self._line_thrshld: return coords
        ratio = 13 / dist
        x_offset = ratio * (head[0] - tail[0])
        y_offset = ratio * (head[1] - tail[1])
        return (tail[0] + x_offset, tail[1] + y_offset, head[0] - x_offset,
                head[1] - y_offset)

    def _drag_line_head(self, line_id, event):
        # drag the head of the line specified by the line_id
        # to the coordinates of the event
        line_coords = self.coords(line_id)
        raw_linecoords = (line_coords[0], line_coords[1],
                          self.canvasx(event.x), self.canvasy(event.y))
        if line_id not in self._mini_lines:  # states are separated enough
            raw_linecoords = self._get_raw_linecoords(*line_coords)
            new_coords = (raw_linecoords[0], raw_linecoords[1],
                          self.canvasx(event.x), self.canvasy(event.y))
            mod_linecoords = self._get_mod_linecoords(*new_coords)
            if mod_linecoords == new_coords:  # line became small enough
                self._mini_lines.add(line_id)
        elif self._get_line_dist(
                *raw_linecoords
        ) >= self._line_thrshld:  # new line is large enough
            self._mini_lines.remove(line_id)
            mod_linecoords = self._get_mod_linecoords(*raw_linecoords)
        else:  # keep drawing small line
            mod_linecoords = raw_linecoords
        self.coords(line_id, *mod_linecoords)

    def _drag_loop(self, line_id, event):
        # drag a loop specified by the line_id to the coordinates of the event
        event_coords = (self.canvasx(event.x), self.canvasy(event.y))
        coords = (event_coords[0] - 7, event_coords[1] - 11,
                  event_coords[0] - 22, event_coords[1] - 36,
                  event_coords[0] + 18, event_coords[1] - 36,
                  event_coords[0] + 3, event_coords[1] - 11)
        self.coords(line_id, *coords)

    def _drag_line_tail(self, line_id, event):
        # drag the tail of a line specified by the line_id
        # to the coordinates of the event
        if line_id in self._loops:
            return self._drag_loop(line_id, event)
        line_coords = self.coords(line_id)
        raw_linecoords = (self.canvasx(event.x), self.canvasy(event.y),
                          line_coords[2], line_coords[3])
        if line_id not in self._mini_lines:  # states are separated enough
            raw_linecoords = self._get_raw_linecoords(*line_coords)
            new_coords = (self.canvasx(event.x), self.canvasy(event.y),
                          raw_linecoords[2], raw_linecoords[3])
            mod_linecoords = self._get_mod_linecoords(*new_coords)
            if mod_linecoords == new_coords:  # line became small enough
                self._mini_lines.add(line_id)
        elif self._get_line_dist(
                *raw_linecoords
        ) >= self._line_thrshld:  # new line is large enough
            self._mini_lines.remove(line_id)
            mod_linecoords = self._get_mod_linecoords(*raw_linecoords)
        else:  # keep drawing small line
            mod_linecoords = raw_linecoords
        self.coords(line_id, *mod_linecoords)

    def _drag(self, event, state_id):
        # drag the state around the canvas
        self._moving_obj = True
        coords = (self.canvasx(event.x) - 12, self.canvasy(event.y) - 12,
                  self.canvasx(event.x) + 13, self.canvasy(event.y) + 13)
        self.coords(state_id, *coords)
        self.coords(str(state_id) + 't', coords[0] + 12, coords[1] + 12)
        self.coords(
            str(state_id) + 'f', coords[0] - 3, coords[1] - 3, coords[2] + 3,
            coords[3] + 3)
        self.coords(
            str(state_id) + 'i', coords[0] - 20, coords[1] - 20, coords[0],
            coords[1])
        try:
            for line_id in self.find_withtag('-' + str(state_id)):
                self._drag_line_head(line_id, event)
        except KeyError:
            pass
        try:
            for line_id in self.find_withtag(str(state_id) + '-'):
                self._drag_line_tail(line_id, event)
        except KeyError:
            pass

    def _drop(self, event):
        # drop the state
        self._moving_obj = False

    def _update_status(self, state_num):
        # update the status bar with the specified state number
        if not self._moving_obj:
            self.info_manager.update_status('State {}'.format(state_num))

    def _clear_status(self):
        # clear the status bar if not moving a state
        if not self._moving_obj:
            self.info_manager.clear_status()

    def add_state(self, state_num, as_init):
        """Add a state to the display.

        Parameters:
            state_num (int): The state number of the newly added state.
            as_init (bool): Whether or not the newly added state is an initial state.
        """
        x, y = self.canvasx(75 + randrange(150)), self.canvasy(75 +
                                                               randrange(200))
        coords = (x, y, x + 25, y + 25)
        state_id = self.create_oval(*coords, fill=self._default_state_fill)
        tag = str(state_id) + 't'
        self.create_text(coords[0] + 13,
                         coords[1] + 13,
                         text=str(state_num),
                         tags=tag)
        self._id_map[state_num] = state_id
        self.tag_bind(state_id, '<B1-Motion>',
                      lambda e: self._drag(e, state_id))
        self.tag_bind(state_id, '<ButtonRelease-1>', self._drop)
        self.tag_bind(state_id, '<Enter>',
                      lambda e: self._update_status(state_num))
        self.tag_bind(state_id, '<Leave>', lambda e: self._clear_status())
        self.tag_bind(tag, '<B1-Motion>', lambda e: self._drag(e, state_id))
        self.tag_bind(tag, '<ButtonRelease-1>', self._drop)
        self.tag_bind(tag, '<Enter>', lambda e: self._update_status(state_num))
        self.info_manager.update_status('Added State {}'.format(state_num))
        if as_init:
            # draw init arrow to show as init state
            self.create_line(x - 20,
                             y - 20,
                             x,
                             y,
                             arrow=self._lines_config['arrow'],
                             tags=str(state_id) + 'i',
                             width=self._lines_config['width'])
            self._init_id = state_id

    def del_state(self, state_num, init_deleted):
        """Delete a state from the display.

        Parameters:
            state_num (int): The number of the state to delete.
            init_deleted (bool): Whether or not the state to delete is an initial state.
        """
        state_id = self._id_map[state_num]
        core_tag = str(state_id)
        self.delete(state_id)
        for line_id in self.find_withtag(core_tag + '-'):
            self._mini_lines.discard(line_id)
            self._loops.discard(line_id)
            self.delete(line_id)
        for line_id in self.find_withtag('-' + core_tag):
            self._mini_lines.discard(line_id)
            self.delete(line_id)
        self.delete(core_tag + 'f')
        self.delete(core_tag + 't')
        if init_deleted:
            self.delete(str(state_id) + 'i')
            if self.machine.init_state != 0:
                self.set_init(self.machine.init_state)

    def set_init(self, state_num):
        """Set the specified state as initial.

        The initial state has an arrow pointing to it with no source,
        indicating the entry point of the machine.

        Parameters:
            state_num (int): The number of the state to set as initial.
        """
        self.delete(str(self._init_id) + 'i')
        state_id = self._id_map[state_num]
        tag = str(state_id) + 'i'
        x, y, _, _ = self.coords(state_id)
        self.create_line(x - 20,
                         y - 20,
                         x,
                         y,
                         arrow=self._lines_config['arrow'],
                         tags=tag,
                         width=self._lines_config['width'])
        self._init_id = state_id

    def set_final(self, state_num):
        """Set the specified state as final.

        A final state is enclosed in another circle. In other words, a final state
        is indicated with another circle forming the outer edge of the original inner
        circle.

        Parameters:
            state_num (int): The number of the state to set as final.
        """
        state_id = self._id_map[state_num]
        tag = str(state_id) + 'f'
        if len(self.find_withtag(tag)) == 0:
            state_coords = self.coords(state_id)
            coords = (state_coords[0] - 3, state_coords[1] - 3,
                      state_coords[2] + 3, state_coords[3] + 3)
            self.create_oval(*coords, tags=tag)

    def set_nonfinal(self, state_num):
        """Set the specified state as non-final.

        Parameters:
            state_num (int): The number of the state to set as non-final.
        """
        state_id = self._id_map[state_num]
        tag = str(state_id) + 'f'
        self.delete(tag)

    def _add_loop(self, state_num):
        # add a loop transition to the specified state
        state_coords = self.coords(self._id_map[state_num])
        coords = (state_coords[0] + 6, state_coords[1] + 2,
                  state_coords[0] - 9, state_coords[1] - 23,
                  state_coords[0] + 31, state_coords[1] - 23,
                  state_coords[0] + 16, state_coords[1] + 2)
        tag1 = str(self._id_map[state_num]) + '-'
        tag2 = '{}-{}'.format(state_num, state_num)
        line_id = self.create_line(*coords,
                                   smooth=True,
                                   tags=(tag1, tag2),
                                   **self._lines_config)
        self.tag_bind(
            line_id, '<ButtonPress-1>',
            lambda e: self.info_manager.show_transitions(state_num, state_num))
        self._loops.add(line_id)

    def add_transition(self, from_state, to_state, cnf):
        """Add a transition to the display.

        Parameters:
            from_state (int): The state number of the source of the transition.
            to_state (int): The state number of the target of the transition.
            cnf (str): The configuration of the transition.
        """
        # may not need cnf
        find_result = self.find_withtag('{}-{}'.format(from_state, to_state))
        if len(find_result) == 1:
            line = find_result[0]
            if self.itemcget(line, 'arrow') == 'first':
                self.itemconfig(line, arrow='both')
            return
        elif len(self.find_withtag('{}-{}'.format(to_state, from_state))) == 1:
            line_id = self.find_withtag('{}-{}'.format(to_state,
                                                       from_state))[0]
            self.itemconfig(line_id, arrow='both')
            return
        if from_state == to_state:
            return self._add_loop(from_state)
        f_coords = self.coords(self._id_map[from_state])
        f_coords = (f_coords[0] + 13, f_coords[1] + 13)
        t_coords = self.coords(self._id_map[to_state])
        t_coords = (t_coords[0] + 13, t_coords[1] + 13)
        coords = (f_coords[0], f_coords[1], t_coords[0], t_coords[1])
        mini_line = self._get_line_dist(*coords) <= self._line_thrshld
        line_coords = self._get_mod_linecoords(
            *coords) if not mini_line else coords
        tag1 = str(self._id_map[from_state]) + '-'
        tag2 = '-' + str(self._id_map[to_state])
        tag3 = '{}-{}'.format(from_state, to_state)
        line_id = self.create_line(line_coords,
                                   tags=(tag1, tag2, tag3),
                                   **self._lines_config)
        if mini_line: self._mini_lines.add(line_id)
        self.tag_bind(
            line_id, '<ButtonPress-1>',
            lambda e: self.info_manager.show_transitions(from_state, to_state))

    def del_transition(self, from_state, to_state, cnf):
        """Delete a transition to the display.

        Parameters:
            from_state (int): The state number of the source of the transition.
            to_state (int): The state number of the target of the transition.
            cnf (str): The configuration of the transition.
        """
        # may not need cnf
        if self.machine.get_transition_count(from_state, to_state) != 0:
            return
        find_result1 = self.find_withtag('{}-{}'.format(from_state, to_state))
        find_result2 = self.find_withtag('{}-{}'.format(to_state, from_state))
        if len(find_result1) == 0 and len(
                find_result2) == 0:  # transition does not exist
            return
        elif len(find_result1) == 1:  # 'from_state-to_state' is tag
            line_id = find_result1[0]
            arrow_cnf = self.itemcget(line_id, 'arrow')
            if arrow_cnf == 'both':
                self.itemconfig(line_id, arrow='first')
            elif arrow_cnf == 'first':  # line exists, but transition does not exist
                return
            else:
                self._mini_lines.discard(line_id)
                self._loops.discard(line_id)
                self.delete(line_id)
        else:  # 'to_state-from_state' is tag
            line_id = find_result2[0]
            arrow_cnf = self.itemcget(line_id, 'arrow')
            if arrow_cnf == 'both':
                self.itemconfig(line_id, arrow='last')
            elif arrow_cnf == 'last':  # line exists, but transition does not exist
                return
            else:
                self._mini_lines.discard(line_id)
                self._loops.discard(line_id)
                self.delete(line_id)

    def highlight_state(self, state_num):
        """Highlight the specified state in the display.

        This is used during the sequential tests to indicate which state the
        machine is currently in.

        Parameters:
            state_num (int): The state number to highlight.
        """
        if self._highlighted_state_id is not None:
            self.itemconfig(self._highlighted_state_id,
                            fill=self._default_state_fill)
        state_id = self._id_map[state_num]
        self.itemconfig(state_id, fill=self._highlight_fill)
        self._highlighted_state_id = state_id

    def clear_highlight(self):
        """Clear the  highlighted state, if any."""
        if self._highlighted_state_id is not None:
            self.itemconfig(self._highlighted_state_id,
                            fill=self._default_state_fill)
            self._highlighted_state_id = None
Esempio n. 19
0
class Otch():
    def __init__(self):
        self.ot = Tk()
        self.ot.geometry('520x500')

        self.l_1 = Label(self.ot, text='Первый отчет')
        self.l_2 = Label(self.ot, text='Второй отчет')

        self.b_1 = Button(self.ot,
                          text='Download',
                          command=lambda: self.dow_one())
        self.b_2 = Button(self.ot,
                          text='Download',
                          command=lambda: self.dow_two())

        self.Fr1 = Frame(self.ot)
        self.Fr2 = Frame(self.ot)

        self.l_1.place(x='10', y='10')
        self.l_2.place(x='260', y='10')

        self.b_1.place(x='100', y='10')
        self.b_2.place(x='350', y='10')

        self.tex_1 = Text(self.Fr1,
                          width=45,
                          height=40,
                          font="Verdana 6",
                          wrap=WORD)
        self.scr_1 = Scrollbar(self.Fr1, command=self.tex_1.yview)
        self.tex_1.configure(yscrollcommand=self.scr_1.set)
        self.scr_1.pack(side='right', fill='y')
        self.Fr1.place(x='10', y='40')
        self.tex_1.pack(fill='both')

        self.tex_2 = Text(self.Fr2,
                          width=45,
                          height=40,
                          font="Verdana 6",
                          wrap=WORD)
        self.scr_2 = Scrollbar(self.Fr2, command=self.tex_2.yview)
        self.tex_2.configure(yscrollcommand=self.scr_2.set)
        self.scr_2.pack(side='right', fill='y')
        self.Fr2.place(x='260', y='40')
        self.tex_2.pack(fill='both')

        global vse
        global gr
        global pol

        self.vs = vse
        self.group = gr
        self.pols = pol

    def start(self):
        st1 = ''
        st2 = ''

        for idd, i in enumerate(self.pols):
            if "NO" in self.vs[idd]:
                st1 += i + " BLOCKED\n"
            if "-" in self.vs[idd][1:]:
                st1 += "Пользователь " + i + " не вступил в группы:\n"
                for idd_1, j in enumerate(self.vs[idd][1:]):
                    if j == "-":
                        st1 += "   " + self.group[idd_1] + "\n"
            st1 += '\n'
        if st1 == '': st1 = "Нет не подписавшихся"

        for idd, i in enumerate(self.group):
            tr = True
            for j in self.vs:
                if j[idd + 1] == '-':
                    if tr == True:
                        st2 += "В сообщество " + i + " не вступили люди от этих пабликов:\n"
                        tr = False
                    for q in self.group:
                        if j[0] == q.split(' ')[0]:
                            st2 += "   " + q + "\n"
                            break
            st2 += "\n"

        if st2 == '': st2 = "Нет не подписавшихся"

        self.tex_1.insert(1.0, st1)
        self.tex_2.insert(1.0, st2)
        self.ot.mainloop()

    def dow_one(self):
        name = "1var_" + str(datetime.datetime.now().day) + "_" + str(
            datetime.datetime.now().month) + "_" + str(
                datetime.datetime.now().year) + "__" + str(
                    datetime.datetime.now().hour) + "_" + str(
                        datetime.datetime.now().minute) + ".txt"
        t = open(name, 'w')
        t.write(self.tex_1.get('1.0', 'end'))
        t.close()

    def dow_two(self):
        name = "2var_" + str(datetime.datetime.now().day) + "_" + str(
            datetime.datetime.now().month) + "_" + str(
                datetime.datetime.now().year) + "__" + str(
                    datetime.datetime.now().hour) + "_" + str(
                        datetime.datetime.now().minute) + ".txt"
        t = open(name, 'w')
        t.write(self.tex_2.get('1.0', 'end'))
        t.close()
Esempio n. 20
0
class Watchman_reg():
    def __init__(self, master):
        # Global variable
        self.master = master
        self.regs = []
        self.flag_data = []
        self.UDP_IP = '192.168.1.10'
        self.UDP_PORT = 7
        self.cmd = [
            'write_all_reg', 'read_all_reg', 'ping', 'start_stop_stream',
            'stop_uC'
        ]
        self.stream_flag = False
        self.destroy_flag = False
        # Initialize the GUI
        self.init_window()
        self.init_UDP_connection()
        self.thread = Thread(target=self.thread_int, args=())
        self.run_flag = True
        self.toplevel_flag = False
        self.thread.start()

    def init_window(self):
        # Change window's title
        self.master.title("Watchman - registers")
        self.master.protocol(
            "WM_DELETE_WINDOW",
            self.exit_prog)  # when use close window with the red cross
        # Menu bar
        self.menu = Menu(self.master)
        self.master.config(menu=self.menu)
        self.submenu = Menu(self.menu)
        self.menu.add_cascade(label='Menu', menu=self.submenu)
        self.submenu.add_command(label='Load sequence...',
                                 command=self.openfile)
        self.submenu.add_command(label='Save sequence...',
                                 command=self.savefile)
        self.submenu.add_command(label='EXIT', command=self.exit_prog)
        self.menu.add_cascade(label='HELP', command=self.help_callback)
        # Table for the registers
        count = 0
        for i in range(0, 4, 2):
            for j in range(25):
                l = Label(self.master,
                          relief=RIDGE,
                          text=("    Reg. " + str(count) + "   "))
                l.grid(column=i, row=j, sticky=N + S + E + W)
                var = StringVar()
                var.trace('w', partial(self.entry_callback, count, var))
                e = Entry(self.master, relief=RIDGE, textvariable=var)
                e.grid(column=(i + 1), row=j, sticky=N + S + E + W)
                self.regs.append(e)
                self.flag_data.append(1)
                count += 1
        # Buttons
        self.btn_write_all = Button(self.master,
                                    text="Write all reg.",
                                    command=partial(self.send_command, 0))
        self.btn_write_all.grid(column=4,
                                row=0,
                                rowspan=2,
                                padx=5,
                                sticky=W + E)
        self.btn_write_all.configure(state="disable")
        self.btn_read_all = Button(self.master,
                                   text="Read all reg.",
                                   command=partial(self.send_command, 1))
        self.btn_read_all.grid(column=4,
                               row=2,
                               rowspan=2,
                               padx=5,
                               sticky=W + E)
        self.btn_ping = Button(self.master,
                               text="Ping",
                               command=partial(self.send_command, 2))
        self.btn_ping.grid(column=4, row=4, rowspan=2, padx=5, sticky=W + E)
        self.btn_stream = Button(self.master,
                                 text="Start stream.",
                                 command=partial(self.send_command, 3))
        self.btn_stream.grid(column=4, row=6, rowspan=2, padx=5, sticky=W + E)
        self.btn_stop = Button(self.master,
                               text="Stop uC",
                               command=partial(self.send_command, 4))
        self.btn_stop.grid(column=4, row=8, rowspan=2, padx=5, sticky=W + E)
        self.btn_graph = Button(self.master,
                                text="Open graph\nStore data",
                                command=self.open_graph)
        self.btn_graph.grid(column=4, row=22, rowspan=2, padx=5, sticky=W + E)
        # Listbox to show data transfert
        self.text = Text(self.master, width=40)
        self.text.grid(column=5, row=0, rowspan=25, pady=10, sticky=N + S)
        self.scrlbar = Scrollbar(self.master)
        self.scrlbar.grid(column=6,
                          row=0,
                          rowspan=25,
                          pady=10,
                          padx=5,
                          sticky=N + S)
        self.text.configure(yscrollcommand=self.scrlbar.set)
        self.scrlbar.configure(command=self.text.yview)
        self.text.insert(
            END,
            "List of command sent and received\n-------------------------")
        self.text.configure(state="disable")

    def openfile(self):
        file_path = filedialog.askopenfilename()
        if len(file_path) != 0:
            ff = open(file_path, 'r')
            for reg in self.regs:
                reg.delete(0, END)
                reg.insert(END, str(ff.readline())[:-1])
            ff.close()

    def savefile(self):
        if (sum(self.flag_data) == 0):
            file_path = filedialog.asksaveasfilename()
            if len(file_path) != 0:
                ff = open(file_path, 'w')
                for reg in self.regs:
                    ff.write(str(reg.get()) + "\n")
                ff.close()
        else:
            messagebox.showinfo(
                "Warning", "Every register value must be in the right format!")

    def exit_prog(self):
        if (self.toplevel_flag):
            self.close_graph()
            while (self.toplevel_flag):
                time.sleep(0.1)
        if (self.stream_flag):
            self.destroy_flag = True  # avoid problem while trying to change btn_stream's name
            self.send_command(3)
        while (self.stream_flag):
            time.sleep(0.1)
        self.run_flag = False  # stop the thread
        self.thread.join()
        self.sock.close()
        self.master.destroy()
        print("main destroy", file=sys.stderr)

    def help_callback(self):
        print("help_callback")

    def is_number(self, s):
        try:
            numb = int(s)
            if (numb >= 0):
                return True
            else:
                return False
        except ValueError:
            return False

    def entry_callback(self, count, var, *args):
        s = var.get()
        if (self.is_number(s) and (len(s) != 0)):
            if ((int(s) < 4096) and (int(s) >= 0)):
                self.regs[count].configure(fg="black")
                self.flag_data[count] = 0
            else:
                self.regs[count].configure(fg="red")
                self.flag_data[count] = 1
        else:
            self.regs[count].configure(fg="red")
            self.flag_data[count] = 1
        if (sum(self.flag_data) == 0):
            self.btn_write_all.configure(state="normal")
        else:
            self.btn_write_all.configure(state="disable")

    def write_txt(self, text):
        self.text.configure(state="normal")
        self.text.insert(END, ("\n" + text))
        self.text.see("end")
        self.text.configure(state="disable")

    def init_UDP_connection(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind(('', self.UDP_PORT))
        self.sock.settimeout(0.1)

    def send_command(self, cmd):
        payload = bytearray()
        payload.append(int("0x55", 0))
        payload.append(int("0xAA", 0))
        payload.append(cmd)
        payload.append(random.randrange(0, 255))
        if (self.cmd[cmd] == 'write_all_reg'):
            for reg in self.regs:
                numb = int(reg.get())
                payload.append(int(numb / 256))
                payload.append(int(numb % 256))
        payload.append(int("0x33", 0))
        payload.append(int("0xCC", 0))
        self.write_txt("Tx: " + self.cmd[cmd] + " rand=" + str(payload[3]))
        self.sock.sendto(payload, (self.UDP_IP, self.UDP_PORT))

    def open_graph(self):
        if (self.toplevel_flag == False):
            self.toplevel = Toplevel(self.master)
            self.window_data = receive.Watchman_data(self.toplevel)
            self.toplevel_flag = True
            self.toplevel.protocol("WM_DELETE_WINDOW", self.close_graph)

    def close_graph(self):
        self.window_data.exit_prog()
        self.toplevel_flag = False

    def thread_int(self):
        while self.run_flag:
            try:
                data = bytearray()
                data, adress = self.sock.recvfrom(200)
                if (adress[0] == self.UDP_IP):
                    if ((data[0] == int("0x55", 0))
                            and (data[1] == int("0xAA", 0))):
                        if (self.cmd[data[2]] == 'start_stop_stream'):
                            if (self.stream_flag):
                                if (self.destroy_flag == False):
                                    self.btn_stream.configure(
                                        text="Start stream")
                                    if (self.toplevel_flag):
                                        self.write_txt(
                                            "total of frame received =" +
                                            str(self.window_data.count))
                                        self.write_txt(
                                            "LostCnt:" +
                                            str(self.window_data.lostcnt))
                                self.stream_flag = False
                            else:
                                if (self.destroy_flag == False):
                                    self.btn_stream.configure(
                                        text="Stop stream")
                                    if (self.toplevel_flag):
                                        self.window_data.count = 0
                                        self.window_data.lostcnt = 0
                                self.stream_flag = True
                        if (self.cmd[data[2]] == 'stop_uC'):
                            self.btn_stream.configure(text="Start stream")
                            self.stream_flag = False
                        if (self.cmd[data[2]] == 'read_all_reg'):
                            offset = 100
                        else:
                            offset = 0
                        if ((data[4 + offset] == int("0x33", 0))
                                and (data[5 + offset] == int("0xCC", 0))):
                            if (self.destroy_flag == False):
                                self.write_txt("Rx: " + self.cmd[data[2]] +
                                               " rand=" + str(data[3]))
                                if (offset != 0):
                                    count = 4
                                    for reg in self.regs:
                                        reg.delete(0, END)
                                        reg.insert(
                                            END,
                                            str(data[count] * 256 +
                                                data[count + 1]))
                                        count += 2
                        else:
                            if (self.destroy_flag == False):
                                self.write_txt("Rx: ERROR end of frame")
                    else:
                        if (self.destroy_flag == False):
                            self.write_txt("Rx: ERROR start of frame")
                else:
                    if (self.destroy_flag == False):
                        self.write_txt("Rx: ERROR ip of frame (" + adress[0] +
                                       ")")
            except socket.timeout:
                time.sleep(0.1)
                dummy = 0  # dummy execution just to use try without trouble
            except socket.error:
                dummy = 0
            #time.sleep(0.5)
        print("end of main thread", file=sys.stderr)
Esempio n. 21
0
    def __init__(self):
        self.aut = ''
        self.root = Tk()
        self.root.state('zoomed')
        self.root.geometry(
            str(self.root.winfo_screenwidth() - 200) + 'x' +
            str(self.root.winfo_screenheight() - 200))

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

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

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

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

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

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

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

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

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

        self.splitter.add(self.frame_2)

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

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

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

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

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

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

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

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

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

        self.root.mainloop()
Esempio n. 22
0
 def init_window(self):
     # Change window's title
     self.master.title("Watchman - registers")
     self.master.protocol(
         "WM_DELETE_WINDOW",
         self.exit_prog)  # when use close window with the red cross
     # Menu bar
     self.menu = Menu(self.master)
     self.master.config(menu=self.menu)
     self.submenu = Menu(self.menu)
     self.menu.add_cascade(label='Menu', menu=self.submenu)
     self.submenu.add_command(label='Load sequence...',
                              command=self.openfile)
     self.submenu.add_command(label='Save sequence...',
                              command=self.savefile)
     self.submenu.add_command(label='EXIT', command=self.exit_prog)
     self.menu.add_cascade(label='HELP', command=self.help_callback)
     # Table for the registers
     count = 0
     for i in range(0, 4, 2):
         for j in range(25):
             l = Label(self.master,
                       relief=RIDGE,
                       text=("    Reg. " + str(count) + "   "))
             l.grid(column=i, row=j, sticky=N + S + E + W)
             var = StringVar()
             var.trace('w', partial(self.entry_callback, count, var))
             e = Entry(self.master, relief=RIDGE, textvariable=var)
             e.grid(column=(i + 1), row=j, sticky=N + S + E + W)
             self.regs.append(e)
             self.flag_data.append(1)
             count += 1
     # Buttons
     self.btn_write_all = Button(self.master,
                                 text="Write all reg.",
                                 command=partial(self.send_command, 0))
     self.btn_write_all.grid(column=4,
                             row=0,
                             rowspan=2,
                             padx=5,
                             sticky=W + E)
     self.btn_write_all.configure(state="disable")
     self.btn_read_all = Button(self.master,
                                text="Read all reg.",
                                command=partial(self.send_command, 1))
     self.btn_read_all.grid(column=4,
                            row=2,
                            rowspan=2,
                            padx=5,
                            sticky=W + E)
     self.btn_ping = Button(self.master,
                            text="Ping",
                            command=partial(self.send_command, 2))
     self.btn_ping.grid(column=4, row=4, rowspan=2, padx=5, sticky=W + E)
     self.btn_stream = Button(self.master,
                              text="Start stream.",
                              command=partial(self.send_command, 3))
     self.btn_stream.grid(column=4, row=6, rowspan=2, padx=5, sticky=W + E)
     self.btn_stop = Button(self.master,
                            text="Stop uC",
                            command=partial(self.send_command, 4))
     self.btn_stop.grid(column=4, row=8, rowspan=2, padx=5, sticky=W + E)
     self.btn_graph = Button(self.master,
                             text="Open graph\nStore data",
                             command=self.open_graph)
     self.btn_graph.grid(column=4, row=22, rowspan=2, padx=5, sticky=W + E)
     # Listbox to show data transfert
     self.text = Text(self.master, width=40)
     self.text.grid(column=5, row=0, rowspan=25, pady=10, sticky=N + S)
     self.scrlbar = Scrollbar(self.master)
     self.scrlbar.grid(column=6,
                       row=0,
                       rowspan=25,
                       pady=10,
                       padx=5,
                       sticky=N + S)
     self.text.configure(yscrollcommand=self.scrlbar.set)
     self.scrlbar.configure(command=self.text.yview)
     self.text.insert(
         END,
         "List of command sent and received\n-------------------------")
     self.text.configure(state="disable")
Esempio n. 23
0
class HDF5Viewer:
    ''' HD5Viewer
        ======================
        David Miller, 2020
        The University of Sheffield 2020
        
        Presents a graphical means for users to view and inspect the contents of a HDF5 file.
        
        The user points the GUI to a HDF5 file by clicking on the 'Open' button, travelling to a folder and either
        double clicking on a file or selecting a file and clicking the 'Open' button.

        Once the file is selected, the user clicks the 'Scan' button which opens the file in read-only mode in
        a context manager and iterates through the file. The GUI populates a treeview in the GUI with the names of
        objects, their type, shape and data type (datasets only) in a way that mirrows the structures of the file.
        If the type column describes the type of object inside the HDF5 file. If the object is a Group, the contents
        under the shape column represents the number of items stored one level under it. If the object is a Dataset,
        the shape represents the shape of the array stored in the dataset. The data type column is only updated for
        datasets and is the type of data stored in the dataset.

        This class keeps control of the specified file for the minimum amount of time only accessing it for the
        duration of scan_file.

        If the user double clicks on a dataset, a DataViewer GUI is opened in another window. This attempts to display
        the dataset, choosing the appropriate plots based on the shape of the dataset.

        Methods:
        --------------------------
        open_file(self):
            Opens a file dialog for the user to select the HDF5 file they want to inspect.
            
        explore_group(self,item,parent):
            Iterates through the objects stored under item and updates the treeview with the information it finds
            under the node/leaft with the ID parent. If it finds a Group while iterating, explore_group is called
            with the newly discovered Group passed as the item to explore and the parent node to update under.
            Used in scan_file.

        scan_file(self):
            Attempts to open the file specified by the user. If a file path has yet to be specified it returns.
            If it's successful in opening the file, it iterates through its contents updating the treeview with the=
            information it finds. It uses the function explore_group to iterate through Groups it finds under root.
    '''
        
    def __init__(self,master):
        self.master = master
        # set title of image
        master.title("HDF5 File Viewer")

        ## initialize internal variables used
        # set current file as blank
        self.curr_file = "/"
        self.status = StringVar()
        
        ## initialize widgets
        # status label indicating progress or errors
        self.status_label = Label(master,textvariable=self.status)
        self.status.set("Waiting for filename...")
        # button to scan target HDF5 file
        self.scan_button = Button(master,text="Scan File",command=self.scan_file,padx=2)
        # button to chose hdf5 file
        self.openfile_button = Button(master,text="Open File",command=self.open_file,padx=2)
        # box to display current filename
        self.name_display = Entry(master,text="Current filename")
        ## setup tree headings
        # tree view for file layout
        self.file_tree = Treeview(master,columns=("htype","shape","dtype"),show="tree")
        # add double click handler
        # <Double-1> double left click handler
        self.file_tree.bind("<Double-1>",self.create_viewer)
        # dimensions of the columns
        self.file_tree.column("htype",width=200,anchor=CENTER)
        self.file_tree.column("shape",width=200,anchor=CENTER)
        self.file_tree.column("dtype",width=200,anchor=CENTER)
        # text to display in headings
        self.file_tree.heading("htype",text="Item Type")
        self.file_tree.heading("shape",text="Shape")
        self.file_tree.heading("dtype",text="Data Type")
        self.file_tree['show']='headings'
        
        ## add scrollbar for treeview
        # define scrollbar and set the action associated with moving the scrollbar to changing
        # the yview of the tree
        self.tree_scroll=Scrollbar(master,orient="vertical",command=self.file_tree.yview)
        self.file_tree.configure(yscrollcommand=self.tree_scroll)
        
        # set grid layout for widgets using grid
        self.status_label.grid(columnspan=3,row=0)
        self.file_tree.grid(column=0,row=2,columnspan=3,sticky='nswe')
        self.scan_button.grid(column=0,row=1,sticky='we',padx=10)
        self.openfile_button.grid(column=1,row=1,sticky='we',padx=10)
        self.name_display.grid(column=2,row=1,sticky='we',padx=10)
        self.tree_scroll.grid(column=3,row=2,sticky='ns')
        # set weight parameters for control how the elements are resized when the user changes the window size
        master.columnconfigure(0,weight=1)
        master.columnconfigure(1,weight=1)
        master.columnconfigure(2,weight=1)
        master.columnconfigure(3,weight=1)
        master.rowconfigure(0,weight=1)
        master.rowconfigure(1,weight=1)
        master.rowconfigure(2,weight=1)
        master.rowconfigure(3,weight=1)
        # finish any idle tasks and set the minimum size of the window to cur
        master.update_idletasks()
        master.after_idle(lambda: master.minsize(master.winfo_width(), master.winfo_height()))
        
    # function for the user to select the HDF5 file to explore
    # opens file dialog for user to explore
    def open_file(self):
        self.status.set("Waiting for user to select file...")
        # open dialog to search for hdf5 file
        self.curr_file = filedialog.askopenfilename(initialdir=os.path.dirname(self.curr_file),title="Select HDF5 file to inspect",filetypes=[("HDF5 files","*.hdf5")])
        self.name_display.delete(0,END)
        self.name_display.insert(0,self.curr_file)
        try:
            with open(self.curr_file,'r') as file:
                self.status.set("Successfully opened target file")
        except OSError as err:
            self.status.set(err)
            
    # function to explore HDF5 group and update tree
    # if it finds another HDF5 group it calls the functions to explore that group
    def explore_group(self,item,parent):
        self.status.set(f"Exploring {item.name}")
        #print("Exploring {}...".format(item.name))
        # iterate through items
        for v in item.values():
            #print(v.name,str(type(v)))
            # if it's a dataset, update shape entry with shape of dataset
            if isinstance(v,h5py.Dataset):
                self.file_tree.insert(parent,'end',text=v.name,values=(str(type(v)),str(v.shape),str(v.dtype)),open=True)
                self.file_tree['show']='tree headings'
            # if it's a group, call function to investiage it passing last group as parent to add new nodes to
            elif isinstance(v,h5py.Group):
                pkn = self.file_tree.insert(parent,'end',text=v.name,values=(str(type(v)),f"{(len(v.keys()),)}"),open=True)
                self.explore_group(v,pkn)           
    # explores target hdf5 file and displays the the keys of each entry
    # it the entry is a group, then it calls explore_group to explore further
    def scan_file(self):
        # if target file is set
        if self.curr_file != "/":
            # clear tree
            self.file_tree.delete(*self.file_tree.get_children())
            # open file in read mode and iterate through values
            with h5py.File(self.curr_file,'r') as file:
                for v in file.values():
                    # if it's a dataset, update shape entry with shape of dataset
                    if isinstance(v,h5py.Dataset):
                        self.file_tree.insert('','end',text=v.name,values=(str(type(v)),str(v.shape),str(v.dtype)),open=True)
                    # if it's a group, call function to investiage it
                    elif isinstance(v,h5py.Group):
                        pkn = self.file_tree.insert('','end',text=v.name,values=(str(type(v)),f"{(len(v.keys()),)}"),open=True)
                        self.explore_group(v,pkn)
            # update tree display
            self.file_tree['show']='tree headings'
            self.status.set(f"Finished scanning .../{self.curr_file[self.curr_file.rfind('/')+1:]}")
            # finish idle tasks and set minimum window size to final window size
            self.master.update_idletasks()
            self.master.after_idle(lambda: self.master.minsize(self.master.winfo_width(), self.master.winfo_height()))
        else:
            self.status.set("No fime set!")
    def create_viewer(self,event):
        if self.curr_file != "/":
            # get the item selected
            iid = self.file_tree.identify('item',event.x,event.y)
            # get the values of the item to check if a dataset or group was selected
            if 'Dataset' in self.file_tree.item(iid,"values")[0]:
                self.status.set(f"Creating view for {self.file_tree.item(iid,'text')}")
                # create new child window
                t = Toplevel()
                # initialize window inside new child window
                self.data_viewer = DataViewer(t,self.file_tree.item(iid,"text"),self.curr_file)
Esempio n. 24
0
class MyContacts(Toplevel):
    def __init__(self):
        Toplevel.__init__(self)

        self.geometry("650x650+600+200")
        self.title("My Contacts")
        self.resizable(False, False)
        self.top = Frame(self, height=150, bg='white')
        self.top.pack(fill=X)
        self.bottom = Frame(self, height=500, bg="#fcba03")
        self.bottom.pack(fill=X)
        self.top_image = PhotoImage(file="C:\\Users\\jhali\\Desktop\\Python\\Icons\\people.png")
        self.top_image_label = Label(self.top, image=self.top_image)
        self.top_image_label.place(x=180, y=35)
        self.heading = Label(self.top, text="My PhoneBook App", font="arial 15 bold", bg="white", fg="#34baeb")
        self.heading.place(x=260, y=60)
        # scroll bar vertical
        self.scroll = Scrollbar(self.bottom, orient=VERTICAL)
        # list box for data
        self.list_box = Listbox(self.bottom, width=70, height=27)
        self.list_box.grid(row=0, column=0, padx=(30, 0))
        self.scroll.config(command=self.list_box.yview)
        self.list_box.config(yscrollcommand=self.scroll.set)

        persons = cursor.execute("SELECT * FROM contacts").fetchall()
        count = 0
        for person in persons:
            self.list_box.insert(count,
                                 str(person[0]) + " " + person[1] + " " + person[2] + " " + person[3] + " " + person[
                                     4] + " " + person[5])
            count += 1
        # scroll grid
        self.scroll.grid(row=0, column=1, sticky=N + S)

        # buttons
        add_button = Button(self.bottom, text="Add", width=12, font="Sans 12 bold", command=self.addPeople)
        add_button.grid(row=0, column=2, padx=30, pady=10, sticky=N)

        update_button = Button(self.bottom, text="Update", width=12, font="Sans 12 bold", command=self.updateContacts)
        update_button.grid(row=0, column=2, padx=30, pady=50, sticky=N)

        display_button = Button(self.bottom, text="Display", width=12, font="Sans 12 bold",
                                command=self.displayContacts)
        display_button.grid(row=0, column=2, padx=30, pady=90, sticky=N)

        delete_button = Button(self.bottom, text="Delete", width=12, font="Sans 12 bold",
                                command=self.deletePerson)
        delete_button.grid(row=0, column=2, padx=30, pady=130, sticky=N)

    def addPeople(self):
        add_page = AddPerson()
        self.destroy()

    def updateContacts(self):
        selected_item = self.list_box.curselection()
        person = self.list_box.get(selected_item)
        person_id = person.split(" ")[0]
        update_page = UpdatePeople(person_id)
        self.destroy()

    def displayContacts(self):
        selected_item = self.list_box.curselection()
        person = self.list_box.get(selected_item)
        person_id = person.split(" ")[0]
        display_page = DisplayPeople(person_id)
        self.destroy()

    def deletePerson(self):
        selected_item = self.list_box.curselection()
        person = self.list_box.get(selected_item)
        person_id = person.split(" ")[0]

        query = "DELETE FROM contacts where person_id = '{}'".format(person_id)
        string_for_mbox = "Are you sure you wanna delete ", person.split(" ")[1], "?"
        answer = messagebox.askquestion("Warning", string_for_mbox)
        if answer == 'yes':
            try:
                cursor.execute(query)
                conn.commit()
                messagebox.showinfo("Success", "The record was deleted")
                self.destroy()
            except Exception as e:
                messagebox.showerror("Info", str(e))
Esempio n. 25
0
class DataViewer:
    ''' DataViewer
        ======================
        David Miller, 2020
        The University of Sheffield 2020

        Wrapper GUI for a Matplotlib Figure showing the data given on creation. Called by HDF5Viewer when the user
        double clicks on a dataset.

        This GUI is designed a means of performing basic inspections of data stored in HDF5 files. If users want to
        perform something intensive or particular custom, they are advised to do so elsewhere.

        On creation, the DataViewer opens up the file specified by filename and accesses the dataset specified by the
        path dataName. It then decides how to plot the data based on the number of dimensions in the dataset. The used
        plots are as follows using their respective default options:

        |No. dims | Plots    |
        |---------|----------|
        |   1     | Line     |
        |   2     | Contourf |
        |   3     | Contourf |

        In the case of three dimensions, a scrollbar is added on top of the plot and provides a means for the user
        to select which 2D slice of the 3D dataset to show.

        The scrollbar only supports drag operations.

        Any higher dimensional data is ignored.

        The title above the Figure displays the name of the dataset and which index, if any is being displayed.

        Methods
        -------------------------
        on_key_press(event):
            Handler for key presses used on the Matploblib canvas

        scroll_data(self,*args):
            Handler for changing which slice of a 3D dataset is displayed. A new data index is chosen based on where
            the scrollbar cursor is dragged to. The index is calculated by multiplying the scrollbar positon [0,1] by
            the number of frames in the dataset and then converted to an integer.
            Updates the title and canvas on exit. Sets the scrollbar position to where the user left it.
            
            Currently this only has support for clicking and dragging the scrollbar cursor. Other operations are
            ignored.
    '''
    # using filename and name of dataset
    # create a figure and display the data
    def __init__(self,master,dataName,filename):
        self.master = master
        # save creation options
        self.dataName = dataName
        self.filename = filename
        # set title
        self.master.title("Data Viewer")
        # current colormap, default
        self.curr_cmap = getattr(matplotlib.cm,matplotlib.rcParams['image.cmap'])
        # currnt line color
        self.curr_lcol = matplotlib.rcParams['axes.prop_cycle'].by_key()['color'][0]
        ## menu bar for customisation
        # root menu
        menu = Menu(master)
        # options menu
        optsmenu = Menu(menu,tearoff=0)
        # label for graph
        self.title = StringVar()
        self.title.set(f'Displaying {dataName}')
        self.graph_title = Label(master,textvariable=self.title)
        self.graph_title.pack(side=TOP,pady=10,padx=10)
        # create figure
        self.fig = Figure(figsize=(5,5),dpi=100)
        self.axes = self.fig.add_subplot(111)
        # get data from dataset and plot data
        with h5py.File(filename,mode='r') as f:
            self.data_shape = f[dataName].shape
            # if the data is 1D, plot as line
            if len(self.data_shape)==1:
                self.axes.plot(f[dataName][()],self.curr_lcol)
                optsmenu.add_command(label="Set color",command=self.set_color)
            # if data is 2D, plot as filled contour
            elif len(self.data_shape)==2:
                self.axes.contourf(f[dataName][()],cmap=self.curr_cmap)
                optsmenu.add_command(label="Set colormap",command=self.set_colormap)
            # if data is 3D plot as contourf, but also add a scrollbar for navigation
            elif len(self.data_shape)==3:
                optsmenu.add_command(label="Set colormap",command=self.set_colormap)
                # create scroll bar for viewing different slices
                self.plot_scroll=Scrollbar(master,orient="horizontal",command=self.scroll_data)
                # add too gui
                self.plot_scroll.pack(side=TOP,fill=BOTH,expand=True)
                # plot first slice of data
                self.axes.contourf(f[dataName][:,:,0],cmap=self.curr_cmap)
                # create index for current depth index
                self.depth_index = 0
                self.title.set(f"Displaying {dataName} [{self.depth_index}]")
        # add to root menu
        menu.add_cascade(label="Options",menu=optsmenu)
        self.master.config(menu=menu)
        # create canvas to render figure
        self.fig_canvas = FigureCanvasTkAgg(self.fig,self.master)
        # update result
        self.fig_canvas.draw()
        # update canvas to set position and expansion options
        self.fig_canvas.get_tk_widget().pack(side=TOP,fill=BOTH,expand=True)

        ## add matplotlib toolbar
        self.fig_toolbar = NavigationToolbar2Tk(self.fig_canvas,self.master)
        self.fig_toolbar.update()
        # add to gui. always one row below the canvas
        self.fig_canvas._tkcanvas.pack(side=TOP,fill=BOTH,expand=True)
        ## add key press handlers
        self.fig_canvas.mpl_connect("key_press_event",self.on_key_press)
        # ensure elements are expandable in grid
        num_cols,num_rows = master.grid_size()
        for c in range(num_cols):
            master.columnconfigure(c,weight=1)
        for r in range(num_rows):
            master.rowconfigure(r,weight=1)
        # finish any idle tasks and set the minimum size of the window to cur
        master.update_idletasks()
        master.after_idle(lambda: master.minsize(master.winfo_width(), master.winfo_height()))
        
    # handler for matplotlib keypress events
    def on_key_press(event):
        key_press_handler(event,self.fig_canvas,self.fig_toolbar)

    # handler for using the scrollbar to view slices of data
    def scroll_data(self,*args):
        #print(args)
        # if the user has dragged the scrollbar
        if args[0] == "moveto":
            # args is only one element in this case and is a number between 0 and 1
            # 0 is left most position and 1 is right most position
            # the data index is calculated as this number times depth and converted to integer
            self.depth_index = int(float(args[1])*self.data_shape[2])
            # if index exceeds dataset limits
            # correct it
            if self.depth_index>=self.data_shape[-1]:
                self.depth_index = self.data_shape[-1]-1
            # set the scrollbar position to where the user dragged it to
            self.plot_scroll.set(float(args[1]),(self.depth_index+1)/self.data_shape[2])
            # reopen file
            with h5py.File(self.filename,mode='r') as f:
                self.axes.contourf(f[self.dataName][:,:,self.depth_index],cmap=self.curr_cmap)
            # update canvas
            self.fig_canvas.draw()
            # update title
            self.title.set(f"Displaying {self.dataName} [{self.depth_index}]")

    def set_colormap(self):
        ch = ColormapChooser(self.master).show()
        if ch:
            self.curr_cmap = ch
            self.scroll_data("moveto",str(self.plot_scroll.get()[0]))

    def update_line(self):
        # remove first line from plot
        self.axes.lines.pop(0)
        with h5py.File(self.filename,mode='r') as f:
            self.axes.plot(f[self.dataName][()],self.curr_lcol)
        # update canvas
        self.fig_canvas.draw()

    def set_color(self):
        col = colorchooser.askcolor()
        if col[1]:
            self.curr_lcol = col[1]
            self.update_line()
from tkinter import Listbox, END, Button, ANCHOR, Label, Frame, Scrollbar, VERTICAL, RIGHT, Y, Tk
import tkinter as tk
root = tk.Tk()
root.geometry("600x640")
root.config(bg="#353130")

# Create Frame
my_frame = Frame(root)
my_frame.pack()

#scroll bar
scroll_bar_4_my_listbox = Scrollbar(my_frame, orient=VERTICAL)
scroll_bar_4_my_listbox.pack(side=RIGHT,
                             fill=Y)  #? y is to fill UP and DOWN all the way
#? pack in on RIGHT hand side
#Listbox
#*  SELECT MODE = SINGLE IS AT DEFAULT
my_listbox = Listbox(my_frame,
                     width=50,
                     bg="#353130",
                     fg="white",
                     yscrollcommand=scroll_bar_4_my_listbox.set
                     )  #?yscrollcommand -> is for horizontal scrollbar
my_listbox.pack(pady=15)

## coz of my_listbox no defined so got to put it here

scroll_bar_4_my_listbox.config(command=my_listbox.yview)

# my_listbox.insert(0, "This is an item")   #? 0 -> put it in the first one
#                                           #? END -> put it  in the END
Esempio n. 27
0
img = PhotoImage(file="bot2.png")
photoL = Label(main, image=img)
photoL.pack(pady=5)


def ask_from_bot():
    query = textF.get()
    answer_from_bot = bot.get_response(query)
    msgs.insert(END, "you : " + query)
    print(type(answer_from_bot))
    msgs.insert(END, "bot :" + str(answer_from_bot))
    textF.delete(0, END)


frame = Frame(main)
sc = Scrollbar(frame)
msgs = Listbox(frame, width=150, height=20)
sc.pack(side=RIGHT, fill=Y)
msgs.pack(side=LEFT, fill=BOTH, pady=10)
frame.pack()
#creating a text filed
textF = Entry(main, font=("Verdana", 20))
textF.pack(fill=X, pady=10)
btn = Button(main,
             text="Ask for Bot",
             font=("verdana", 20),
             command=ask_from_bot)  #tuple
btn.pack()

main.mainloop()
Esempio n. 28
0
class Window(Frame):

    # Inicialización
    def __init__(self, master):
        # Parametros para mi clase Frame
        Frame.__init__(self, master)
        # Referenciamos
        self.master = master
        # corremos
        self.init_window()

    def init_window(self):
        # Titulo de la ventana
        self.master.title("QA Tools")
        # Instanciamos un menu
        menu = Menu(self.master)
        # Referenciamos al widget
        self.master.config(menu=menu)
        # Agreamos submenus
        file = Menu(menu, tearoff=0)
        # Agregamos submenu Open
        file.add_command(label="Open", command=self.openFile)
        # Agregamos submenu exit
        file.add_command(label="Exit", command=self.client_exit)
        # menu File
        menu.add_cascade(label="File", menu=file)
        # Scrollbar
        self.scrollbar = Scrollbar(self.master, orient=VERTICAL)
        self.scrollbar.pack(side=RIGHT, fill=Y)
        # Lista
        self.lista = Listbox(self.master, font=("Helvetica", 8), borderwidth=0, activestyle=NONE, yscrollcommand=self.scrollbar.set)
        self.lista.pack(fill=BOTH, expand=1)
        self.scrollbar.config(command=self.lista.yview)

    # Funcion para cerrar la app
    def client_exit(self):

        self.master.destroy()

    # Funcion para abrir un doc
    def openFile(self):

        self.lista.delete(0, END)

        # obtenemos el archivo
        filepath = fdialog.askopenfilename(initialdir="C:/Users/%s" % user,
                                           filetypes=(
                                               ("SQL File", "*.sql"), ("All Files", "*.*")),
                                           title="Selección de Archivo")

        switchCommentOn = 'N'
        listBlockBD = [use, database]
        listBlockHeader = [if_, exists, from_, sysobjects, objectid_, and_, type_, drop, procedure]
        listBlockBody = [create, procedure]
        listBlockFoot = [grant, execute]

        dic = {}
        dicBlock = {}
#        dicParameters = {}
        dicBlockDescriptions = {}

#        listObjects = []
        listConstants = [use, if_, exists, from_, sysobjects, objectid_, and_, type_, drop, procedure, create, grant, execute]
        listStatements = [usp]
#        listParameters = ['@']
        listDescriptions = [datos, generales, parametros, control, version, historial, autor, fecha]
        listBlock = []
        conjBlockBD = set(listBlockBD)
        conjBlockHeader = set(listBlockHeader)
        conjBlockBody = set(listBlockBody)
        conjBlockFoot = set(listBlockFoot)

#        listBlockParameters = []
        listBlockDescriptions = []

        try:
            # con el nombre del archivo
            with open(filepath) as fp:
                # obtenemos la primera linea
                line = fp.readline()
                cnt = 1

                # mientras exista una linea
                while line:
                    # damos formato estandar a la linea reemplazando )([].' por un espacio
                    line = line.lower().replace(')', ' ').replace('(', ' ').replace('[', ' ').replace(
                        ']', ' ').replace('.', ' ').replace("'", ' ').replace("\n", ' ').replace("\t", ' ')

                    strippedLine = line.strip()

                    if strippedLine == "":
                        line = fp.readline()
                        cnt += 1
                        continue

                    if strippedLine == go:

                        conjBlock = set(listBlock)

                        if conjBlock == conjBlockBD:
                            print(conjBlock)
                        elif conjBlockHeader.issubset(conjBlock):
                            print(conjBlock)
                        elif conjBlockBody.issubset(conjBlock):
                            print(conjBlock)
                        elif conjBlockFoot.issubset(conjBlock):
                            print(conjBlock)


                        print (listBlockDescriptions)
                        
                        listBlock.clear()  # limpiamos la lista por bloque
                        #listBlockParameters.clear()
                        #listBlockDescriptions.clear()

                    else:

                        indexBlockComentOpen = line.find(blockCommentOpen, beg)

                        if indexBlockComentOpen >= 0 or switchCommentOn == 'S':
                            indexBlockComentClose = line.find(blockCommentClose, beg)
                            if indexBlockComentClose >= 0:
                                switchCommentOn = 'N'
                            else:
                                for const in listDescriptions:
                                    startPosition = line.find(const, beg)
                                    while startPosition >= 0:
                                        endPosition = line.find(space, startPosition)
                                        object_ = line[startPosition: endPosition]
                                        if object_ in listDescriptions:
                                            # listObjects.append(object_)
                                            if object_ in listBlockDescriptions:
                                                dicBlockDescriptions[object_] += 1
                                            else:
                                                dicBlockDescriptions[object_] = 1
                                                listBlockDescriptions.append(object_)

                                        startPosition = line.find(const, endPosition + 1)

                                switchCommentOn = 'S'
                        

                        for const in listConstants:
                            startPosition = line.find(const, beg)
                            while startPosition >= 0:
                                endPosition = line.find(space, startPosition)
                                object_ = line[startPosition: endPosition]
                                if object_ in listConstants:
                                    # listObjects.append(object_)
                                    if object_ in listBlock:
                                        dicBlock[object_] += 1
                                    else:
                                        dicBlock[object_] = 1
                                        listBlock.append(object_)     

                                startPosition = line.find(const, endPosition + 1)

                        for var in listStatements:
                            startPosition = line.find(var, beg)
                            while startPosition >= 0:
                                endPosition = line.find(space, startPosition)
                                object_ = line[startPosition: endPosition]
                                # listObjects.append(object_)
                                if object_ in listBlock:
                                    dic[object_] += 1
                                else:
                                    dic[object_] = 1
                                    listBlock.append(object_)

                                startPosition = line.find(var, endPosition + 1)

#                        for par in listParameters:
#                            startPosition = line.find(par)
#                            while startPosition >= 0:
#                                endPosition = line.find(space, startPosition)
#                                object_ = line[startPosition: endPosition]
#                                # listObjects.append(object_)
#                                if object_ in listBlockParameters:
#                                    dicParameters[object_] += 1
#                                else:
#                                    dicParameters[object_] = 1
#                                    listBlockParameters.append(object_)
#
#                                startPosition = line.find(par, endPosition + 1)

                    # siguiente linea
                    line = fp.readline()
                    cnt += 1

        except OSError as e:
            if e.errno == errno.ENOENT:
                messagebox.showwarning("Warning", "File not found / File not selected")
Esempio n. 29
0
                 fg="white",
                 font="helvetica 10 bold",
                 command=add_book)
add_btn.grid(row=0, column=6, sticky=W)

# list box that shows all the books
list_bx = Listbox(window,
                  height=16,
                  width=40,
                  font="helvetica 13",
                  background="ghost white")
list_bx.grid(row=3, column=1, columnspan=14, sticky=W + E, pady=40, padx=15)
list_bx.bind('<<ListboxSelect>>', get_selected_row)

# scroll bar on right of listbox to enable scrolling
scroll_bar = Scrollbar(window)
scroll_bar.grid(row=1, column=8, rowspan=14, sticky=W)

list_bx.configure(
    yscrollcommand=scroll_bar.set)  # command enables vertical scrolling
scroll_bar.configure(
    command=list_bx.yview)  # yview makes listbox vertically scrollable

# Modify button
modify_btn = Button(window,
                    text="Modify Record",
                    bg="tomato3",
                    fg="white",
                    font="helvetica 10 bold",
                    command=update_records)
modify_btn.grid(row=15, column=4)
Esempio n. 30
0
def mainPanel():
    global top
    top = tk.Tk()
    top.geometry("812x620+151+41")
    top.title("DOC-BOT")
    top.configure(background='floral white')

    Frame1 = tk.Frame(top)
    Frame1.place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0)
    Frame1.configure(relief='groove')
    Frame1.configure(borderwidth="2")
    Frame1.configure(background="#99d8d6")

    Label1 = tk.Label(Frame1)
    Label1.place(relx=0.209, rely=0.032, height=51, width=194)
    Label1.configure(
        font="-family {Microsoft Tai Le} -size 18 -weight bold -underline 1")
    Label1.configure(background="#99d8d6")
    Label1.configure(disabledforeground="#a3a3a3")
    Label1.configure(foreground="#000000")
    Label1.configure(text='''DOC-BOT''')
    Label1.configure(width=194)

    Labelframe1 = tk.LabelFrame(Frame1)
    Labelframe1.place(relx=0.616, rely=0.016, relheight=0.976, relwidth=0.382)
    Labelframe1.configure(
        font="-family {Microsoft Tai Le} -size 10 -weight bold")
    Labelframe1.configure(relief='groove')
    Labelframe1.configure(foreground="black")
    Labelframe1.configure(text='''All Symtoms''')
    Labelframe1.configure(background="#d9d9d9")
    Labelframe1.configure(width=250)

    global Listbox2
    Listbox2 = tk.Listbox(Labelframe1)
    Listbox2.place(relx=0.016,
                   rely=0.033,
                   relheight=0.945,
                   relwidth=0.948,
                   bordermode='ignore')
    Listbox2.configure(background="#c7f9ff")
    Listbox2.configure(disabledforeground="#a3a3a3")
    Listbox2.configure(font="TkFixedFont")
    Listbox2.configure(foreground="#000000")
    Listbox2.configure(width=234)

    Listbox2.bind('<<ListboxSelect>>', onselect)

    scrollbar = Scrollbar(Labelframe1, orient="vertical")
    scrollbar.config(command=Listbox2.yview)
    scrollbar.pack(side="right", fill="y")

    Listbox2.config(yscrollcommand=scrollbar.set)

    for sym in Symtoms:
        Listbox2.insert(tk.END, sym)

    Label2 = tk.Label(Frame1)
    Label2.place(relx=0.123, rely=0.194, height=21, width=104)
    Label2.configure(font="-family {Microsoft Tai Le} -size 10 -weight bold")
    Label2.configure(background="#99d8d6")
    Label2.configure(disabledforeground="#a3a3a3")
    Label2.configure(foreground="#000000")
    Label2.configure(text='''Enter Symtoms''')
    Label2.configure(width=94)

    entry_var = tk.StringVar()

    global Entry1
    Entry1 = tk.Entry(Frame1)
    Entry1.place(relx=0.259, rely=0.194, height=20, relwidth=0.239)
    Entry1.configure(background="#d6e2ff", textvariable=entry_var)
    Entry1.configure(disabledforeground="#a3a3a3")
    Entry1.configure(foreground="#000000")
    Entry1.configure(insertbackground="black")

    global Listbox1
    Listbox1 = tk.Listbox(Frame1)
    Listbox1.place(relx=0.123, rely=0.29, relheight=0.374, relwidth=0.374)
    Listbox1.configure(background="#c7f9ff")
    Listbox1.configure(disabledforeground="#a3a3a3")
    Listbox1.configure(font="-family {Microsoft Tai Le} -size 10")
    Listbox1.configure(foreground="#000000")
    Listbox1.configure(width=164)

    scrollbar = Scrollbar(Listbox1, orient="vertical")
    scrollbar.config(command=Listbox1.yview)
    scrollbar.pack(side="right", fill="y")

    Listbox1.config(yscrollcommand=scrollbar.set)

    Entry1.bind("<Return>", add)

    Button2 = tk.Button(Frame1)
    Button2.place(relx=0.148, rely=0.726, height=30, width=97)
    Button2.configure(font="-family {Microsoft Tai Le} -size 10 -weight bold")
    Button2.configure(activebackground="#ececec", command=predict)
    Button2.configure(activeforeground="#000000")
    Button2.configure(background="#7fd89d")
    Button2.configure(disabledforeground="#a3a3a3")
    Button2.configure(foreground="#000000")
    Button2.configure(highlightbackground="#d9d9d9")
    Button2.configure(highlightcolor="black")
    Button2.configure(pady="0")
    Button2.configure(text='''Predict Disease''')
    Button2.configure(width=97)

    Button3 = tk.Button(Frame1)
    Button3.place(relx=0.369, rely=0.726, height=30, width=69)
    Button3.configure(font="-family {Microsoft Tai Le} -size 10 -weight bold")
    Button3.configure(activebackground="#ececec", command=clear)
    Button3.configure(activeforeground="#000000")
    Button3.configure(background="#7fd89d")
    Button3.configure(disabledforeground="#a3a3a3")
    Button3.configure(foreground="#000000")
    Button3.configure(highlightbackground="#d9d9d9")
    Button3.configure(highlightcolor="black")
    Button3.configure(pady="0")
    Button3.configure(text='''Clear List''')
    Button3.configure(width=69)

    top.mainloop()