Ejemplo n.º 1
0
class Button:
    def __init__(self,
                 parent,
                 value,
                 label,
                 stateCarrier,
                 width=0,
                 height=0,
                 variable=None):

        self.instance = Radiobutton(
            parent,
            value=value,
            variable=variable,
            indicatoron=0,
            command=lambda: stateCarrier.saveVal(value),
            width=width,
            height=height)
        if isinstance(label, str):
            self.instance.config(text=label)
        elif isinstance(label, ImageTk.PhotoImage):
            self.instance.config(image=label)
        else:
            raise TypeError(
                'Wrong Type. Label must be of type String or PhotoImage!')

    def pos(self, row, column, padx=0, pady=0):
        self.instance.grid(row=row,
                           column=column,
                           padx=padx,
                           pady=pady,
                           sticky=N)
Ejemplo n.º 2
0
class RadioButton(WidgetMixin, ScheduleMixin, DestroyMixin, EnableMixin,
                  FocusMixin, DisplayMixin, ReprMixin):
    def __init__(self,
                 master,
                 text,
                 value,
                 variable,
                 command=None,
                 grid=None,
                 align=None):

        self._master = master
        self._grid = grid
        self._align = align
        self._visible = True

        self.description = "[RadioButton] object with option=\"" + str(
            text) + "\" value=\"" + str(value) + "\""
        self._text = text
        self._value = value

        # `variable` is the externally passed StringVar keeping track of which
        # option was selected. This class should not be instantiated by a user
        # unless they know what they are doing.
        self.tk = Radiobutton(master.tk,
                              text=self._text,
                              value=self._value,
                              variable=variable)

    # PROPERTIES
    # -----------------------------------

    # The value of this button
    @property
    def value(self):
        return (self._value)

    @value.setter
    def value(self, value):
        self._value = str(value)
        self.tk.config(value=str(value))
        self.description = "[RadioButton] object with option=\"" + self._text + "\" value=\"" + str(
            value) + "\""

    # The text from this button
    @property
    def text(self):
        return (self._text)

    @text.setter
    def text(self, text):
        self._text = str(text)
        self.tk.config(text=self._text)
        self.description = "[RadioButton] object with option=\"" + str(
            text) + "\" value=\"" + self._value + "\""
Ejemplo n.º 3
0
def Radio(root, lists = [], **options):

  props = {
    
  }

  for idx, val in enumerate(lists):
    R = Radiobutton(root, value=idx, text=val)

    R.config(**options)
    R.pack()
Ejemplo n.º 4
0
    def __init__(self, master, parentWindow):
        
        frame = Frame(master)
        frame.pack()
        self.frame = frame

        # for destroy purpose
        self.master = master

        self.parentWindow = parentWindow
        
        # database with images
        self.imgDB = tm.cdb.imgDB
        # for database.get(item)
        self.item = 1
        
        self.labelImgPlace = Label(frame,
                                   text="Image from database \n (click next)")
        self.labelImgPlace.grid(row=0, column=1)

        # buttons for going trought imgDB
        self.buttonNext = Button(frame, text="Next",
                                 command=self.next)
        self.buttonNext.grid(row=2, column=0)

        self.buttonBack = Button(frame, text="Back",
                                 command=self.back)
        self.buttonBack.grid(row=3, column=0)

        # label for name of class
        self.varForLabel = StringVar()
        self.labelClassName = Label(frame, textvariable=self.varForLabel)
        self.labelClassName.grid(row=4, column=0)

        self.button = Button(frame, text="load image",
                             command=self.load_image)
        # self.button.grid(row=0, column=0)
        
        self.label = 0
        # self.label=Label(frame,image=imgP)
        # self.label.pack(side=RIGHT)
        
        self.things = self.parentWindow.childResultList  # ["cup","banana","pencil"]
        
        for i in range(len(self.things)):
            b = Radiobutton(self.frame, text=self.things[i], value=i)
            # write i-ths element from list to database as label 
            b.config(command=lambda iter=i: self.choice_class(iter))
            b.deselect()
            b.grid(row=i+1, column=2)
class Inicio(Frame):
    def __init__(self, master, *args, **kwargs):
        Frame.__init__(self, master, *args, **kwargs)
        self.master = master
        self.master.nombre.set('')
        self.master.puntaje.set(0)

        self.config(background=constantes.color_fondo)
        self.grid(sticky='nsew')
        self.reproductor = Reproductor()
        self.reproductor.reproducir_musica(constantes.musica_inicio, 0.4)
        self.crear_widgets()

    def crear_widgets(self):
        self.ph_imagen_bienvenida = PhotoImage(file=constantes.imagen_fondo)
        self.lb_bienvenida_img = Label(self,
                                       image=self.ph_imagen_bienvenida,
                                       bg=constantes.color_fondo)
        self.lb_bienvenida_img.grid(row=0,
                                    column=0,
                                    columnspan=2,
                                    sticky='nsew',
                                    padx=10,
                                    pady=10)

        self.lb_bienvenida = Label(self,
                                   text=constantes.titulo,
                                   font=(constantes.tipografia, 20),
                                   bg=constantes.color_fondo,
                                   fg='white')
        self.lb_bienvenida.grid(row=1,
                                column=0,
                                columnspan=3,
                                sticky='nsew',
                                padx=10,
                                pady=10)

        self.lb_nombre_j = Label(self, text='Nombre Jugador:')
        self.lb_nombre_j.config(bg=constantes.color_fondo,
                                fg='white',
                                font=(constantes.tipografia, 12))
        self.lb_nombre_j.grid(row=2, column=0, sticky='nsew', padx=10, pady=10)

        self.lb_nombre_jugador = Entry(self, textvariable=self.master.nombre)
        self.lb_nombre_jugador.grid(row=2,
                                    column=1,
                                    sticky='nsew',
                                    padx=10,
                                    pady=10)
        self.lb_nombre_jugador.config(bg=constantes.color_fondo,
                                      fg=constantes.color_tipografia,
                                      justify='center',
                                      font=(constantes.tipografia, 12))
        self.lb_nombre_jugador.focus()

        self.msg_alerta = Label(self)
        self.msg_alerta.grid(row=4, column=0, sticky='nsew', padx=10, pady=10)
        self.msg_alerta.config(bg=constantes.color_fondo,
                               fg='red',
                               justify='left',
                               anchor=CENTER,
                               font=(constantes.tipografia, 12))

        self.txt_musica_on_off = 'Musica OFF'
        self.btn_musica_on_off = Button(self,
                                        text=self.txt_musica_on_off,
                                        command=self.cambio_musica)
        self.btn_musica_on_off.grid(row=4,
                                    column=1,
                                    sticky='nsew',
                                    padx=10,
                                    pady=10)
        self.btn_musica_on_off.config(bg=constantes.color_fondo,
                                      fg='white',
                                      justify='center',
                                      font=(constantes.tipografia, 12))

        self.rb_facil = Radiobutton(self,
                                    text='Facil',
                                    variable=self.master.dificultad,
                                    value='Facil',
                                    command=self.cambia_dificultad)
        self.rb_facil.config(bg=constantes.color_fondo,
                             fg='white',
                             justify='center',
                             font=(constantes.tipografia, 12))
        self.rb_facil.grid(row=3, column=0, sticky='nsew', padx=10, pady=10)

        self.rb_dificil = Radiobutton(self,
                                      text='Dificil',
                                      variable=self.master.dificultad,
                                      value='Dificil',
                                      command=self.cambia_dificultad)
        self.rb_dificil.config(bg=constantes.color_fondo,
                               fg='white',
                               justify='center',
                               font=(constantes.tipografia, 12))
        self.rb_dificil.grid(row=3, column=1, sticky='nsew', padx=10, pady=10)

        self.btn_jugar = Button(self, text='JUGAR')
        self.btn_jugar.grid(row=5,
                            column=0,
                            columnspan=2,
                            sticky='nsew',
                            padx=10,
                            pady=15)
        self.btn_jugar.config(bg=constantes.color_fondo,
                              fg=constantes.color_tipografia,
                              justify='center',
                              font=(constantes.tipografia, 20),
                              command=lambda: [self.guarda_datos()])

    def msj_alerta(self, msj):
        self.msg_alerta.config(text=str(msj))

    def cambio_musica(self):
        if self.btn_musica_on_off['text'] == 'Musica OFF':
            self.btn_musica_on_off['text'] = 'Musica ON'
            self.btn_musica_on_off['fg'] = constantes.color_tipografia
            self.reproductor.pausa_musica()
        elif self.btn_musica_on_off['text'] == 'Musica ON':
            self.btn_musica_on_off['text'] = 'Musica OFF'
            self.btn_musica_on_off['fg'] = 'white'
            self.reproductor.reanuda_musica()

    def cambia_dificultad(self):
        if self.master.dificultad.get() == 'Facil':
            self.master.velocidad.set(83)
            self.rb_facil['fg'] = constantes.color_tipografia
            self.rb_dificil['fg'] = 'white'
        elif self.master.dificultad.get() == 'Dificil':
            self.master.velocidad.set(53)
            self.rb_dificil['fg'] = constantes.color_tipografia
            self.rb_facil['fg'] = 'white'

    def guarda_datos(self):
        alerta = ''
        if (self.master.nombre.get() == ''
                and self.master.dificultad.get() == ''):
            alerta = 'Elija un nombre \nElija dificultad'
            self.msj_alerta(alerta)
        elif (self.master.nombre.get() == ''):
            alerta = 'Elija un nombre'
            self.msj_alerta(alerta)
        elif (self.master.dificultad.get() == ''):
            alerta = 'Elija la dificultad'
            self.msj_alerta(alerta)
        elif (self.master.nombre.get() and self.master.dificultad.get()):
            alerta = 'Comenzando...'
            self.msj_alerta(alerta)
            t = Timer(1.5, lambda: [self.borrar_widget_grid()])
            t.start()
            self.reproductor.para_musica()
            self.reproductor.reproducir_sonido(constantes.musica_play, 0.5)

    def borrar_widget_grid(self):
        self.grid_remove()
        from pantalla_juego import PantallaJuego
        self.master.cambia_frame(PantallaJuego, self.master)
Ejemplo n.º 6
0
class Spremnik:
    def __init__(self,root,frame):
        self.root=root
        self.frame=frame
        self.oblik = IntVar()
        self.boja = IntVar()
        self.masa_min = IntVar()
        self.masa_max = IntVar()
        Label(frame, text="OBLICI").grid(row=0, column=0)
        Label(frame, text="BOJA").grid(row=0, column=1)
        Label(frame, text="MASA").grid(row=0, column=2)
        self.toggle_btn_oblik = Button(frame, text="OFF", bg='red', command=self.ToggleOblik, width=TOG_WIDTH)
        self.toggle_btn_oblik.grid(row=1, column=0)
        self.toggle_btn_boja = Button(frame, text="OFF", bg='red', command=self.ToggleBoja, width=TOG_WIDTH)
        self.toggle_btn_boja.grid(row=1, column=1)
        self.toggle_btn_masa = Button(frame, text="OFF", bg='red', command=self.ToggleMasa, width=TOG_WIDTH)
        self.toggle_btn_masa.grid(row=1, column=2)
        self.radio_btn_kugla = Radiobutton(frame, variable=self.oblik, value=1, text='kugla', state=DISABLED, width=RB_WIDTH, height=RB_HEIGHT, anchor=W, font=(None, RB_FONT_SIZE))
        self.radio_btn_kugla.grid(row=2, column=0)
        self.radio_btn_kocka = Radiobutton(frame, variable=self.oblik, value=2, text='kocka', state=DISABLED, width=RB_WIDTH, height=RB_HEIGHT, anchor=W, font=(None, RB_FONT_SIZE))
        self.radio_btn_kocka.grid(row=3, column=0)
        self.radio_btn_piramida = Radiobutton(frame, variable=self.oblik, value=3, text='piramida', state=DISABLED, width=RB_WIDTH, height=RB_HEIGHT, anchor=W, font=(None, RB_FONT_SIZE))
        self.radio_btn_piramida.grid(row=4, column=0)
        self.radio_btn_zelena = Radiobutton(frame, variable=self.boja, value=1, text='zelena', state=DISABLED, width=RB_WIDTH, height=RB_HEIGHT, anchor=W, font=(None, RB_FONT_SIZE))
        self.radio_btn_zelena.grid(row=2, column=1)
        self.radio_btn_crvena = Radiobutton(frame, variable=self.boja, value=2, text='crvena', state=DISABLED, width=RB_WIDTH, height=RB_HEIGHT, anchor=W, font=(None, RB_FONT_SIZE))
        self.radio_btn_crvena.grid(row=3, column=1)
        self.radio_btn_plava = Radiobutton(frame, variable=self.boja, value=3, text='plava', state=DISABLED, width=RB_WIDTH, height=RB_HEIGHT, anchor=W, font=(None, RB_FONT_SIZE))
        self.radio_btn_plava.grid(row=4, column=1)
        self.radio_btn_zuta = Radiobutton(frame, variable=self.boja, value=4, text='zuta', state=DISABLED, width=RB_WIDTH, height=RB_HEIGHT, anchor=W, font=(None, RB_FONT_SIZE))
        self.radio_btn_zuta.grid(row=5, column=1)
        self.label_masa_min = Label(frame, text="  MIN", fg="grey")
        self.label_masa_min.grid(row=2, column=2, sticky=W)
        self.entry_masa_min = Entry(frame, width=5, state=DISABLED)
        self.entry_masa_min.grid(row=2, column=2, columnspan=2, sticky=E)
        self.label_masa_max = Label(frame, text="  MAX", fg="grey")
        self.label_masa_max.grid(row=3, column=2, sticky=W)
        self.entry_masa_max = Entry(frame, width=5, state=DISABLED)
        self.entry_masa_max.grid(row=3, column=2, sticky=E)
        self.entry_masa_min.bind("<Button-1>",self.Numpad_Show_Min)
        self.entry_masa_max.bind("<Button-1>",self.Numpad_Show_Max)
        self._oblikState=False
        self._bojaState=False
        self._masaState=False

    def ToggleOblik(self):
        self._oblikState = not self._oblikState
        #print(self._oblikState)
        if self._oblikState == True:
            self.toggle_btn_oblik.config(bg='light green')
            self.toggle_btn_oblik.config(text='ON')
            self.radio_btn_kugla.config(state=NORMAL)
            self.radio_btn_kocka.config(state=NORMAL)
            self.radio_btn_piramida.config(state=NORMAL)
            self.radio_btn_kugla.select()
        elif self._oblikState == False:
            self.toggle_btn_oblik.config(bg='red')
            self.toggle_btn_oblik.config(text='OFF')
            self.radio_btn_kugla.config(state=DISABLED)
            self.radio_btn_kocka.config(state=DISABLED)
            self.radio_btn_piramida.config(state=DISABLED)
            self.oblik.set(0)

    def ToggleBoja(self):
        self._bojaState = not self._bojaState
        if self._bojaState == True:
            self.toggle_btn_boja.config(bg='light green')
            self.toggle_btn_boja.config(text='ON')
            self.radio_btn_crvena.config(state=NORMAL)
            self.radio_btn_plava.config(state=NORMAL)
            self.radio_btn_zelena.config(state=NORMAL)
            self.radio_btn_zuta.config(state=NORMAL)
            self.radio_btn_zelena.select()
        elif self._bojaState == False:
            self.toggle_btn_boja.config(bg='red')
            self.toggle_btn_boja.config(text='OFF')
            self.radio_btn_crvena.config(state=DISABLED)
            self.radio_btn_plava.config(state=DISABLED)
            self.radio_btn_zuta.config(state=DISABLED)
            self.radio_btn_zelena.config(state=DISABLED)
            self.boja.set(0)

    def ToggleMasa(self):
        self._masaState = not self._masaState
        if self._masaState == True:
            self.toggle_btn_masa.config(bg='light green')
            self.toggle_btn_masa.config(text='ON')
            self.entry_masa_max.config(state=NORMAL)
            self.entry_masa_min.config(state=NORMAL)
            self.label_masa_min.config(fg='black')
            self.label_masa_max.config(fg='black')
            self.masa_min.set(0)
            self.masa_max.set(1000)
            self.entry_masa_min.insert(0, 0)
            self.entry_masa_max.insert(0, 1000)
        elif self._masaState == False:
            self.toggle_btn_masa.config(bg='red')
            self.toggle_btn_masa.config(text='OFF')
            self.entry_masa_min.delete(0, END)
            self.entry_masa_max.delete(0, END)
            self.entry_masa_max.config(state=DISABLED)
            self.entry_masa_min.config(state=DISABLED)
            self.label_masa_min.config(fg='grey')
            self.label_masa_max.config(fg='grey')
            self.masa_min.set(0)
            self.masa_max.set(0)

    def Numpad_Show_Min(self,arg):
        if self._masaState == True:
            new = NumPad(self.root, self, "min")

    def Numpad_Show_Max(self,arg):
        if self._masaState == True:
            self.masa_max.set(0)
            new = NumPad(self.root, self, "max")
    def __init__(self, TkObject):

        #Load company image
        Imageloc = tk.PhotoImage(file='../Images/alstom_logo.gif')
        label3 = Label(image=Imageloc, )
        label3.image = Imageloc
        label3.place(x=200, y=20)

        global TkObject_ref, entryText_LDRAToolPath, entryText_vvPath, entryText_SourceFilePath, entryText_commonSourceFilePath, entryText_sysearchFilePath, entryText_TestbedINI, AnalyseDirRunBatchButton, swLevelRadioButton

        #1. select LDRA Tool suite directory
        TkObject_ref = TkObject
        LDRAToolsuitePath = Button(
            TkObject_ref,
            activebackground='green',
            borderwidth=3,
            anchor="w",
            text='1. Select LDRA Tool suite path:',
            width=30,
            command=lambda: GUI_COntroller.selectResDirectory("LDRAPath"),
            cursor="hand2")
        LDRAToolsuitePath.place(x=30, y=120)
        LDRAToolsuitePath.config(font=('helvetica', 10, 'bold'))

        #1. This is text box where LDRA tool suite directory will be shown to user
        entryText_LDRAToolPath = tk.StringVar()
        Entry_LDRAToolSuitePath = Entry(TkObject_ref,
                                        width=78,
                                        textvariable=entryText_LDRAToolPath,
                                        bd=1)
        Entry_LDRAToolSuitePath.place(x=290, y=124)
        Entry_LDRAToolSuitePath.config(font=('helvetica', 10),
                                       state="readonly")

        #2. select VV directory
        vvPath = Button(
            TkObject_ref,
            activebackground='green',
            borderwidth=3,
            anchor="w",
            text='2. Select VV path:',
            width=30,
            command=lambda: GUI_COntroller.selectResDirectory("VVPath"),
            cursor="hand2")
        vvPath.place(x=30, y=180)
        vvPath.config(font=('helvetica', 10, 'bold'))

        #2. This is text box where VV directory will be shown to user
        entryText_vvPath = tk.StringVar()
        Entry_vvPath = Entry(TkObject_ref,
                             width=78,
                             textvariable=entryText_vvPath,
                             bd=1)
        Entry_vvPath.place(x=290, y=184)
        Entry_vvPath.config(font=('helvetica', 10), state="readonly")

        #3. select Source file directory
        SourceFilePath = Button(TkObject_ref,
                                activebackground='green',
                                borderwidth=3,
                                anchor="w",
                                text='3. Select Source files path:',
                                width=30,
                                command=lambda: GUI_COntroller.
                                selectResDirectory("SourceFilesPath"),
                                cursor="hand2")
        SourceFilePath.place(x=30, y=240)
        SourceFilePath.config(font=('helvetica', 10, 'bold'))

        #3. This is text box where source file directory will be shown to user
        entryText_SourceFilePath = tk.StringVar()
        Entry_SourceFilePath = Entry(TkObject_ref,
                                     width=78,
                                     textvariable=entryText_SourceFilePath,
                                     bd=1)
        Entry_SourceFilePath.place(x=290, y=244)
        Entry_SourceFilePath.config(font=('helvetica', 10), state="readonly")

        #4. select common Source file directory
        CommonSourceFilePath = Button(
            TkObject_ref,
            activebackground='green',
            borderwidth=3,
            anchor="w",
            text='4. Select common Source files path:',
            width=30,
            command=lambda: GUI_COntroller.selectResDirectory(
                "CommonSourceFilesPath"),
            cursor="hand2")
        CommonSourceFilePath.place(x=30, y=300)
        CommonSourceFilePath.config(font=('helvetica', 10, 'bold'))

        #4. This is text box where source file directory will be shown to user
        entryText_commonSourceFilePath = tk.StringVar()
        Entry_CommonSourceFilePath = Entry(
            TkObject_ref,
            width=78,
            textvariable=entryText_commonSourceFilePath,
            bd=1)
        Entry_CommonSourceFilePath.place(x=290, y=304)
        Entry_CommonSourceFilePath.config(font=('helvetica', 10),
                                          state="readonly")

        #5. select sysearch file
        sysearchFilePath = Button(
            TkObject_ref,
            activebackground='green',
            borderwidth=3,
            anchor="w",
            text='5. Select a sysearch file:',
            width=30,
            command=lambda: GUI_COntroller.selectResDirectory("SysearchFile"),
            cursor="hand2")
        sysearchFilePath.place(x=30, y=360)
        sysearchFilePath.config(font=('helvetica', 10, 'bold'))

        #5. This is text box where source file directory will be shown to user
        entryText_sysearchFilePath = tk.StringVar()
        Entry_sysearchFilePath = Entry(TkObject_ref,
                                       width=78,
                                       textvariable=entryText_sysearchFilePath,
                                       bd=1)
        Entry_sysearchFilePath.place(x=290, y=364)
        Entry_sysearchFilePath.config(font=('helvetica', 10), state="readonly")

        # Select creticality of the software
        swCriticalityLabel = Label(
            TkObject_ref,
            text="Select the criticality of the software: ",
            background="#b7bbc7")
        swCriticalityLabel.place(x=30, y=420)
        swCriticalityLabel.config(font=('helvetica', 10, 'bold'))

        #Set the Radio button to select software complexity level
        swLevelRadioButton = tk.IntVar()
        swCriticalityLevel_VitalRadioButton = Radiobutton(
            TkObject_ref,
            text="Vital software",
            background="#b7bbc7",
            variable=swLevelRadioButton,
            value=1)
        swCriticalityLevel_VitalRadioButton.place(x=290, y=424)
        swCriticalityLevel_VitalRadioButton.config(font=('helvetica', 10,
                                                         'bold'))

        swCriticalityLevel_NonVitalRadioButton = Radiobutton(
            TkObject_ref,
            text="Non-Vital software",
            background="#b7bbc7",
            variable=swLevelRadioButton,
            value=2)
        swCriticalityLevel_NonVitalRadioButton.place(x=430, y=424)
        swCriticalityLevel_NonVitalRadioButton.config(font=('helvetica', 10,
                                                            'bold'))

        #6. select testbed.ini file directory
        TestbedINI = Button(
            TkObject_ref,
            activebackground='green',
            borderwidth=3,
            anchor="w",
            text='6. Select TESTBED.ini file:',
            width=30,
            command=lambda: GUI_COntroller.selectResDirectory("TESTBEDINI"),
            cursor="hand2")
        TestbedINI.place(x=30, y=480)
        TestbedINI.config(font=('helvetica', 10, 'bold'))

        #6. This is text box where spare directory will be shown to user
        entryText_TestbedINI = tk.StringVar()
        Entry_TestbedINI = Entry(TkObject_ref,
                                 width=78,
                                 textvariable=entryText_TestbedINI,
                                 bd=1)
        Entry_TestbedINI.place(x=290, y=484)
        Entry_TestbedINI.config(font=('helvetica', 10), state="readonly")

        #Exit Window
        closeButton = Button(TkObject_ref,
                             activebackground='green',
                             borderwidth=4,
                             text='Close Window',
                             command=GUI_COntroller.exitWindow)
        closeButton.place(x=570, y=580)
        closeButton.config(font=('helvetica', 11, 'bold'))

        #select sequence files directory
        AnalyseDirRunBatchButton = Button(TkObject_ref,
                                          activebackground='green',
                                          borderwidth=4,
                                          text='Configure LDRA Project',
                                          width=25,
                                          command=GUI_COntroller.RunTest)
        AnalyseDirRunBatchButton.place(x=200, y=580)
        AnalyseDirRunBatchButton.config(font=('helvetica', 11, 'bold'))

        #read the data from saved preference if it is saved already
        GUI_COntroller.readDataFromSavedPref()
lbl_email.grid(row=4, column=0, pady=15, padx=10, sticky='w')

lbl_Dirección = Label(frame_form)
lbl_Dirección.config(text='dirección', font=config[0], bg=colors[1])
lbl_Dirección.grid(row=5, column=0, pady=15, padx=10, sticky='w')

lbl_genre = Label(frame_form)
lbl_genre.config(text='genero', font=config[0], bg=colors[1])
lbl_genre.grid(row=6, column=0, pady=15, padx=10, sticky='w')

# ========================checkbuttons========================
var_man = IntVar()
chb_man = Radiobutton(frame_form)
chb_man.config(text='Hombre',
               font=config[0],
               bg=colors[1],
               variable=var_man,
               value=1)
chb_man.grid(row=6, column=1)

var_woman = IntVar()
chb_woman = Radiobutton(frame_form)
chb_woman.config(text='mujer',
                 font=config[0],
                 bg=colors[1],
                 variable=var_woman,
                 value=2)
chb_woman.grid(row=6, column=3)

# ========================Entrys========================
en_name = Entry(frame_form)
Ejemplo n.º 9
0
class Interface:
    """ GUI class """
    def __init__(self, master):
        # colour swatches
        self.gray1 = "#f6f6f6"
        self.gray2 = "#eaeaea"
        self.gray3 = "#d9d9d9"
        # key parameters
        self.running = False
        self.sect_width = 360
        self.rb_choice = StringVar()
        self.dob1_val = StringVar()
        self.dob2_val = StringVar()
        self.df_records = StringVar()

        master.geometry("800x600+200+200")
        master.title("Red Snapper")
        master.resizable(False, False)
        master.configure(background=self.gray1)

        # LEFT SECTION LAYER
        # --------------------------------------------------------------------
        self.sect_left = Frame(master)
        self.sect_left.place(x=15, y=15, width=self.sect_width, height=570)
        self.sect_left.config(relief=RIDGE)
        self.sect_left.config(background=self.gray2)

        # RIGHT SECTION LAYER
        # --------------------------------------------------------------------
        self.sect_right = Frame(master)
        self.sect_right.place(x=-15, y=200, width=self.sect_width, height=385)
        self.sect_right.place(relx=1.0, anchor="ne")
        self.sect_right.config(relief=RIDGE)
        self.sect_right.config(background=self.gray2)

        # Sliders layer
        self.layer_sliders = Frame(self.sect_left)
        self.layer_sliders.place(y=0, width=self.sect_width, height=320)
        self.layer_sliders.config(**self.layer_props(self.gray2))
        self.lab_sliders = Label(self.layer_sliders)
        self.lab_sliders.config(**self.title_props("Parameters"))
        self.lab_sliders.pack()

        # DOB layer
        self.layer_dob = Frame(self.sect_left)
        self.layer_dob.place(y=320, width=self.sect_width, height=80)
        self.layer_dob.config(**self.layer_props(self.gray2))
        self.lab_dob = Label(self.layer_dob)
        self.lab_dob.config(**self.title_props("Birthdays range"))
        self.lab_dob.pack()

        # Export layer
        self.layer_export = Frame(self.sect_left)
        self.layer_export.place(y=400, width=self.sect_width, height=80)
        self.layer_export.config(**self.layer_props(self.gray2))
        self.lab_export = Label(self.layer_export)
        self.lab_export.config(**self.title_props("Export format"))
        self.lab_export.pack()

        # Run layer
        self.layer_run = Frame(self.sect_left)
        self.layer_run.place(y=480, width=self.sect_width, height=100)
        self.layer_run.config(**self.layer_props(self.gray2))
        self.lab_run = Label(self.layer_run)
        self.lab_run.config(**self.title_props("Run"))
        self.lab_run.pack()

        # About layer
        self.layer_about = Frame(self.sect_right)
        self.layer_about.place(width=self.sect_width, height=385)
        self.layer_about.config(**self.layer_props(self.gray2))
        self.lab_about = Label(self.layer_about)
        self.lab_about.config(**self.title_props("About Red Snapper"))
        self.lab_about.pack()

        # sliders
        self.sli_wom = Scale(self.layer_sliders, from_=0, to=100)
        self.sli_wom.config(**self.sli_props())
        self.sli_wom.config(label="Percentage of women in dataset.")
        self.sli_wom.pack(padx=20, pady=10)
        self.sli_wom.set(50)

        self.sli_nam = Scale(self.layer_sliders, from_=0, to=100)
        self.sli_nam.config(**self.sli_props())
        self.sli_nam.config(label="Percentage of people with double name")
        self.sli_nam.pack(padx=20, pady=0)
        self.sli_nam.set(25)

        self.sli_sur = Scale(self.layer_sliders, from_=0, to=100)
        self.sli_sur.config(**self.sli_props())
        self.sli_sur.config(label="Percentage of people with double surname")
        self.sli_sur.pack(padx=20, pady=10)
        self.sli_sur.set(15)

        # DOB Layer - From Date
        self.dob1_val.set("1945")
        self.lab_dob1 = Label(self.layer_dob, text="From date")
        self.lab_dob1.config(**self.label_props())
        self.lab_dob1.pack(side=LEFT, padx=5)
        self.box_dob1 = Spinbox(self.layer_dob)
        self.box_dob1.config(from_=1945, to=1996, textvariable=self.dob1_val)
        self.box_dob1.config(**self.date_props())
        self.box_dob1.pack(side=LEFT)

        # DOB Layer - To Date
        self.dob2_val.set("1997")
        self.lab_dob2 = Label(self.layer_dob, text="To date")
        self.lab_dob2.config(**self.label_props())
        self.lab_dob2.pack(side=LEFT, padx=17)
        self.box_dob2 = Spinbox(self.layer_dob)
        self.box_dob2.config(from_=1946, to=1997, textvariable=self.dob2_val)
        self.box_dob2.config(**self.date_props())
        self.box_dob2.pack(side=LEFT)

        # Export layer - JSON / CSV radio buttons
        self.rb_choice.set("CSV")
        self.rb1 = Radiobutton(self.layer_export,
                               text="Save as CSV",
                               variable=self.rb_choice,
                               value="CSV")
        self.rb1.config(**self.radio_props())
        self.rb1.place(y=35, x=50)
        self.rb2 = Radiobutton(self.layer_export,
                               text="Save as JSON",
                               variable=self.rb_choice,
                               value="JSON")
        self.rb2.config(**self.radio_props())
        self.rb2.place(y=35, x=200)

        # Run layer - no of records spinbox
        self.df_records.set("100")
        self.box_gen = Spinbox(self.layer_run)
        self.box_gen.config(from_=1, to=999999, textvariable=self.df_records)
        self.box_gen.config(increment=1000, width=19)
        self.box_gen.place(x=70, y=53)
        self.lab_gen = Label(self.layer_run, text="Number of records")
        self.lab_gen.config(**self.label_props())
        self.lab_gen.place(x=70, y=30)

        # Run layer - generate button
        self.btn_run = ttk.Button(self.layer_run)
        self.btn_run.place(x=225, y=35, height=40)
        self.btn_run_reset()

        # header & logo section
        self.sect_logo = Frame(master)
        self.sect_logo.place(x=-15, y=30, width=350, height=120)
        self.sect_logo.place(relx=1.0, anchor="ne")
        self.logo = PhotoImage(file="./redsnapper/interface/logo.png")
        self.lab_logo = Label(self.sect_logo, image=self.logo)
        self.lab_logo.config(background=self.gray1)
        self.lab_logo.pack()

        # About
        box_about = Text(self.layer_about)
        box_about.config(**self.text_props())
        box_about.pack(pady=10, padx=10)
        txt = """This program allows generating thousands of rows filled with pseudo-random data. """ \
              + """\nThe generated records (like name,  """ \
              + """ surname, date of birth, e-mail address) can be used to provide sample data to:
        - test query performance of your database 
        - practice data operations with BI tools.""" \
              + """ \nThe application uses 4 processes to generate data simultaneously. """ \
              + """ It takes about 25 seconds to create 1 million rows of data.\n"""

        box_about.insert(END, txt)

    # styling wrapped into functions for reusability
    def sli_props(self):
        """
        bundle popular attributes of TK control so they can be reused
        :return: dict of bundled props
        """
        return {
            "length": 300,
            "orient": HORIZONTAL,
            "sliderrelief": FLAT,
            "showvalue": 1,
            "resolution": 1,
            "sliderlength": 25,
            "tickinterval": 100,
            "font": ("Arial", 8),
            "activebackground": "#333333",
            "background": "#666666",
            "troughcolor": "#d0d4d2",
            "foreground": "#eeeeee",
            "highlightthickness": 8,
            "highlightcolor": "#ffffff",
            "highlightbackground": self.gray3,
            "borderwidth": 1
        }

    @staticmethod
    def layer_props(bgcolor):
        """
        bundle popular attributes of TK control so they can be reused
        :return: dict of bundled props
        """
        return {"relief": RIDGE, "background": bgcolor}

    def title_props(self, title):
        """
        bundle popular attributes of TK control so they can be reused
        :return: dict of bundled props
        """
        return {
            "text": title,
            "background": self.gray3,
            "width": self.sect_width,
            "borderwidth": 1,
            "relief": RIDGE
        }

    def radio_props(self):
        """
        bundle popular attributes of TK control so they can be reused
        :return: dict of bundled props
        """
        return {
            "background": self.gray2,
            "activebackground": self.gray2,
        }

    def date_props(self):
        """
        bundle popular attributes of TK control so they can be reused
        :return: dict of bundled props
        """
        return {
            "width": 8,
            "increment": 1,
            "font": ("Arial", 8),
            "background": "#666666",
            "buttonbackground": "#666666",
            "foreground": "#eeeeee",
            "highlightthickness": 8,
            "highlightcolor": "#ffffff",
            "highlightbackground": self.gray2,
            "borderwidth": 1
        }

    def label_props(self):
        """
        bundle popular attributes of TK control so they can be reused
        :return: dict of bundled props
        """
        return {
            "background": self.gray2,
            "highlightcolor": "#ffffff",
            "highlightbackground": self.gray2,
            "borderwidth": 1
        }

    def text_props(self):
        """
        bundle popular attributes of TK control so they can be reused
        :return: dict of bundled props
        """
        return {
            "font": ("Arial", 11),
            "background": self.gray1,
            "foreground": "#212121",
            "highlightthickness": 8,
            "highlightbackground": self.gray1,
            "highlightcolor": self.gray1,
            "borderwidth": 0,
            "wrap": "word",
            "spacing1": 11,
            "spacing2": 7,
        }

    def produce_props(self):
        """
        produce dict of key GUI parameters selected by user
        :return: no return parameters
        """
        rows = int(self.box_gen.get())
        props = {
            "pgender": self.sli_wom.get(),
            "pdname": self.sli_nam.get(),
            "pdsurname": self.sli_sur.get(),
            "dob1": self.box_dob1.get(),
            "dob2": self.box_dob2.get(),
        }
        dataset = Dataset().run_workload(rows, **props)
        exp_format = self.rb_choice.get()
        if exp_format == "CSV":
            Export().to_csv(dataset)
        else:
            Export().to_json(dataset)
        self.btn_run_reset()
        return

    def btn_run_reset(self):
        """
        abort button (when generating)
        :return: no return parameters
        """
        self.running = False
        self.btn_run.config(text="Generate", command=self.btn_run_start)
        return

    def btn_run_start(self):
        """
        handle the run button
        :return: no return parameters
        """
        self.running = True
        newthread = threading.Thread(target=self.produce_props)
        newthread.start()
        self.btn_run.config(text="Abort", command=self.btn_run_reset)
        return
Ejemplo n.º 10
0
class EnaSubGui(Frame):
    # The AlleleGui class is an extension of Tkinter Frame. GUI elements go here.

    def selectAll(self, event):
        # I shouldn't need to write a select-All method but TK is kind of annoying.
        event.widget.tag_add("sel", "1.0", "end")

    def customPaste(self, event):
        # Writing a Paste method because TK doesn't operate intuitively. It doesn't replace the highlighted text.
        try:
            event.widget.delete("sel.first", "sel.last")
        except:
            pass
        event.widget.insert("insert", event.widget.clipboard_get())
        return "break"

    def __init__(self, root):
        # Initialize the GUI
        Frame.__init__(self, root)
        root.title("Create and Submit an EMBL-ENA Sequence Submission")
        self.parent = root

        # Assign the icon of this sub-window.
        assignIcon(self.parent)

        # Some basic functionality just doesn't work in TK. For example Ctrl-A, and pasting text.
        # I shouldn't need to encode this but here we are.
        root.bind_class("Text", "<Control-a>", self.selectAll)
        root.bind_class("Text", "<<Paste>>", self.customPaste)

        # To define the exit behavior.  Save the input sequence text.
        self.parent.protocol('WM_DELETE_WINDOW', self.saveAndExit)

        button_opt = {'fill': BOTH, 'padx': 35, 'pady': 5}

        # Setup the Menu bar
        mainMenuBar = Menu(root)

        batchMenu = Menu(mainMenuBar, tearoff=0)
        batchMenu.add_command(label='Configure Batch Settings',
                              command=self.chooseSubmissionOptions)
        batchMenu.add_command(label='Import Submission Data File',
                              command=self.importSubmissions)
        batchMenu.add_command(label='Export Submission Data File',
                              command=self.exportSubmissions)
        mainMenuBar.add_cascade(label='Batch Options', menu=batchMenu)

        helpMenu = Menu(mainMenuBar, tearoff=0)
        helpMenu.add_command(label='How To Use This tool',
                             command=self.howToUse)
        helpMenu.add_command(label='Sample Submission Data',
                             command=self.sampleSequence)
        mainMenuBar.add_cascade(label='Help', menu=helpMenu)

        root.config(menu=mainMenuBar)

        # A frame for the Instructions Label.
        self.instructionsFrame = Frame(self)
        self.instructionText = StringVar()
        self.instructionText.set(
            '\nThis tool will generate a batch of HLA allele submissions for\n'
            + 'the EMBL-ENA nucleotide database.\n')
        Label(self.instructionsFrame,
              width=85,
              height=3,
              textvariable=self.instructionText).pack()
        self.instructionsFrame.pack(expand=False, fill='both')

        # Gather the submission batch to put the data on this frame.
        self.submissionIndex = 0  # This 0-based index indicates what submission within the batch we are currently looking at.
        self.submissionBatch = getConfigurationValue('submission_batch')
        logging.debug(
            'Just loaded the configuration. I have this many submissions in the batch:'
            + str(len(self.submissionBatch.submissionBatch)))
        # A frame to show what submission we are on in the batch.
        self.submIndexFrame = Frame(self)
        self.previousSubmissionButton = Button(self.submIndexFrame,
                                               text='<- Previous Submission',
                                               command=self.previousSubmission)
        self.previousSubmissionButton.grid(row=0, column=0)
        self.submissionIndexText = StringVar()
        # submission Index is zero-based. Add 1 for it to make sense to humans.
        self.submissionIndexText.set('.........')
        self.SubmissionIndexLabel = Label(
            self.submIndexFrame,
            width=25,
            height=3,
            textvariable=self.submissionIndexText)
        self.SubmissionIndexLabel.grid(row=0, column=1)
        self.nextSubmissionButton = Button(self.submIndexFrame,
                                           text='Next Submission ->',
                                           command=self.nextSubmission)
        self.nextSubmissionButton.grid(row=0, column=2)
        self.submIndexFrame.pack()

        self.addSubmissionFrame = Frame(self)
        self.deleteSubmissionButton = Button(
            self.addSubmissionFrame,
            text='Delete Submission',
            command=self.deleteCurrentSubmission)
        self.deleteSubmissionButton.grid(row=0, column=0)
        self.insertSubmissionButton = Button(self.addSubmissionFrame,
                                             text='New Submission',
                                             command=self.newSubmission)
        self.insertSubmissionButton.grid(row=0, column=1)
        self.addSubmissionFrame.pack()

        self.setSubmissionButtonState(
        )  # Buttons must exist before i call this.

        # Create a frame for basic allele sequence information.
        self.sequenceIdentifierFrame = Frame(self)
        #Standard Inputs widths for the form elements
        formInputWidth = 30
        labelInputWidth = 30

        self.sampleIDInstrText = StringVar()
        self.sampleIDInstrText.set('Sample ID:')
        self.sampleIDinstrLabel = Label(
            self.sequenceIdentifierFrame,
            width=labelInputWidth,
            height=1,
            textvariable=self.sampleIDInstrText).grid(row=0, column=0)
        self.inputSampleID = StringVar()
        self.inputSampleIDEntry = Entry(self.sequenceIdentifierFrame,
                                        width=formInputWidth,
                                        textvariable=self.inputSampleID)
        self.inputSampleIDEntry.grid(row=0, column=1)

        self.geneInstrStringVar = StringVar()
        self.geneInstrStringVar.set('Gene:')
        self.geneInstrLabel = Label(self.sequenceIdentifierFrame,
                                    width=labelInputWidth,
                                    height=1,
                                    textvariable=self.geneInstrStringVar).grid(
                                        row=1, column=0)
        self.inputGene = StringVar()
        self.inputGeneEntry = Entry(self.sequenceIdentifierFrame,
                                    width=formInputWidth,
                                    textvariable=self.inputGene)
        self.inputGeneEntry.grid(row=1, column=1)

        self.chooseClassIntVar = IntVar()
        self.chooseClassIntVar.set(1)
        self.classIRadio = Radiobutton(self.sequenceIdentifierFrame,
                                       text="HLA Class I ",
                                       variable=self.chooseClassIntVar,
                                       value=1)
        self.classIRadio.grid(row=2, column=0)
        self.classIIRadio = Radiobutton(self.sequenceIdentifierFrame,
                                        text="HLA Class II",
                                        variable=self.chooseClassIntVar,
                                        value=2)
        self.classIIRadio.grid(row=2, column=1)

        self.alleleInstrText = StringVar()
        self.alleleInstrText.set('Allele Local Name:')
        self.alleleInstrLabel = Label(self.sequenceIdentifierFrame,
                                      width=labelInputWidth,
                                      height=1,
                                      textvariable=self.alleleInstrText).grid(
                                          row=3, column=0)
        self.inputAllele = StringVar()
        self.inputAlleleEntry = Entry(self.sequenceIdentifierFrame,
                                      width=formInputWidth,
                                      textvariable=self.inputAllele)
        self.inputAlleleEntry.grid(row=3, column=1)

        self.sequenceIdentifierFrame.pack()

        # Create a frame for the input widget and scrollbars.
        self.featureInputFrame = Frame(self)
        self.featureInstrText = StringVar()
        self.featureInstrText.set('Annotated Sequence:')
        self.featureInstrLabel = Label(
            self.featureInputFrame,
            width=80,
            height=1,
            textvariable=self.featureInstrText).pack()
        self.featureInputXScrollbar = Scrollbar(self.featureInputFrame,
                                                orient=HORIZONTAL)
        self.featureInputXScrollbar.pack(side=BOTTOM, fill=X)
        self.featureInputYScrollbar = Scrollbar(self.featureInputFrame)
        self.featureInputYScrollbar.pack(side=RIGHT, fill=Y)
        self.featureInputGuiObject = Text(
            self.featureInputFrame,
            width=80,
            height=8,
            wrap=NONE,
            xscrollcommand=self.featureInputXScrollbar.set,
            yscrollcommand=self.featureInputYScrollbar.set)
        self.featureInputXScrollbar.config(
            command=self.featureInputGuiObject.xview)
        self.featureInputYScrollbar.config(
            command=self.featureInputGuiObject.yview)
        self.featureInputGuiObject.pack(expand=True, fill='both')
        self.featureInputFrame.pack(expand=True, fill='both')

        # Create  Frame for "Generate Submission" button.
        self.submButtonFrame = Frame(self)

        #self.submissionOptionsButton = Button(self.submButtonFrame, text='1) Submission Options', command=self.chooseSubmissionOptions)
        #self.submissionOptionsButton.grid(row=0, column=0)
        self.annotateFeaturesButton = Button(
            self.submButtonFrame,
            text='2) Annotate Exons & Introns',
            command=self.annotateInputSequence)
        self.annotateFeaturesButton.grid(row=0, column=1)
        #self.generateSubmissionButton = Button(self.submButtonFrame, text='3) Generate an ENA-ENA submission', command=self.constructSubmission)
        #self.generateSubmissionButton.grid(row=0, column=2)
        self.submButtonFrame.pack()

        # Output interface is contained on a frame.
        self.submOutputFrame = Frame(self)
        self.outputENASubmission = StringVar()
        self.outputENASubmission.set('Allele Submission Preview:')
        self.outputENALabel = Label(
            self.submOutputFrame,
            width=80,
            height=1,
            textvariable=self.outputENASubmission).pack()
        self.submOutputXScrollbar = Scrollbar(self.submOutputFrame,
                                              orient=HORIZONTAL)
        self.submOutputXScrollbar.pack(side=BOTTOM, fill=X)
        self.submOutputYScrollbar = Scrollbar(self.submOutputFrame)
        self.submOutputYScrollbar.pack(side=RIGHT, fill=Y)
        self.submOutputGuiObject = Text(
            self.submOutputFrame,
            width=80,
            height=8,
            wrap=NONE,
            xscrollcommand=self.submOutputXScrollbar.set,
            yscrollcommand=self.submOutputYScrollbar.set,
            state=DISABLED)
        self.submOutputXScrollbar.config(
            command=self.submOutputGuiObject.xview)
        self.submOutputYScrollbar.config(
            command=self.submOutputGuiObject.yview)
        self.submOutputGuiObject.pack(expand=True, fill='both')
        self.submOutputFrame.pack(expand=True, fill='both')

        self.uploadSubmissionFrame = Frame(self)
        # TODO: Think about: Should I export a zip file with all the submissions?
        # TODO: Or else a .csv file with the submision data?
        # TODO: Duh! All of it! Submission files and data in a .zip.
        # TODO: In that case, remove the export button here. I put it above, in the GUI.
        #self.saveSubmissionButton = Button(self.uploadSubmissionFrame, text='4) Save Submission to My Computer', command=self.saveSubmissionFile)
        #self.saveSubmissionButton.pack(**button_opt)
        self.uploadButton = Button(self.uploadSubmissionFrame,
                                   text='5) Upload Submission to EMBL-ENA',
                                   command=self.uploadSubmission)
        self.uploadButton.pack(**button_opt)
        self.exitButton = Button(self.uploadSubmissionFrame,
                                 text='Exit',
                                 command=self.saveAndExit)
        self.exitButton.pack(**button_opt)
        self.uploadSubmissionFrame.pack()

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

        self.loadCurrentSubmission()

    def loadCurrentSubmission(self):
        currentSubmission = self.submissionBatch.submissionBatch[
            self.submissionIndex]

        newSubmissionIndexText = 'Submission ' + str(
            self.submissionIndex + 1) + ' / ' + str(
                len(self.submissionBatch.submissionBatch))
        self.submissionIndexText.set(newSubmissionIndexText)

        self.setSubmissionButtonState()

        self.inputSampleID.set('' if currentSubmission.cellId is None else
                               currentSubmission.cellId)
        self.inputGene.set(
            '' if currentSubmission.submittedAllele.geneLocus is None else
            currentSubmission.submittedAllele.geneLocus)
        self.inputAllele.set('' if currentSubmission.localAlleleName is None
                             else currentSubmission.localAlleleName)
        self.chooseClassIntVar.set(
            int(currentSubmission.submittedAllele.hlaClass)
            if currentSubmission.submittedAllele.hlaClass is not None else 1
        )  # I think this works? 1 or 2 is always stored. 1 or 2 are the potential values of the intvar.
        self.overwriteSequenceText(' ')
        self.overwriteSubmissionText(' ')
        self.overwriteSequenceText(
            currentSubmission.submittedAllele.getAnnotatedSequence(
                includeLineBreaks=True))
        self.constructSubmission()

    def saveCurrentSubmission(self):
        currentSubmission = self.submissionBatch.submissionBatch[
            self.submissionIndex]

        currentSubmission.submittedAllele.rawSequence = self.featureInputGuiObject.get(
            '1.0', 'end')
        currentSubmission.submittedAllele.identifyFeaturesFromFormattedSequence(
        )
        currentSubmission.localAlleleName = self.inputAllele.get()
        currentSubmission.submittedAllele.geneLocus = self.inputGene.get()
        currentSubmission.cellId = self.inputSampleID.get()
        currentSubmission.submittedAllele.hlaClass = str(
            self.chooseClassIntVar.get()
        )  # I think this works? 1 or 2 is always stored. 1 or 2 are the potential values of the intvar.

        self.submissionBatch.submissionBatch[
            self.submissionIndex] = currentSubmission

    def importSubmissions(self):
        # Popup warning message: This will ADD the imported submissions to the batch.
        # Figure out a way to either replace or add the submission files.

        logging.error('Have not implemented import submission files yet.')

    def exportSubmissions(self):
        logging.error('Have not implemented export submission files yet.')

    def deleteCurrentSubmission(self):
        logging.debug('deleteCurrentSubmission pressed')
        self.saveCurrentSubmission()

        if (len(self.submissionBatch.submissionBatch) == 1):
            showInfoBox(
                'Cannot delete last submission.',
                'You cannot delete the last remaining submission in the batch.'
            )
        else:
            del self.submissionBatch.submissionBatch[self.submissionIndex]

            # If that was the rightmost in the batch, we need to reduce the index
            if ((self.submissionIndex) >= len(
                    self.submissionBatch.submissionBatch)):
                self.submissionIndex = self.submissionIndex - 1

            self.loadCurrentSubmission()

    def newSubmission(self):
        logging.debug('newSubmission pressed')
        self.saveCurrentSubmission()
        # I'm adding a submission AFTER the current one. This feels intuitive to me.
        self.submissionBatch.submissionBatch.insert(self.submissionIndex + 1,
                                                    AlleleSubmission())
        self.submissionIndex += 1
        self.loadCurrentSubmission()

    def previousSubmission(self):
        logging.debug('previousSubmission pressed')
        self.saveCurrentSubmission()
        if (self.submissionIndex <= 0):
            # Button should be disabled, but we don't want to walk left if we're at minimum.
            pass
        else:
            self.submissionIndex = self.submissionIndex - 1
            self.loadCurrentSubmission()

    def nextSubmission(self):
        logging.debug('nextSubmission pressed')
        self.saveCurrentSubmission()
        if ((self.submissionIndex + 1) >= len(
                self.submissionBatch.submissionBatch)):
            # Button should be disabled, but we don't want to walk right if we're at maximum.
            pass
        else:
            self.submissionIndex = self.submissionIndex + 1
            self.loadCurrentSubmission()

    def chooseSubmissionOptions(self):
        logging.info('Opening the EMBL-ENA Submission Options Dialog')

        self.disableGUI()

        enaOptionsRoot = Toplevel()
        enaOptionsRoot.bind("<Destroy>", self.enableGUI)
        EnaSubOptionsForm(enaOptionsRoot).pack()

        # Set the X and the Y Position of the options window, so it is nearby.
        enaOptionsRoot.update()
        windowXpos = str(self.parent.winfo_geometry().split('+')[1])
        windowYpos = str(self.parent.winfo_geometry().split('+')[2])
        newGeometry = (str(enaOptionsRoot.winfo_width()) + 'x' +
                       str(enaOptionsRoot.winfo_height()) + '+' +
                       str(windowXpos) + '+' + str(windowYpos))
        enaOptionsRoot.geometry(newGeometry)

        enaOptionsRoot.mainloop()

    def sampleSequence(self):
        logging.debug('sampleSequence pressed')
        logging.error('Have not implemented sample sequence yet.')

        # TODO: Old code. I need to create the batch submission here.
        # self.featureInputGuiObject.insert('1.0', 'aag\nCGTCGT\nccg\nGGCTGA\naat')
        #
        # # Clear the password, keep the username
        # #assignConfigurationValue('ena_username','')
        # assignConfigurationValue('ena_password','')
        #
        # assignConfigurationValue('sample_id', 'sample_12345')
        # assignConfigurationValue('gene','HLA-C')
        # assignConfigurationValue('class','1')
        # assignConfigurationValue("allele_name",'Allele*01:02MstNew.6')
        #
        # assignConfigurationValue('study_accession','PRJEB12345')
        #
        # assignConfigurationValue('choose_project','2')
        #
        # assignConfigurationValue('study_identifier','HLA_Analysis_Project')
        # assignConfigurationValue('study_short_title','HLA Typing for Cancer Research.')
        # assignConfigurationValue('study_abstract','An abstract is a more in-depth description of the nature of the research project.')
        #
        # assignConfigurationValue('analysis_alias','unique_HLA_analysis_alias')
        # assignConfigurationValue('analysis_title','Novel HLA sequence from patient with Leukemia')
        # assignConfigurationValue('analysis_description','This is an HLA-A sequence from a patient. It was discovered that he has Leukemia, so we decided to sequence his HLA.')
        #
        # self.constructSubmission()

    def howToUse(self):
        # This method should popup some instruction text in a wee window.
        # This should be explicit on how to use the tool.
        logging.error(
            'howToUse() is probably outdated. Check if it needs updating.')

        showInfoBox(
            'How to use this tool',
            'This software is to be used to create an\n' +
            'ENA-formatted submission document,\n' +
            'which specifies a (novel) HLA allele.\n\n' +
            'This tool requires you to submit a\n' +
            'full length HLA allele, including\n' + '5\' and 3\' UTRs.\n\n' +
            'To create & submit an EMBL-ENA submission:\n\n' +
            '1.) Paste a full-length HLA sequence in\n' +
            'the Annotated Sequence text area.\n' +
            '2.) Push [Submission Options] and provide\n' +
            'the necessary sequence metadata.\n' +
            '3.) Push [Annotate Exons & Introns] to\n' +
            'annotate your exons automatically.\n' +
            '4.) Push [Generate an EMBL-ENA submission]\n' +
            'button to generate a submission.\n' +
            '5.) Push [Upload Submission to EMBL-ENA]\n' +
            'to submit the sequence\n' + 'using ENA Webin REST interface\n\n' +
            'If exon annotation is not available,\n' +
            'it may be necessary to annotate manually.\n\n' +
            'Sequences should follow this pattern:\n' +
            '5\'utr EX1 int1 EX2 ... EX{X} 3\'utr\n\n' +
            'Use capital letters for exons,\n' +
            'lowercase for introns & UTRs.\n\n' +
            'Push the "Example Sequence" button to see\n' +
            'an example of a formatted sequence.\n\n' +
            'More information available\n' + 'on the MUMC Github Page:\n' +
            'https://github.com/transplantation-\n' +
            'immunology-maastricht/saddle-bags')

    # TODO: Delete this method, use exportSubmissions instead.
    """
    def saveSubmissionFile(self):
        logging.error('Deprecated the save submission file method. But somehow I still called the method.')
        # Ask user for a output file location, and write the ENA submission to a file.
        # This takes the input from the output field, rather than generate a new submission.
        # So the user can edit the submission before or after saving it.

        
        self.dir_opt = options = {}       
        options['initialdir'] = expanduser("~")
        options['parent'] = self
        options['title'] = 'Specify your output file.'
        options['initialfile'] = 'ENA.HLA.Submission.txt'
        outputFileObject = filedialog.asksaveasfile(**self.dir_opt)
        submissionText = self.submOutputGuiObject.get('1.0', 'end')
        outputFileObject.write(submissionText)
        
        # TODO: Did I detect any exceptions? Maybe I don't have permission to write that file
        # I saw an error when i wrote to a network drive once. 
    """

    def annotateInputSequence(self):
        logging.debug('Annotating Input Sequence')
        try:
            self.disableGUI()
            self.update()

            # Popup.  This uses NMDP BTM ACT tool to annotate sequences.
            if (messagebox.askyesno(
                    'Annotate Sequence?',
                    'This will annotate your sequence using the\n' +
                    'NMDP: BeTheMatch Gene Feature\n' +
                    'Enumeration / Allele Calling Tool.\n\n' +
                    'Do you want to continue?')):

                roughNucleotideSequence = collectAndValidateRoughSequence(
                    self.featureInputGuiObject.get('1.0', 'end'))
                currentSubmission = self.submissionBatch.submissionBatch[
                    self.submissionIndex]
                currentSubmission.submittedAllele.rawSequence = roughNucleotideSequence
                currentSubmission.submittedAllele.annotateSequenceUsingService(
                    rawRequestURL=getConfigurationValue(
                        'nmdp_act_rest_address'))
                self.overwriteSequenceText(
                    currentSubmission.submittedAllele.getAnnotatedSequence(
                        includeLineBreaks=True))

            self.update()
            self.enableGUI()

        except Exception:
            showInfoBox('Error Annotating Input Sequence.', str(exc_info()))
            self.update()
            self.enableGUI()
            raise

    def overwriteSequenceText(self, sequenceText=None):
        if (sequenceText is not None and len(sequenceText) > 0):
            oldState = self.featureInputGuiObject.cget('state')
            self.featureInputGuiObject.config(state=NORMAL)
            self.featureInputGuiObject.delete('1.0', 'end')
            self.featureInputGuiObject.insert('1.0', sequenceText)
            self.featureInputGuiObject.config(state=oldState)
        else:
            logging.warning(
                'Attempting to replace sequence text with an empty value.')

    def overwriteSubmissionText(self, submissionText=None):
        if (submissionText is not None and len(submissionText) > 0):
            oldState = self.submOutputGuiObject.cget('state')
            self.submOutputGuiObject.config(state=NORMAL)
            self.submOutputGuiObject.delete('1.0', 'end')
            self.submOutputGuiObject.insert('1.0', submissionText)
            self.submOutputGuiObject.config(state=oldState)
        else:
            logging.warning(
                'Attempting to replace submission text with an empty value.')

    def uploadSubmission(self):
        logging.debug('Uploading Submission Batch')
        # TODO: Perform a Batch Submission
        #performFullSubmission(self.submOutputGuiObject.get('1.0', 'end') )
        logging.error(
            'Upload Submission needs batch Submission functionality. Add it.')

    def constructSubmission(self):
        # Gather sequence information from the input elements, and generate a text ENA submission.
        logging.debug('Constructing Submission')
        try:
            currentSubmission = self.submissionBatch.submissionBatch[
                self.submissionIndex]

            # TODO: What happens when the sequence is not annotated yet? Probably need to remove this logic. Annoying.
            # if (isSequenceAlreadyAnnotated(roughNucleotideSequence)):
            #     annotatedSequence = roughNucleotideSequence
            #
            # else:
            #
            #     if (messagebox.askyesno('Auto - Annotate Exons?'
            #         , 'It looks like your sequence features have not been identified.\n' +
            #         'Would you like to annotate using NMDP: BeTheMatch\n' +
            #         'Gene Feature Enumeration Tool?')):
            #
            #         self.annotateInputSequence()
            #         annotatedSequence = collectRoughSequence(self.featureInputGuiObject)
            #     else:
            #         # You chose not to annotate.  Hope this works out for you.
            #         annotatedSequence = roughNucleotideSequence

            allGen = EnaSubGenerator()
            allGen.submission = currentSubmission
            allGen.submissionBatch = self.submissionBatch
            enaSubmissionText = allGen.buildENASubmission()

            if (enaSubmissionText is None or len(enaSubmissionText) < 1):
                #showInfoBox('Empty submission text'
                #    ,'You are missing some required information.\n'
                #    + 'Try the \'Submission Options\' button.\n')
                logging.warning('Submission text is empty.')

                self.overwriteSubmissionText('')
            else:
                self.overwriteSubmissionText(enaSubmissionText)

        except KeyError:
            showInfoBox(
                'Missing Submission Options',
                'You are missing some required information.\n' +
                'Use the \'Submission Options\' button.\n' + 'Missing Data: ' +
                str(exc_info()))

        except HlaSequenceException:
            showInfoBox('I see a problem with Sequence Format.',
                        str(exc_info()))

        except Exception:
            showInfoBox('Error Constructing Submission.', str(exc_info()))
            raise

    def saveAndExit(self):
        logging.debug('saveAndExit pressed')
        self.saveCurrentSubmission()
        assignConfigurationValue('submission_batch', self.submissionBatch)

        writeConfigurationFile()
        self.parent.destroy()

    def enableGUI(self, event=None):
        self.toggleGUI(True)

    def disableGUI(self):
        self.toggleGUI(False)

    def toggleGUI(self, isEnabled):
        logging.debug('Toggling GUI Widgets:' + str(isEnabled))

        newState = (NORMAL if (isEnabled) else DISABLED)

        # Choosing the widgets individually, this makes the most sense I think.
        #self.submissionOptionsButton.config(state=newState)
        #self.generateSubmissionButton.config(state=newState)
        self.annotateFeaturesButton.config(state=newState)
        self.uploadButton.config(state=newState)
        self.exitButton.config(state=newState)
        self.previousSubmissionButton.config(state=newState)
        self.nextSubmissionButton.config(state=newState)
        self.deleteSubmissionButton.config(state=newState)
        self.insertSubmissionButton.config(state=newState)
        self.classIRadio.config(state=newState)
        self.classIIRadio.config(state=newState)
        self.inputSampleIDEntry.config(state=newState)
        self.inputGeneEntry.config(state=newState)
        self.inputAlleleEntry.config(state=newState)
        self.featureInputGuiObject.config(state=newState)

        # set the Submission next/previous buttons, only if the GUI is enabled.
        if (isEnabled):
            self.setSubmissionButtonState()

    def setSubmissionButtonState(self):
        # Enable or disable the next/previous buttons.
        if (self.submissionIndex <= 0):
            self.previousSubmissionButton.config(state=DISABLED)
        else:
            self.previousSubmissionButton.config(state=NORMAL)

        if ((self.submissionIndex + 1) >= len(
                self.submissionBatch.submissionBatch)):
            self.nextSubmissionButton.config(state=DISABLED)
        else:
            self.nextSubmissionButton.config(state=NORMAL)

        if (len(self.submissionBatch.submissionBatch) <= 1):
            self.deleteSubmissionButton.config(state=DISABLED)
        else:
            self.deleteSubmissionButton.config(state=NORMAL)
Ejemplo n.º 11
0
port_lbl.grid(row=0,column=0, padx = 2, pady = 5)
sel_Port.grid(row=0,column=1, padx = 5, pady = 5)
stat_lbl.grid(row=1,column=0, padx = 2, pady = 5)
stat_etry.grid(row=1, column=1, padx = 5, pady = 5)
testConn_but.grid(row=2, column=0, padx = 2, pady = 5)
disConn_but.grid(row=2, column=1, padx = 2, pady = 5)

frame_Mode = LabelFrame(frame_Conn, text = "App mode (WIP)")
mode_auto = Radiobutton(frame_Mode, text = "Auto", variable = modeVal, value = 1, width = 20, height = 1,command=modeSet)
mode_manual = Radiobutton(frame_Mode, text = "Manual", variable = modeVal, value = 2, width = 20, height = 1,command=modeSet)
frame_Mode.grid(row=4,columnspan=2)
mode_auto.grid(row=0, columnspan=2,padx = 5, pady = 5)
mode_manual.grid(row=1, columnspan=2,padx = 5, pady = 5)

#mode_auto.config(state='disabled')
mode_manual.config(state='disabled')

#ELoad Information & control grouping
frame_ELOAD = LabelFrame(App, text="ELOAD Interface")
frame_Meas = LabelFrame(frame_ELOAD, text="ELOAD Measured Values")
curr_lbl = Label(frame_Meas, width=10, height=1,text = "Current (A):")
volt_lbl = Label(frame_Meas, width=10, height=1,text = "Voltage (V):")
curr_etry = Entry(frame_Meas, width=8, textvariable=currVal,justify='center', state='disabled',disabledbackground='green',disabledforeground='white')
volt_etry = Entry(frame_Meas, width=8, textvariable=voltVal,justify='center', state='disabled',disabledbackground='green',disabledforeground='white')

##Measured & set current display
frame_ELOAD.place(x=225)
frame_Meas.grid(row=0)
curr_lbl.grid(row=0,column=0,padx=5,pady=1)
volt_lbl.grid(row=1,column=0,padx=5,pady=1)
curr_etry.grid(row=0,column=1,padx=5,pady=1)
Ejemplo n.º 12
0
class GUI():
    def __init__(self,root,song):
        # given parameters
        self.root = root
        self.song = song

        # main window
        self.root.title("Song segment player")
        self.root.iconbitmap(r'Images/icon.ico')
        self.root.configure(background='white')

        # menubar
        self.menubar = Menu(self.root)
        self.filemenu = Menu(self.menubar,tearoff=0)
        self.filemenu.add_command(label="Open",
                                  command=lambda:b.openSong(self))
        self.menubar.add_cascade(label="File",menu=self.filemenu)

        # images for buttons
        self.segmentIm = PhotoImage(file=r'Images/SegmentB.png')
        self.repSegIm = PhotoImage(file=r'Images/Repeat.png')
        self.playIm = PhotoImage(file=r'Images/PlayB.png')
        self.pauseIm = PhotoImage(file=r'Images/PauseB.png')
        self.stopIm = PhotoImage(file=r'Images/StopB.png')
        self.ffIm = PhotoImage(file=r'Images/ffB.png')
        self.rwIm = PhotoImage(file=r'Images/rwB.png')
        self.fullSpeedIm = PhotoImage(file=r'Images/FullSpeedB.png')
        self.halfSpeedIm = PhotoImage(file=r'Images/HalfSpeedB.png')
        self.sliderIm = PhotoImage(file=r'Images/SliderB.png')
        self.cursorIm = PhotoImage(file=r'Images/Cursor.png')
        self.magPlusIm = PhotoImage(file=r'Images/MagPlus.png')
        self.magMinusIm = PhotoImage(file=r'Images/MagMinus.png')

        # making buttons
        self.segmentB = Button(image=self.segmentIm,
                               command=lambda:b.playSeg(self.song))
        self.repSegB = Button(image=self.repSegIm,
                                 command=lambda:b.repeatSeg(self.song,self.repSegB))
        self.playB = Button(image=self.playIm,
                            command=lambda:b.playStream(self.song))
        self.pauseB = Button(image=self.pauseIm,
                             command=lambda:b.pauseStream(self.song))
        self.stopB = Button(image=self.stopIm,
                            command=lambda:b.stopStream(self.song))
        self.ffB = Button(image=self.ffIm,
                          command=lambda:b.ffStream(self.song))
        self.rwB = Button(image=self.rwIm,
                          command=lambda:b.rwStream(self.song))
        self.fullSpeedB = Button(image=self.fullSpeedIm)
        self.halfSpeedB = Button(image=self.halfSpeedIm)
        # making radio buttons
        self.CLICKMODE = StringVar(value="slide")
        self.sliderB = Radiobutton(
            self.root,
            image=self.sliderIm,
            variable=self.CLICKMODE,
            value='slide',
            indicatoron=0)
        self.cursorB = Radiobutton(
            self.root,
            image=self.cursorIm,
            variable=self.CLICKMODE,
            value='curse',
            indicatoron=0)
        self.magPlusB = Radiobutton(
            self.root,
            image=self.magPlusIm,
            variable=self.CLICKMODE,
            value='mag+',
            indicatoron=0)
        self.magMinusB = Radiobutton(
            self.root,
            image=self.magMinusIm,
            variable=self.CLICKMODE,
            value='mag-',
            indicatoron=0)

        # setting button parameters
        self.allButts = [self.segmentB,self.repSegB,self.playB,self.stopB,
                         self.pauseB,self.ffB,self.rwB,self.fullSpeedB,
                         self.halfSpeedB,self.sliderB,self.cursorB,
                         self.magPlusB,self.magMinusB]
        [butt.config(bg='white') for butt in self.allButts]
        # disable all buttons to start with
        [butt.config(state='disabled') for butt in self.allButts]
        self.sliderB.config(state='normal')

        # placing buttons
        rowc = 3
        self.segmentB.grid(row=0,column=2)
        self.repSegB.grid(row=0,column=3)
        self.playB.grid(row=rowc,column=3)
        self.pauseB.grid(row=rowc,column=2)
        self.stopB.grid(row=rowc,column=1)
        self.ffB.grid(row=rowc,column=4)
        self.rwB.grid(row=rowc,column=0)
        self.fullSpeedB.grid(row=0,column=4,columnspan=3)
        self.halfSpeedB.grid(row=0,column=5,columnspan=3)
        self.sliderB.grid(row=2,column=0)
        self.cursorB.grid(row=2,column=1)
        self.magPlusB.grid(row=2,column=2)
        self.magMinusB.grid(row=2,column=3)

        # display song title
        if self.song.songname:
            t = self.song.songname[0:-4]
        else:
            t = ''
        self.songTitleL = Label(self.root,text=t,bg='white')
        self.songTitleL.grid(row=0,column=0)

        # making figure canvas
        self.canvas = FigureCanvasTkAgg(self.song.fig,master=self.root)
        self.canvas.draw()
        self.canvas.get_tk_widget().grid(row=rowc-2,column=0,columnspan=5)

        # connecting canvas to monitor events
        self.cidpress = self.canvas.mpl_connect(
            'button_press_event',
            lambda event:e.on_press(event,self.song,self.CLICKMODE))
        self.cidrelease = self.canvas.mpl_connect(
            'button_release_event',
            lambda event:e.on_release(event,self.song))
        self.cidmotion = self.canvas.mpl_connect(
            'motion_notify_event',
            lambda event:e.on_motion(event,self.song))

        self.root.bind('<space>', lambda event:b.playPauseStream(self.song))
        self.root.bind('<Return>', lambda event:b.playSeg(self.song))

        # set cursor updating
        self.root.after(10000,lambda: e.updateCursor(self))

        # insert menu bar
        self.root.config(menu=self.menubar)

        # closing behaviour
        self.root.protocol("WM_DELETE_WINDOW",self.on_closing)



    def on_closing(self):
        self.canvas.mpl_disconnect(self.cidpress)
        self.canvas.mpl_disconnect(self.cidrelease)
        self.canvas.mpl_disconnect(self.cidmotion)
        self.root.destroy()
        self.song.wf.close()
        self.song.stream.close()
        self.song.p.terminate()
        [os.remove(s) for s in self.song.createdFilepaths]

    def updateCursor(self):
        if self.song.wf:
            pos = self.song.wf.tell()/self.song.RATE
            self.song.cursor[0].set_x(pos)
            self.canvas.draw()
        self.root.after(250,self.updateCursor)
Ejemplo n.º 13
0
    def __init__(self, operation):
        root = Tk(className=" ALINVISIBLECLOAK ")
        root.geometry("500x250+1410+780")
        root.resizable(0, 0)
        root.iconbitmap(
            os.path.join(cwd + '\\UI\\icons', 'alinvisiblecloak.ico'))
        root.overrideredirect(1)
        if operation.lower() == 'hide':
            opr = 'Attrib +h /s /d'
            response = "hidden"
            root.attributes('-alpha', 0.6)
        elif operation.lower() == 'unhide':
            opr = 'Attrib -h -s /s /d'
            response = "unhidden"
            root.attributes('-alpha', 1)

        def liftWindow():
            root.lift()
            root.after(1000, liftWindow)

        def callback(event):
            root.geometry("450x250+1460+800")

        def showScreen(event):
            root.deiconify()
            root.overrideredirect(1)

        def screenAppear(event):
            root.overrideredirect(1)

        def hideScreen():
            root.overrideredirect(0)
            root.iconify()

        def getFile():
            folderPathEntry.delete(1.0, END)
            filename = filedialog.askdirectory()
            folderPathEntry.insert(1.0, filename)

        def folderOperation():
            text.delete(1.0, END)
            selection = var.get()
            path = folderPathEntry.get("1.0", END)
            path = path.replace('/', '\\')[:-1]
            if selection == 1:
                os.system(f'{opr} "{path}"')
                path = path + '\\*'
                os.system(f'{opr} "{path}"')
                text.insert(
                    1.0, "Folder and it's sub folders and files are " +
                    f"now {response}")
            elif selection == 2:
                os.system(f'{opr} "{path}"')
                if operation.lower() == 'hide':
                    path = path + '\\*'
                    os.system(f'Attrib -h -s /s /d "{path}"')
                elif operation.lower() == 'unhide':
                    path = path + '\\*'
                    os.system(f'Attrib +h /s /d "{path}"')
                text.insert(1.0, f"Folder is now {response}")

        textHighlightFont = font.Font(family='OnePlus Sans Display', size=12)
        appHighlightFont = font.Font(family='OnePlus Sans Display',
                                     size=12,
                                     weight='bold')

        titleBar = Frame(root, bg='#141414', relief=SUNKEN, bd=0)
        icon = Image.open(
            os.path.join(cwd + '\\UI\\icons', 'alinvisiblecloak.ico'))
        icon = icon.resize((30, 30), Image.ANTIALIAS)
        icon = ImageTk.PhotoImage(icon)
        iconLabel = Label(titleBar, image=icon)
        iconLabel.photo = icon
        iconLabel.config(bg='#141414')
        iconLabel.grid(row=0, column=0, sticky="nsew")
        titleLabel = Label(titleBar,
                           text='ALINVISIBLECLOAK',
                           fg='#909090',
                           bg='#141414',
                           font=appHighlightFont)
        titleLabel.grid(row=0, column=1, sticky="nsew")
        closeButton = Button(titleBar,
                             text="x",
                             bg='#141414',
                             fg="#909090",
                             borderwidth=0,
                             command=root.destroy,
                             font=appHighlightFont)
        closeButton.grid(row=0, column=3, sticky="nsew")
        minimizeButton = Button(titleBar,
                                text="-",
                                bg='#141414',
                                fg="#909090",
                                borderwidth=0,
                                command=hideScreen,
                                font=appHighlightFont)
        minimizeButton.grid(row=0, column=2, sticky="nsew")
        titleBar.grid_columnconfigure(0, weight=1)
        titleBar.grid_columnconfigure(1, weight=50)
        titleBar.grid_columnconfigure(2, weight=1)
        titleBar.grid_columnconfigure(3, weight=1)
        titleBar.pack(fill=X)

        folderPath = Button(root,
                            text="FOLDER PATH",
                            borderwidth=0,
                            highlightthickness=3,
                            command=getFile)
        folderPath.pack(fill=X)
        folderPath.config(font=appHighlightFont)
        folderPathEntry = Text(root,
                               highlightthickness=3,
                               bd=0,
                               font=appHighlightFont,
                               height=1)
        folderPathEntry.pack(fill=BOTH, expand=True)
        ask = Label(root,
                    text=f'DO YOU WANT TO {operation.upper()} ' +
                    'SUB FOLDERS AND FILES ALSO?')
        ask.pack(fill=X, pady=5)
        ask.config(font=appHighlightFont)

        confirm = Label(root)
        confirm.pack(fill=X)
        confirm.config(font=appHighlightFont)
        var = IntVar()
        radioYes = Radiobutton(confirm,
                               text="Yes",
                               variable=var,
                               value=1,
                               command=folderOperation)
        radioYes.config(font=appHighlightFont)
        radioYes.grid(column=0, row=0, padx=70)

        radioNo = Radiobutton(confirm,
                              text="No",
                              variable=var,
                              value=2,
                              command=folderOperation)
        radioNo.config(font=appHighlightFont)
        radioNo.grid(column=1, row=0, padx=70)

        text = Text(root,
                    font="sans-serif",
                    relief=SUNKEN,
                    highlightthickness=5,
                    bd=0)
        text.config(height=2, font=textHighlightFont)
        text.pack(fill=BOTH, expand=True)

        titleBar.bind("<B1-Motion>", callback)
        titleBar.bind("<Button-3>", showScreen)
        titleBar.bind("<Map>", screenAppear)

        liftWindow()
        root.mainloop()
class Display_Frame(tkinter.Frame):
    def __init__(self, root):
        super().__init__(root, width=1000, height=1000)

        self.angles = []

        self.units_radio_rad = Radiobutton(self, 
                                           variable=display_settings.AngleUnits,
                                           text="radians",
                                           value=display_settings.UNITS_RADIANS)
        self.units_radio_rad.place(y=10, x=20)
        self.units_radio_deg = Radiobutton(self, 
                                           variable=display_settings.AngleUnits,
                                           text="degrees",
                                           value=display_settings.UNITS_DEGREES)
        self.units_radio_deg.place(y=30, x=20)

        self.angle_labels = []
        self.angle_boxes = []
        
        self.grid_lines_CB = Checkbutton(self,
                                         variable=display_settings.ShowGrid,
                                         text="Show Grid")
        self.grid_numbers_CB = Checkbutton(self,
                                           variable=display_settings.ShowGridNumbers,
                                           text="Show Grid Numbers")
        self.arm_bounds_CB = Checkbutton(self,
                                         variable=display_settings.ShowArmBounds,
                                         text="Show Arm Bounds")
        self.angle_text_CB = Checkbutton(self,
                                         variable=display_settings.ShowAngleText,
                                         text="Show Angle Text")
        self.angle_arc_CB = Checkbutton(self, 
                                        variable=display_settings.ShowAngleArc,
                                        text="Show Angle Arc")
        self.fit_arm_button = tkinter.Button(self, text="Fit Arm")

        elements = [self.grid_lines_CB, self.grid_numbers_CB,
                    self.arm_bounds_CB, self.angle_text_CB,
                    self.angle_arc_CB, self.fit_arm_button]
        for i in range(len(elements)):
            elements[i].place(x=200, y=10 + i * 20)
        
    def bind_canvas(self, canvas):
        self.units_radio_rad.config(command=lambda self=self: [self.refresh_angle_elements(), canvas.update()])
        self.units_radio_deg.config(command=lambda self=self: [self.refresh_angle_elements(), canvas.update()])
        
        self.grid_lines_CB.config(command=canvas.update)
        self.grid_numbers_CB.config(command=canvas.update)
        self.arm_bounds_CB.config(command=canvas.update)
        self.angle_text_CB.config(command=canvas.update)
        self.angle_arc_CB.config(command=canvas.update)
        self.fit_arm_button.config(command=canvas.scale_to_fit_arm)
        
    def refresh_angle_elements(self):
        angle_mult = 1
        if display_settings.AngleUnits.get() == display_settings.UNITS_DEGREES:
            angle_mult = (180 / 3.14159)
        for i in range(len(self.angles)):
            self.angle_boxes[i].config(state="normal")
            self.angle_boxes[i].delete(0, tkinter.END)
            angle = round(self.angles[i] * angle_mult, 3)
            self.angle_boxes[i].insert(0, str(angle))
            self.angle_boxes[i].config(state="disabled")
        
    def set_elements(self, angles):
        self.angles = angles
        while len(self.angle_boxes) < len(angles):
            self.add_angle_element()
        while len(self.angle_boxes) > len(angles):
            self.remove_angle_element()
        self.refresh_angle_elements()
        
            
    def add_angle_element(self):
        index = len(self.angle_boxes)
        y_val = 70 + index * 20
        
        label = tkinter.Label(self,
                              text="Angle "+str(index+1)+":")
        label.place(x=20, y=y_val)
        
        a_box = tkinter.Entry(self, width=10, justify="center")
        a_box.place(x=100, y=y_val)
        a_box.delete(0, tkinter.END)
        a_box.insert(0, "0.0")
        a_box.config(state="disabled")
        
        self.angle_labels.append(label)
        self.angle_boxes.append(a_box)
    def remove_angle_element(self):
        self.angle_labels[-1].destroy()
        self.angle_labels = self.angle_labels[:-1]
        
        self.angle_boxes[-1].destroy()
        self.angle_boxes = self.angle_boxes[:-1]
Ejemplo n.º 15
0
def startQuest(parent):
    # field size selection
    frame_1 = Frame(parent)
    frame_1.config(padx=20, pady=10)
    frame_1.grid(row=0, column=0)
    label_1 = Label(frame_1, text='Choose field size')
    label_1.config(font='Times, 14')
    label_1.grid(row=0, column=0, columnspan=2)
    var_1 = IntVar()
    var_1.set(3)
    col_1 = 0
    for key in cells:
        rad = Radiobutton(frame_1, text=key,
                          variable=var_1, value=cells[key])
        rad.config(font='Times, 12')
        rad.grid(row=1, column=col_1)
        col_1 += 1
        
    # first turn selection
    frame_2 = Frame(parent)
    frame_2.config(padx=20, pady=10)
    frame_2.grid(row=1, column=0)
    label_2 = Label(frame_2, text='Who makes the first move?')
    label_2.config(font='Times, 14')
    label_2.grid(row=0, column=0, columnspan=2)
    var_2 = IntVar()
    var_2.set(0)
    col_2 = 0
    for key in first_move:
        f_movie = Radiobutton(frame_2, text=key, variable=var_2,
                              value=first_move[key])
        f_movie.config(font='Times, 12')
        f_movie.grid(row=1, column=col_2)
        col_2 += 1

    # choice of difficulty
    frame_3 = Frame(parent)
    frame_3.config(padx=20, pady=10)
    frame_3.grid(row=2, column=0)
    label_3 = Label(frame_3, text='Choose the difficulty of the game')
    label_3.config(font='Times, 14')
    label_3.grid(row=0, column=0, columnspan=2)
    var_3 = IntVar()
    var_3.set(0)
    col_3 = 0
    for key in difficulty:
        diff = Radiobutton(frame_3, text=key, variable=var_3,
                           value=difficulty[key])
        diff.config(font='Times, 12')
        diff.grid(row=1, column=col_3)
        col_3 += 1

    # data return button
    frame_4 = Frame(parent)
    frame_4.config(padx=20, pady=10)
    frame_4.grid(row=3, column=0)
    btn = Button(frame_4)
    btn = Button(frame_4, command=parent.destroy)
    btn.config(bg='silver', text='Accept',
               font='Times, 10')
    btn.grid(row=0, column=0)

    # focus on dialogue, waiting for the window to close
    parent.focus_set()
    parent.grab_set()
    parent.wait_window()
        
    # building a game array
    play_array = [[0 for x in range(var_1.get())]
                  for y in range(var_1.get())]

    answers.append(play_array)
    
    # choosing the first move randomly
    if var_2.get() == 2:
        f_move = random.choice([0, 1])
        print ('f_move', f_move)
        answers.append(f_move)
    else:
        answers.append(var_2.get())

    answers.append(var_3.get())

    return answers
Ejemplo n.º 16
0
    def main(self):
        # main frame
        self.root = Tk()
        self.root.geometry('500x450')
        self.root.title("Registration Form")

        # data binding
        self.USERNAME = StringVar(self.root)
        self.EMAIL = StringVar(self.root)
        self.PASSWORD = StringVar(self.root)
        self.GENDER = StringVar(self.root)
        self.UID = StringVar(self.root)

        # Registration form
        label_0 = Label(self.root,
                        text="Registration form",
                        width=20,
                        font=("bold", 20))
        label_0.place(x=90, y=53)

        # FullName label & entry
        label_1 = Label(self.root,
                        text="Username *",
                        width=20,
                        font=("bold", 10))
        label_1.place(x=80, y=130)
        entry_1 = Entry(self.root, textvariable=self.USERNAME)
        entry_1.place(x=240, y=130)

        # self.EMAIL label & entry
        label_2 = Label(self.root, text="Email *", width=20, font=("bold", 10))
        label_2.place(x=68, y=180)
        entry_2 = Entry(self.root, textvariable=self.EMAIL)
        entry_2.place(x=240, y=180)

        # self.PASSWORD label & entry
        label_2_ = Label(self.root,
                         text="Password *",
                         width=20,
                         font=("bold", 10))
        label_2_.place(x=68, y=230)
        entry_2_ = Entry(self.root, textvariable=self.PASSWORD, show="*")
        entry_2_.place(x=240, y=230)

        # self.GENDER label & radio-box
        label_3 = Label(self.root, text="Gender", width=20, font=("bold", 10))
        label_3.place(x=70, y=280)

        optionMale = Radiobutton(self.root,
                                 text="Male",
                                 padx=5,
                                 variable=self.GENDER,
                                 value=1)
        optionMale.place(x=235, y=280)
        optionFemale = Radiobutton(self.root,
                                   text="Female",
                                   padx=20,
                                   variable=self.GENDER,
                                   value=2)
        optionFemale.place(x=290, y=280)

        # Age label & entry
        label_4 = Label(self.root,
                        text="Student ID *",
                        width=20,
                        font=("bold", 10))
        label_4.place(x=70, y=330)
        entry_3 = Entry(self.root, textvariable=self.UID)
        entry_3.place(x=240, y=330)

        # Error label
        self.error_label = Label(self.root, width=60, font=("bold", 8))
        self.error_label.place(x=65, y=370)

        # Submit button
        btn = Button(self.root,
                     text='Submit',
                     width=20,
                     command=self.Register,
                     bg='brown',
                     fg='white')
        btn.place(x=180, y=400)

        # Login button
        btn_2 = Button(self.root,
                       text='Login',
                       width=10,
                       command=self.navigate_to_login,
                       bg='#0F0F0F',
                       fg='#33FF33',
                       borderwidth=0,
                       font="Verdana 10 underline")
        btn_2.place(x=350, y=400)

        # theme color hacker
        self.root.config(bg="#0F0F0F")
        label_0.config(bg="#0F0F0F", fg="#33FF33")
        label_1.config(bg="#0F0F0F", fg="#33FF33")
        label_2.config(bg="#0F0F0F", fg="#33FF33")
        label_2_.config(bg="#0F0F0F", fg="#33FF33")
        label_3.config(bg="#0F0F0F", fg="#33FF33")
        label_4.config(bg="#0F0F0F", fg="#33FF33")
        entry_1.config(bg="#0F0F0F", fg="#33FF33", insertbackground="#33FF33")
        entry_3.config(bg="#0F0F0F", fg="#33FF33", insertbackground="#33FF33")
        entry_2.config(bg="#0F0F0F", fg="#33FF33", insertbackground="#33FF33")
        entry_2_.config(bg="#0F0F0F", fg="#33FF33", insertbackground="#33FF33")
        optionFemale.config(bg="#0F0F0F", fg="#33FF33")
        optionMale.config(bg="#0F0F0F", fg="#33FF33")
        btn.config(bg="#0F0F0F",
                   fg="#FFFFFF",
                   activebackground="#0F0F0F",
                   activeforeground="#FFFFFF")
        self.error_label.config(bg="#0F0F0F")

        # it is use for display the registration form on the window
        self.root.mainloop()
        print("registration form  seccussfully created...")
Ejemplo n.º 17
0
class UserInterface:
    def promotionRadioBttnFalse(self, event):

        self.promotion = "false"
        #print("Promotion = ", self.promotion)

    def promotionRadioBttnTrue(self, event):

        self.promotion = "true"
        #print("Promotion = ", self.promotion)

    def startTheModelButton(self, event):

        self.stopEvent = threading.Event()
        self.thread1 = threading.Thread(target=self.startModel, args=())
        self.thread1.start()

    def shopID(self, shop):

        self.shop = shop
        #print("Shop Chosen = ", self.shop)

    def productID(self, product):

        self.product = product
        #print("Product Chosen = ", self.product)

    def __init__(self, master):

        ##-------------------------- Setting up the variables --------------------------##

        self.master = master

        self.thread1 = None
        self.stopEvent = None

        self.shop_dd_options = [
            "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"
        ]
        self.product_dd_options = [
            "108701", "99197", "103665", "105574", "106716", "114790",
            "115267", "115850", "116018", "119141"
        ]

        self.variable_shop = StringVar(self.master)
        self.variable_shop.set("Shop ID Drop Down")

        self.variable_product = StringVar(self.master)
        self.variable_product.set("Product ID Drop Down")

        self.shop_dd = OptionMenu(self.master,
                                  self.variable_shop,
                                  *self.shop_dd_options,
                                  command=self.shopID)

        self.product_dd = OptionMenu(self.master,
                                     self.variable_product,
                                     *self.product_dd_options,
                                     command=self.productID)

        self.mydate = StringVar(self.master)
        self.date = tk.Entry(self.master, textvariable=self.mydate, width=10)

        self.v = IntVar()
        self.onpromotion_false = Radiobutton(self.master,
                                             text="Promotion False",
                                             variable=self.v,
                                             value=0)
        self.onpromotion_true = Radiobutton(self.master,
                                            text="Promotion True",
                                            variable=self.v,
                                            value=1)

        self.output_quantity = Label(self.master, text="xxxx")
        self.shop_dd_label = Label(self.master,
                                   text="Please Select the Shop ID")
        self.product_dd_label = Label(self.master,
                                      text="Please Select the Product ID")
        self.date_dd_label = Label(self.master,
                                   text="Enter the Date : DD/MM/YYYY")
        self.output_dd_label = Label(self.master, text="Output Quantity is : ")

        self.name1 = Label(self.master, text="Shamsheer Verma : 12851248")
        self.name2 = Label(self.master, text="Ankit Kapoor : 12982233")
        self.name3 = Label(self.master, text="Avinash Pakanati: 12723514")

        self.start = Button(self.master,
                            text="START THE MODEL",
                            bg='white',
                            fg='black')

        ##-------------------------- Positioning the Drop Down, Input Box, RadioButtons, and Output --------------------------##

        self.onpromotion_false.config(height=1, width=28)
        self.onpromotion_true.config(height=1, width=25)
        self.shop_dd.config(height=1, width=20)
        self.product_dd.config(height=1, width=20)
        self.output_quantity.config(height=1, width=20)
        self.start.config(height=1, width=20)
        self.shop_dd_label.config(height=1, width=30)
        self.product_dd_label.config(height=1, width=30)
        self.date_dd_label.config(height=1, width=30)
        self.output_dd_label.config(height=1, width=20)
        self.name1.config(height=1, width=30)
        self.name2.config(height=1, width=30)
        self.name3.config(height=1, width=30)

        self.onpromotion_false.grid(row=1, column=0, sticky=W, pady=2)
        self.onpromotion_true.grid(row=1, column=1, sticky=E, pady=2)
        self.shop_dd.grid(row=2, column=1, sticky=E, pady=2)
        self.product_dd.grid(row=3, column=1, sticky=E, pady=2)
        self.date.grid(row=4, column=1, sticky=N, pady=2)
        self.output_quantity.grid(row=5, column=1, sticky=N, pady=2)
        self.shop_dd_label.grid(row=2, column=0, sticky=N, pady=2)
        self.product_dd_label.grid(row=3, column=0, sticky=N, pady=2)
        self.date_dd_label.grid(row=4, column=0, sticky=N, pady=2)
        self.output_dd_label.grid(row=5, column=0, sticky=N, pady=2)
        self.start.grid(row=6, column=0, sticky=N, pady=2, columnspan=2)
        self.name1.grid(row=9, column=0, sticky=S, pady=2)
        self.name2.grid(row=10, column=0, sticky=S, pady=2)
        self.name3.grid(row=11, column=0, sticky=S, pady=2)
        self.name1.place(x=1, y=240)
        self.name2.place(x=1, y=260)
        self.name3.place(x=1, y=280)

        self.uts_photo = PhotoImage(file="uts_logo_new.png")
        self.uts_logo = Label(self.master, image=self.uts_photo)
        self.uts_logo.image = self.uts_photo
        self.uts_logo.grid(row=8, column=0, sticky=N, pady=2, columnspan=2)
        self.uts_logo.place(x=270, y=240)

        self.start.bind("<Button-1>", self.startTheModelButton)
        self.onpromotion_false.bind("<Button-1>", self.promotionRadioBttnFalse)
        self.onpromotion_true.bind("<Button-1>", self.promotionRadioBttnTrue)

    ##-----------------------------Starting the Model - Machine Learning Algorithms - Over Here----------------------------##

    def sqlConnection(self):

        self.conn = pg.connect(host='localhost',
                               user="",
                               password="",
                               database="BIDS_Assignment_5")
        self.cur = self.conn.cursor()
        self.cur.execute("SELECT * FROM corporacion WHERE item_nbr = " +
                         self.product)

        self.colnames = [desc[0] for desc in self.cur.description]
        self.rows = self.cur.fetchall()

        self.subset = pd.DataFrame(self.rows)

        self.conn.close()

        self.subset.columns = self.colnames
        print(self.subset)
        print("done")

        self.subset.replace(to_replace="false", value=0, regex=True)
        self.subset.replace(to_replace="true", value=1, regex=True)

        self.subset.dropna(inplace=True, axis=0, how='any')

        self.current_year = now.year
        self.current_month = now.month
        self.current_day = now.day

        self.subset['date'] = pd.to_datetime(
            self.subset['date'], format='%Y-%m-%d')  #transforming date Column
        self.subset_year = self.subset['date'].dt.year
        self.subset_month = self.subset['date'].dt.month
        self.subset_day = self.subset['date'].dt.day
        self.subset['Duration'] = (
            (self.current_year * 365) +
            (self.current_month * 30) + self.current_day) - (
                (self.subset_year * 365) +
                (self.subset_month * 30) + self.subset_day)
        self.subset.drop('date', axis=1, inplace=True)
        self.randomForests()

    def randomForests(self):

        self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(
            self.subset.drop(['id', 'unit_sales'], axis=1),
            self.subset['unit_sales'],
            test_size=0.3)

        self.lm = RandomForestRegressor(n_estimators=20)
        self.lm.fit(self.X_train, self.y_train)

        if self.promotion == 'true':
            self.promotiontf = 1
        else:
            self.promotiontf = 0

        #self.date = str(self.date)
        #print(datetime.now().date())
        #print(self.date)

        #print(self.date_input)
        self.rdate1 = datetime.strptime(self.date_input, "%Y%m%d").date()

        #print(self.rdate1)
        #self.rdate1 = strftime("%Y-%m-%d %H:%M:%S", str(self.date))
        self.duration = (datetime.now().date() - self.rdate1).days
        print(self.duration)
        self.mylist = {
            "date": self.duration,
            "store_nbr": self.shop,
            "item_nbr": self.product,
            "onpromotion": self.promotiontf
        }
        print(self.mylist)
        self.output_df = pd.DataFrame(self.mylist, index=[0])
        self.lm_predict = self.lm.predict(self.output_df)
        np.round(self.lm_predict, 0)
        self.output_quantity['text'] = self.lm_predict

    def startModel(self):

        self.date_input = str(eval(self.date.get()))

        print("clicking the button")
        print("Shop Number", self.shop)
        print("Product Number", self.product)
        print("Promotion True or False", self.promotion)
        print("Date", self.date_input)
        self.sqlConnection()