Ejemplo n.º 1
0
    def __create_plot(self):
        # Create Border
        plot_frame = Frame(self.__master,
                           borderwidth=1,
                           highlightbackground="Black")
        plot_frame.configure(background="Black")

        # Create Canvas
        plot = Canvas(plot_frame,
                      width=self.__PLOT_WIDTH,
                      height=self.__PLOT_HEIGHT,
                      background="White")

        # Draw Axes
        middle_x = self.__PLOT_WIDTH / 2
        middle_y = self.__PLOT_HEIGHT / 2
        plot.create_line(middle_x, 0, middle_x, self.__PLOT_HEIGHT, fill="Black", width=3)
        plot.create_line(0, middle_y, self.__PLOT_WIDTH, middle_y, fill="Black", width=3)

        # Draw Grid Points
        for center_x in range(self.__gap_x, self.__PLOT_WIDTH, self.__gap_x):
            for center_y in range(self.__gap_y, self.__PLOT_HEIGHT, self.__gap_y):
                size = 3
                plot.create_line(center_x, center_y - size, center_x, center_y + size + 1, fill="Black", width=1)
                plot.create_line(center_x - size, center_y, center_x + size + 1, center_y, fill="Black", width=1)

        # Finish Plot Creation
        plot.pack()
        plot_frame.pack()
        return plot
Ejemplo n.º 2
0
    def __init__(self, root, x, y, name, config, remote_control):
        super().__init__(root, x, y, name)

        remote = remote_control

        frame = Frame(root, bg=remote["color"], width=remote["width"], height=remote["height"])
        frame.place(x=x, y=y)

        self._config = config
        self._key_codes = []
        self._pressed_key_codes = []

        for i in range(0, len(remote["key_rows"])):
            row = remote["key_rows"][i]
            for j in range(0, len(row["buttons"])):
                button_setup = row["buttons"][j]
                if button_setup != None:
                    code = button_setup.get("code", "KEY_" + button_setup["name"])
                    self._key_codes.append(code)

                    command = partial(self._key_press, code)

                    button = Button(frame, text=button_setup["name"],
                                    width=remote["key_width"], height=remote["key_height"],
                                    command=command,
                                    justify=CENTER, highlightbackground=remote["color"])
                    button.grid(row=i, column=j, padx=8, pady=8)

        frame.configure(width=remote["width"], height=remote["height"])
Ejemplo n.º 3
0
    def __init__(self, master, async_loop):
        Frame.__init__(self, master)
        self.async_loop = async_loop
        Frame.configure(self)
        self.master = master
        self.master.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.file_widgets = []
        self.current_row = 3
        self.client = None

        menu = Menu(self)
        # menu.add_command(label='Upload to server', command=self.load_to_serv)
        self.master.config(menu=menu)

        from frames.StartPage import ADR_SRC
        from frames.StartPage import ADR_DEST
        info = "Sender Address: " + str(ADR_SRC) + "\tDestination Address: " + str(ADR_DEST)
        Label(self, text=info).grid(row=1, column=1)

        do_ip_callback = functools.partial(do_ip_package, "First_package", ADR_SRC, ADR_DEST)
        Button(self, text="Do IP Package", command=do_ip_callback).grid(row=1, column=2)

        try:
            a = 0
            # self.client = Client(ADR_SRC, ADR_DEST)
            # files = self.client.get_name_files()
        except Exception as e:
            ft_error(e)
Ejemplo n.º 4
0
    def __init__(self, master, async_loop):
        Frame.__init__(self, master)
        self.async_loop = async_loop
        Frame.configure(self)
        self.master = master
        self.master.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.file_widgets = []
        self.current_row = 3
        self.client = None

        menu = Menu(self)
        menu.add_command(label='Upload to server', command=self.load_to_serv)
        self.master.config(menu=menu)

        from frames.StartPage import TCP_IP
        from frames.StartPage import TCP_PORT
        info = "IP: " + str(TCP_IP) + "\tPORT: " + str(TCP_PORT)
        Label(self, text=info).grid(row=1, column=1)
        Button(self, text="Disconnect", command=self.disconnect).grid(row=1,
                                                                      column=2)
        Button(self, text="Upload to server",
               command=self.load_to_serv).grid(row=2, column=1)
        try:
            self.client = Client(TCP_IP, TCP_PORT)
            files = self.client.get_name_files()
            self.add_file_rows_to_root(files)
        except ConnectionRefusedError:
            raise ConnectionRefusedError
        except ConnectionResetError:
            ft_error("Server died :c")
            self.disconnect()
        except Exception as e:
            ft_error(e)
Ejemplo n.º 5
0
    def __init__(self, master, async_loop):
        Frame.__init__(self, master)
        self.async_loop = async_loop
        Frame.configure(self)
        self.master = master
        self.master.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.file_widgets = []
        self.current_row = 3
        self.client = None

        from FTP_client.frames.StartPage import FTP_MIRROR
        info = "MIRROR: " + str(FTP_MIRROR)
        self.info_label = Label(self, text=info).grid(row=1, column=1)
        self.btn_disconnect = Button(self,
                                     text="Disconnect",
                                     command=self.disconnect).grid(row=1,
                                                                   column=2)

        from FTP_client.frames.StartPage import FTP_MIRROR
        self.client = Client(FTP_MIRROR)

        t1 = threading.Thread(target=self.client.connect)
        t1.start()
        t_progr = threading.Thread(target=self.progress, args=(3, t1)).start()
        ft_done("login is successful")

        t2 = threading.Thread(target=self.connect)
        t2.start()
        t_progr = threading.Thread(target=self.progress, args=(1, t2)).start()
Ejemplo n.º 6
0
    def __init__(self, master, async_loop):
        Frame.__init__(self, master)
        self.async_loop = async_loop
        Frame.configure(self)
        self.master = master
        self.master.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.msg_widgets = []
        self.current_row = 3
        self.client = None
        self.btn_back = None
        self.msgs: list = None
        self.labels = []

        from POP3.frames.StartPage import POP3_ADDRESS
        info = "Email Address: " + str(POP3_ADDRESS)
        self.info_label = Label(self, text=info).grid(row=1, column=2)
        self.btn_disconnect = Button(self,
                                     text="Log Out",
                                     command=self.disconnect).grid(row=1,
                                                                   column=1)
        self.add_label("Date", 2, 1)
        self.add_label("From", 2, 2)
        self.add_label("To", 2, 3)
        self.add_label("Subject", 2, 4)

        self.client = Client(POP3_ADDRESS)

        t1 = threading.Thread(target=self.client.connect)
        t1.start()
        t_progr = threading.Thread(target=self.progress, args=(3, t1)).start()
        ft_done("login is successful")

        t2 = threading.Thread(target=self.connect)
        t2.start()
        t_progr = threading.Thread(target=self.progress, args=(1, t2)).start()
Ejemplo n.º 7
0
    def aviso_aguarde_instalando(self, recente):
        """ Realizando a atualização """

        if self.tp_atualizacao is not None:
            self.tp_atualizacao.destroy()

        self.tp_atualizacao = Toplevel(None)
        self.tp_atualizacao.withdraw()
        self.tp_atualizacao.focus_force()
        self.tp_atualizacao.resizable(False, False)
        self.tp_atualizacao.tk.call('wm', 'iconphoto', self.tp_atualizacao._w,
                                    self.icon)
        self.tp_atualizacao.configure(
            self.design.dic["aviso_versao_top_level"])
        self.tp_atualizacao.grid_columnconfigure(1, weight=1)
        self.tp_atualizacao.title('Atualizando.... Não feche a Safira!')

        #try:
        #    self.tp_atualizacao.wm_attributes('-type', 'splash')
        #except Exception as erro:
        #    print("Erro ao remover barra de titulos => ", erro)

        fr_atualizaca = Frame(self.tp_atualizacao)
        lb_versao_dev = Label(fr_atualizaca,
                              text='{:^30}'.format('Aguarde Atualizando!'))
        lb_versao_tex = Message(fr_atualizaca, text=' ' * 50, width=200)
        fr_botoes = Frame(fr_atualizaca)
        bt_atualiza = Button(fr_botoes)

        fr_atualizaca.configure(self.design.dic["aviso_versao_fr_atualizacao"])
        lb_versao_dev.configure(self.design.dic["aviso_versao_lb_dev"])
        lb_versao_tex.configure(self.design.dic["aviso_versao_ms"])
        fr_botoes.configure(self.design.dic["aviso_versao_btn"])
        bt_atualiza.configure(self.design.dic["aviso_versao_btn_atualiza"],
                              relief=FLAT)

        fr_atualizaca.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(1, weight=1)
        fr_botoes.grid_columnconfigure(2, weight=1)
        fr_atualizaca.grid(row=1, column=1, sticky=NSEW)
        lb_versao_dev.grid(row=1, column=1)
        lb_versao_tex.grid(row=2, column=1, sticky=NSEW)
        fr_botoes.grid(row=3, column=1, sticky=NSEW)

        j_width = self.tp_atualizacao.winfo_reqwidth()
        j_height = self.tp_atualizacao.winfo_reqheight()
        t_width = self.tela.winfo_screenwidth()
        t_heigth = self.tela.winfo_screenheight()

        self.tp_atualizacao.geometry("+{}+{}".format(
            int(t_width / 2) - int(j_width / 2),
            int(t_heigth / 2) - int(j_height / 2)))
        self.tp_atualizacao.deiconify()
        self.tp_atualizacao.update()

        th = Thread(
            target=lambda ver=recente, lb=lb_versao_tex, bt_at=bt_atualiza,
            lb_2=lb_versao_dev: self.aplica_versao(ver, lb, bt_at, lb_2))
        th.start()
Ejemplo n.º 8
0
class findU(GUI):
    def __init__(self, parent, master):
        self.root = master
        Tk().withdraw()
        self.parent = parent

    def close(self):
        self.root.quit()
        self.root.destroy()

    def choose(self, u=None):
        self.parent.chosen_user = u
        self.close()

    def main(self, su):
        def gn(l):  # get "surname name" from list of data
            return l[2] + ' ' + l[1]

        self.basic = Frame(self.root)
        self.basic.grid()
        self.basic.configure(bg=bgcolor5)

        self.fr = Frame(self.basic)
        self.fr.grid(row=0, column=0, sticky='W')
        self.fr.configure(bg=bgcolor5)

        nadpis = Label(self.fr,
                       text=u"VYBER Z�KAZN�KA",
                       width=20,
                       justify='center',
                       bg=bgcolor5)
        nadpis.grid(row=1, column=1)

        buttons = []

        sortkeys = sorted(su, key=lambda x: ' '.join(su.get(x)[2::-1]))

        for k in sortkeys:  # !!!!!!
            txt = ', '.join([k] + [gn(su[k])] + su[k][3:5])
            buttons.append(
                Button(self.fr,
                       text=txt,
                       width=65,
                       justify='left',
                       bd=2,
                       bg=buttoncolor4,
                       command=lambda u=k: self.choose(u)))
            buttons[-1].grid(row=len(buttons) + 2, column=1)

        self.butcanc = Button(self.fr,
                              text=u"Zru�i�",
                              width=20,
                              justify='center',
                              bd=2,
                              bg=buttoncolor5,
                              command=self.close)
        self.butcanc.grid(row=len(su) + 4, column=1)
Ejemplo n.º 9
0
class PianoApp(object):
    def __init__(self, parent, text_path='welcome.txt'):
        self.root = parent
        self.root.title("Piano Player")
        w, h = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
        self.root.geometry("{0}x{1}+0+0".format(w, h))
        self.root.configure(bg='dim grey')
        self.frame = Frame(parent)
        self.frame.configure(bg='dim grey')
        self.frame.pack()

        with open(text_path, 'r') as file:
            text = file.read()

        label = Label(self.frame,
                      text=text,
                      bg='dim grey',
                      font=('Trattatello', 30),
                      pady=15)
        label.pack()

        play_button = HoverButton(self.frame,
                                  text="PLAY",
                                  highlightbackground='dim grey',
                                  activeforeground='light grey',
                                  height=h // 220,
                                  width=w // 40,
                                  fg='brown4',
                                  font=('Trattatello', 40),
                                  pady=10,
                                  padx=10,
                                  command=self.open_frame)
        play_button.pack()

        exit_button = HoverButton(self.frame,
                                  text="EXIT",
                                  highlightbackground='dim grey',
                                  activeforeground='light grey',
                                  height=h // 220,
                                  width=w // 40,
                                  fg='brown4',
                                  font=('Trattatello', 40),
                                  pady=10,
                                  padx=10,
                                  command=self.root.quit)
        exit_button.pack()

    def hide(self):
        self.root.withdraw()

    def open_frame(self):
        self.hide()
        play_frame = PlayFrame(self)

    def show(self):
        self.root.update()
        self.root.deiconify()
def createMainMenuGUI():

    #set as global variables
    global win
    global frame

    #if frame currently being shown in win- destroy it. clears window
    if (frame != None):
        frame.destroy()

    #create new frame object
    frame = Frame(win)
    frame.configure(background='lawn green')

    lab1 = Label(frame,
                 text="Combustion of Hydrocarbon",
                 fg="black",
                 bg="lawn green",
                 font=("Comic Sans MS", 20))
    lab1.grid(
        padx=5,
        column=2,
    )

    #create button
    btnStart = Button(frame,
                      text="Start",
                      command=createSelectGUI,
                      height=5,
                      width=30,
                      fg="black",
                      bg="lime green",
                      font=("Comic Sans MS", 10))
    btnStart.grid(column=3, padx=3, pady=5)

    btnUpdate = Button(frame,
                       text="Update",
                       command=loginGUI,
                       height=5,
                       width=30,
                       fg="black",
                       bg="lime green",
                       font=("Comic Sans MS", 10))
    btnUpdate.grid(column=3, pady=5)

    btnInstruction = Button(frame,
                            text="?",
                            command=instructionGUI,
                            height=2,
                            width=10,
                            fg="black",
                            bg="lime green",
                            font=("Comic Sans MS", 10))
    btnInstruction.grid(column=5, pady=20)

    frame.grid()
Ejemplo n.º 11
0
 def getView(self, window):
     view = Frame(window)
     view.configure(background='#0049ba')
     Label(view, width = 60, text=self.question, bg="#77abfc").grid(row = 1, column = 1, columnspan = 2)
     Button(view, width = 25, text=self.answers[0], activebackground="white", bg="#77abfc", command=lambda *args: self.check("A", view)).grid(row = 2, column = 1, padx=15, pady=15)
     Button(view, width = 25, text=self.answers[1], activebackground="white", bg="#77abfc", command=lambda *args: self.check("B", view)).grid(row = 2, column = 2, padx=15, pady=15)
     Button(view, width = 25, text=self.answers[2], activebackground="white", bg="#77abfc", command=lambda *args: self.check("C", view)).grid(row = 3, column = 1)
     Button(view, width = 25, text=self.answers[3], activebackground="white", bg="#77abfc", command=lambda *args: self.check("D", view)).grid(row = 3, column = 2)
     Label(view, width = 60, text="", bg="#77abfc",).grid(row = 4, column = 1, columnspan = 2, padx=20, pady=20)
     return view
Ejemplo n.º 12
0
    def make_widgets(self):

        self.label = Label(
            self, text="TTS-Prefetch", font=Font(size=14, weight="bold")
        )
        self.label.pack()

        leftpane = Frame(self)
        leftpane.configure(bg="black")

        homedir = os.path.expanduser("~")
        self.settings = EntryFrame(
            leftpane,
            (
                "infile",
                FileEntry,
                dict(
                    label="Input file",
                    initialdir=libtts.GAMEDATA_DEFAULT,
                    filetypes=[("JSON-file", "*.json")],
                    action="open",
                    default=self.args.infile,
                ),
            ),
            (
                "gamedata",
                DirEntry,
                dict(
                    label="Gamedata path",
                    default=libtts.GAMEDATA_DEFAULT,
                    initialdir=homedir,
                    mustexist=True,
                ),
            ),
            ("dry_run", ToggleEntry, dict(label="Dry run")),
            ("refetch", ToggleEntry, dict(label="Refetch")),
            ("relax", ToggleEntry, dict(label="Relax")),
            ("user_agent", TextEntry, dict(label="User-agent")),
            text="Settings",
            width=60,
        )
        self.settings.pack(fill=X)

        control = LabelFrame(leftpane, text="Control")
        self.buttons = ButtonFrame(control, "Run", "Stop", "Quit")
        self.buttons.pack()
        self.buttons.on("Run", self.run)
        self.buttons.on("Stop", self.stop)
        self.buttons.on("Quit", self.quit)
        control.pack(fill=X)

        leftpane.pack(side=LEFT, anchor=N)

        self.output = OutputFrame(self, text="Output")
        self.output.pack(expand=True, fill=BOTH)
Ejemplo n.º 13
0
    def __init__(self):
        super().__init__()

        # ______________________________________________________________________________________________________________
        # Rodapé
        bottom = Frame(self, height=20);
        bottom.pack(side="bottom", fill="x")
        bottom.configure(relief="groove", border=3)
        self.l_footer = StringVar()
        footer = Label(bottom, textvariable=self.l_footer)
        footer.pack(side="left")
def forg():
    Form1 = Frame(t, relief=RIDGE)
    Form1.place(x=450, y=200)
    Form1.configure(bg='white', bd=1)
    Label(Form1,
          text='forgot your password',
          bg='black',
          fg='#efe6e6',
          bd=8,
          width='20').grid(row=0, column=0, ipady=6, sticky='new')
    l3 = Label(Form1,
               text='PLEASE ENTER YOUR RECOVERY\n MOBILE NUMBER',
               bg='#f5f5f5',
               bd=8,
               width='20')
    l3.grid(row=1, column=0, ipady=6, sticky='new')
    rpwd = Entry(Form1, cursor='"xterm"', fg='grey', bg='#f5f5f5')
    rpwd.grid(row=2, column=0, padx=15 + 20, pady=20 - 6, ipady=6)
    rpwd.config(width='35', bd=2)
    rpwd.insert(0, 'Enter your Number Here')
    rpwd.bind('<FocusIn>', lambda event, ag=rpwd: click(event, ag))
    rpwd.bind('<FocusOut>',
              lambda event, ag=rpwd: out(event, ag, "Enter your Number Here"))

    def fpwd():
        if (len(rpwd.get()) == 10 and (rpwd.get()).isdigit() == True):
            c.execute('select mobile from user where mobile=?', (rpwd.get(), ))
            s = c.fetchall()
            if len(s) != 0:
                for i in s:
                    print(i)
                    if str(rpwd.get()) in i:
                        print('hi')
                        messagebox.showerror('Hello',
                                             'Sorry we r unable to find you!')
                    else:
                        rpw = ''
                        c.execute('select Name from user where mobile=?',
                                  (rpwd.get(), ))
                        for i in c.fetchall():
                            for j in i:
                                rpw = j
                        Form1.destroy()
                        modpwd(rpw)
            else:
                messagebox.showerror('Error', 'INVALID MOBILE NUMBER')
        else:
            messagebox.showerror(
                'Error', 'PLease enter your correct 10 digit mobile number')

    Button(Form1, text='VALIDATE', command=fpwd, bg='black',
           fg='#efe6e6').grid(row=3, columnspan=1, pady=14)
Ejemplo n.º 15
0
 def CreateHighlight(self, fwParent, fnImage, ixRow, ixCol):
     psWidth = self.psIconWidth + (2 * self.psBorder)
     psHeight = self.psIconHeight + (2 * self.psBorder)
     fwHilit = Frame(fwParent,
                     borderwidth=0,
                     width=psWidth,
                     height=psHeight)
     if fnImage == self.svPicked.get():
         fwHilit.configure(background=HIGHLIGHT_COL)
     fwHilit.grid(row=(ixRow * 3), column=(ixCol * 2))
     fwHilit.bind("<Button-1>",
                  lambda event, a=fnImage: self.ClickedIcon(a))
     return fwHilit
Ejemplo n.º 16
0
 def textAndInput(self, text, row):
     frame = Frame(self)
     frame.configure(background=window_bg)
     label = createLabel(frame)
     setStyleText(label, text)
     vcmd = (self.register(self.validateInput))
     inputText = Entry(frame, 
         validate='all', 
         validatecommand=(vcmd, '%P'))
     inputText.grid(row=1, column=0)
     label.grid(row=0, column=0, padx=(0, 20), sticky="nw")
     frame.grid(row = row, column= 0, padx=(20, 0), sticky="nw")
     self.inputs.append(inputText)
Ejemplo n.º 17
0
 def display_chat_entry_box(self):
     frame = Frame()
     Label(frame, text='Enter message:',
           font=("Serif", 12)).pack(side='top', anchor='w')
     self.enter_text_widget = Text(frame,
                                   width=60,
                                   height=3,
                                   font=("Serif", 12))
     self.enter_text_widget.pack(side='left', pady=10)
     self.enter_text_widget.bind(
         '<Return>', self.on_enter_key_pressed)  #call on_enter_key_pressed
     frame.pack(side='top')
     frame.configure(bg="bisque2")
Ejemplo n.º 18
0
class ColorRow(ttk.Frame):
    def __init__(self, master, color, style):
        super().__init__(master, padding=(5, 2))
        self.colorname = color
        self.style = style

        self.label = ttk.Label(self, text=color, width=12)
        self.label.pack(side=LEFT)
        self.patch = Frame(master=self,
                           background=self.style.colors.get(color),
                           width=15)
        self.patch.pack(side=LEFT, fill=BOTH, padx=2)
        self.entry = ttk.Entry(self, width=12)
        self.entry.pack(side=LEFT, fill=X, expand=YES)
        self.entry.bind("<FocusOut>", self.enter_color)
        self.color_picker = ttk.Button(
            master=self,
            text="...",
            bootstyle=SECONDARY,
            command=self.pick_color,
        )
        self.color_picker.pack(side=LEFT, padx=2)

        # set initial color value and patch color
        self.color_value = self.style.colors.get(color)
        self.update_patch_color()

    def pick_color(self):
        """Callback for when a color is selected from the color chooser"""
        color = askcolor(color=self.color_value)
        if color[1]:
            self.color_value = color[1]
            self.update_patch_color()
        self.event_generate("<<ColorSelected>>")

    def enter_color(self, *_):
        """Callback for when a color is typed into the entry"""
        try:
            self.color_value = self.entry.get().lower()
            self.update_patch_color()
        except:
            self.color_value = self.style.colors.get(self.label["text"])
            self.update_patch_color()
        self.event_generate("<<ColorSelected>>")

    def update_patch_color(self):
        """Update the color patch frame with the color value stored in
        the entry widget."""
        self.entry.delete(0, END)
        self.entry.insert(END, self.color_value)
        self.patch.configure(background=self.color_value)
Ejemplo n.º 19
0
def additems(i, doreturn=False, bgcolor="#555"):
	returnable = []
	for item in i:
		global totalitems
		totalitems += 1
		ff = Frame(f, bg=bgcolor)
		item.body = item.author.name + ' || ' + item.fullname + '\n' + item.body
		item.body = str(totalitems) + '\n' + item.body
		ibody = item.body.replace('\n\n', '\n')
		ifinal = ''
		for paragraph in ibody.split('\n'):
			ifinal += '\n'.join(textwrap.wrap(paragraph))
			ifinal += '\n'  
	
		item.body = ifinal
		ww = 680
		wh = 10 
		wx = 20
		wy = 20 
		#print(ww, wh, wx, wy)
		ff.ww = ww
		ff.wh = wh
		ff.wx = wx
		ff.wy = wy
		ff.body = item.body
		ff.sourceitem = item
		ff.configure(width=ww, height=wh)
		ff.place(x=wx, y=wy)
		ff.bind("<B1-Motion>", framedrag)
		ff.bind("<ButtonRelease-1>", resetdrag)
		ff.pack_propagate(0)
		l = Label(ff, text=item.body, bg="#777")
		l.place(x=10,y=10)
		rt = Text(ff, width= 15, height= (len(ifinal.split('\n'))) - 2)
		rt.sourceitem = item
		rt.place(x=400,y=10)
		rb = Button(ff, text="Reply", command= lambda rep=rt: reply(rep))
		rb.place(x=400,y=wh-20)
		ff.rt = rt
		ff.rb = rb
		if not doreturn:
			widgets.append(ff)
		else:
			returnable.append(ff)
	if doreturn:
		return returnable
	else:
		refreshscreen()
def modpwd(o):
    Form2 = Frame(t, relief=RIDGE)
    Form2.place(x=450, y=200)
    Form2.configure(bg='white', bd=1)
    Label(Form2,
          text='Enter your Password',
          bg='black',
          fg='#efe6e6',
          bd=8,
          font='Algerian 25 bold',
          width='20').grid(row=0, column=0, ipady=6, sticky='new')
    Label(Form2, text='Hello ' + o + '!', bg='white', bd=8,
          width='20').grid(row=1, column=0, ipady=6, sticky='new')
    e7 = Entry(Form2, cursor='"xterm"', fg='grey', bg='#f5f5f5')
    e8 = Entry(Form2, fg='grey', cursor='"xterm"', bg='#f5f5f5')
    e7.config(width='35', bd=2)
    e8.config(width='35', bd=2)
    e7.grid(row=2, column=0, padx=15 + 20, pady=20 - 6, ipady=6)
    e8.grid(row=3, column=0, padx=15 + 20, pady=20 - 6, ipady=6)
    e7.insert(0, 'Enter your password')
    e8.insert(0, 'Confirm Password')
    e7.bind('<FocusIn>', lambda event, ag=e7: clickpwd(event, ag))
    e7.bind('<FocusOut>',
            lambda event, ag=e7: out(event, ag, "Enter your password"))
    e8.bind('<FocusIn>', lambda event, ag=e8: clickpwd(event, ag))
    e8.bind('<FocusOut>',
            lambda event, ag=e8: out(event, ag, " Confirm Password"))

    def rpp():
        r = 0
        if (match(r'[A-Za-z0-9!@#$%&*_]', e7.get())):
            r = 1
        if (6 < len(e7.get()) < 12 and e7.get() == e8.get() and r == 1):
            c.execute('update user set password=? where name=?', (e7.get(), o))
            conn.commit()
            messagebox.showinfo(
                "STATUS",
                "PASSWORD CHANGED SUCCESSFULLY\nPLEASE LOGIN TO CONTINUE")
            Form2.destroy()
            logpage()
        else:
            messagebox.showerror('error', 'PLease check the Password ')
            e7.delete(0, END)
            e8.delete(0, END)
            e7.focus()

    Button(Form2, text='CONTINUE', command=rpp, bg='black',
           fg='#efe6e6').grid(row=4, columnspan=1, pady=14)
Ejemplo n.º 21
0
 def configure(self, **kwargs) -> None:
     # intercept configure commands
     kw = dict()
     bg = kwargs.get('background', kwargs.get('bg'))
     if bg:
         # get requested background
         kw['bg'] = self.__BG = bg
     cur = kwargs.get('cursor')
     if cur:
         # get requested cursor
         kw['cursor'] = self.__CURSOR = cur
     if kw:
         # update config for sub-widgets
         self.container.configure(**kw)
         self.scroll_canvas.configure(**kw)
     # update config for main widget
     Frame.configure(self, **kwargs)
Ejemplo n.º 22
0
 def display_chat_box(self):
     frame = Frame()  #frame to hold the corresponding elements
     Label(frame, text='Chat Box:', font=("Serif", 12)).pack(side='top',
                                                             anchor='w')
     self.chat_transcript_area = Text(frame,
                                      width=60,
                                      height=6,
                                      font=("Serif", 12))
     scrollbar = Scrollbar(frame,
                           command=self.chat_transcript_area.yview,
                           orient=VERTICAL)
     self.chat_transcript_area.config(yscrollcommand=scrollbar.set)
     self.chat_transcript_area.bind('<KeyPress>', lambda e: 'break')
     self.chat_transcript_area.pack(side='left', padx=10)
     scrollbar.pack(side='right', fill='y')
     frame.pack(side='top')
     frame.configure(bg="sandy brown")  #provide background color
Ejemplo n.º 23
0
 def updateList(self, frm: Frame, sbox: Spinbox, btn: bool = False) -> None:
     # get data
     start = frm.grid_info()['row']
     oldInfo = self.data.pop(zerofrmt(start))
     # get spinbox value
     moveToLbl = str(sbox.get())
     if moveToLbl == zerofrmt(start):
         return
     elif not moveToLbl:
         if start < self.lblRow:
             start = (self.lblRow + 1)
             moveToLbl = zerofrmt(self.lastRow)
             self.focus_set()
         else:
             return
     elif btn and int(moveToLbl) == self.lblRow:
         sbox.delete(0, 'end')
         start = (self.lblRow + 1)
         moveToLbl = zerofrmt(self.lastRow)
         self.after(0, self.focus_set)
     elif btn and abs(start - int(moveToLbl)) > 1:
         self.moveInterim(start, zerofrmt(self.lblRow + 1), True)
         start = 0
         moveToLbl = zerofrmt(self.maxRow)
         sbox.delete(0, 'end')
         sbox.insert(0, moveToLbl)
     elif not btn:
         if len(moveToLbl) != rndto:
             moveToLbl = zerofrmt(moveToLbl)
             sbox.delete(0, 'end')
             sbox.insert(0, moveToLbl)
         if start == self.lastRow:
             self.moveInterim(start, zerofrmt(self.lblRow + 1), True)
     sbox.selection_range(0, 'end')
     if moveToLbl == zerofrmt(start):
         return
     if moveToLbl in self.data:
         self.moveInterim(start, moveToLbl, False)
     moveToRow = int(moveToLbl)
     bg = self.litBg if (moveToRow % 2) else self.defBg
     frm.grid(row=moveToRow)
     frm.configure(bg=bg)
     sbox.configure(bg=bg)
     oldInfo['lbl'].configure(bg=bg)
     self.data[moveToLbl] = oldInfo
Ejemplo n.º 24
0
    def configure(self, cnf={}, **kw):
        """
        Configure this widget.  Use ``label_*`` to configure all
        labels; and ``listbox_*`` to configure all listboxes.  E.g.:

                >>> mlb = MultiListbox(master, 5)
                >>> mlb.configure(label_foreground='red')
                >>> mlb.configure(listbox_foreground='red')
        """
        cnf = dict(list(cnf.items()) + list(kw.items()))
        for (key, val) in list(cnf.items()):
            if key.startswith('label_') or key.startswith('label-'):
                for label in self._labels:
                    label.configure({key[6:]: val})
            elif key.startswith('listbox_') or key.startswith('listbox-'):
                for listbox in self._listboxes:
                    listbox.configure({key[8:]: val})
            else:
                Frame.configure(self, {key:val})
Ejemplo n.º 25
0
    def configure(self, cnf={}, **kw):
        """
        Configure this widget.  Use ``label_*`` to configure all
        labels; and ``listbox_*`` to configure all listboxes.  E.g.:

                >>> mlb = MultiListbox(master, 5)
                >>> mlb.configure(label_foreground='red')
                >>> mlb.configure(listbox_foreground='red')
        """
        cnf = dict(list(cnf.items()) + list(kw.items()))
        for (key, val) in list(cnf.items()):
            if key.startswith('label_') or key.startswith('label-'):
                for label in self._labels:
                    label.configure({key[6:]: val})
            elif key.startswith('listbox_') or key.startswith('listbox-'):
                for listbox in self._listboxes:
                    listbox.configure({key[8:]: val})
            else:
                Frame.configure(self, {key: val})
Ejemplo n.º 26
0
def create_voting_screen(player_names,
                         vote_function,
                         player_message="Time to vote"):
    '''Creates a window in which the player can vote'''
    player_window = Tk()
    width_value = player_window.winfo_screenwidth()
    height_value = player_window.winfo_screenheight()
    player_window.geometry("%dx%d+0+0" % (width_value, height_value))
    background_color = ANTI_FLASH_WHITE
    player_window.configure(background=background_color)
    player_window.title(player_message)

    game_frame = Frame(player_window)
    game_frame.configure(background=background_color)
    game_frame.pack(side=TOP)

    title_frame = Frame(game_frame)
    title_frame.configure(background=background_color)
    title_frame.pack()
    text_label = Label(title_frame,
                       text=player_message,
                       width=width_value,
                       font=("bold", 20),
                       anchor="w",
                       justify="center")
    text_label.configure(bg=UMBER, fg=ANTI_FLASH_WHITE)
    text_label.pack(side=TOP)

    top_frame = Frame(game_frame)
    top_frame.pack()
    top_frame.configure(background=background_color)

    bottom_frame = Frame(game_frame)
    bottom_frame.pack()
    bottom_frame.configure(background=background_color)

    number_of_players = len(player_names)
    for i in range(0, number_of_players):
        player_name = player_names[i]
        if i < number_of_players / 2:
            curr_frame = top_frame
        else:
            curr_frame = bottom_frame
        vote_button = Button(curr_frame,
                             bg=SPICY_MIX,
                             fg=ANTI_FLASH_WHITE,
                             height=20,
                             width=17,
                             text=player_name,
                             command=vote_function(player_window, player_name))
        vote_button.configure(font=("Courier", 10))
        vote_button.pack(side=LEFT)
    player_window.mainloop()
Ejemplo n.º 27
0
    def __init__(self, username):

        print(username)

        self.root = Tk()
        self.root.title('Main Menu')
        self.root.geometry('1300x690')
        self.root.resizable(False, False)

        frame = Frame(self.root, width=1000, height=690)
        frame.configure(background="gray28")
        frame.pack(fill=BOTH, expand=True)

        w = Label(self.root, text=f"{dt.datetime.now():%a, %b %d %Y}", bg="gray28", fg="white", pady=3, font=("Helvetica", 15))
        w.place(x=1100, y=15)

        image2 = create_img('Images/Capture.JPG')
        img2 = Label(frame, image=image2)
        img2.image = image2
        img2.place(x=15, y=15)

        header = Label(self.root, bg="gray28", fg="white", pady=3, font=("Helvetica", 30), text=f'Hello {username}' )
        header.place(x=540, y=155)

        #TODO: Increase text font inside the (Feature-3)

        button1 = Button(self.root, text="Insert New Project", command=self.input)
        button1.config(bg="aquamarine2", pady=10, padx=20, width=20, height=4)
        button1.place(x=350, y=320)

        button2 = Button(self.root, text="Projects Records", command=message)
        button2.config(bg="aquamarine2", pady=10, padx=20, width=20, height=4)
        button2.place(x=550, y=320)

        button3 = Button(self.root, text="Settings", command=message)
        button3.config(bg="aquamarine2", pady=10, padx=20, width=20, height=4)
        button3.place(x=750, y=320)

        bottom_header = Label(self.root, bg="gray28", fg="white", pady=3, font=("Helvetica", 15),
                              text='Hybrid Management - where Agile, TOC and waterfall meet together')
        bottom_header.place(x=360, y=650)
Ejemplo n.º 28
0
    def __init__(self, master, async_loop):
        Frame.__init__(self, master)
        self.async_loop = async_loop
        Frame.configure(self)
        self.master = master

        Label(self, text="To").grid(row=0)
        e1 = Entry(self, exportselection=0)
        e1.grid(row=0, column=1)

        Label(self, text="Subject").grid(row=1)
        subject = Text(self, height=1)
        subject.grid(row=1, column=1)

        Label(self, text="Message").grid(row=2)
        msg = Text(self)
        msg.grid(row=2, column=1)

        send_callback = functools.partial(self.send, e1, subject, msg)
        send_button = Button(self, text='Send', command=send_callback)
        send_button.grid(column=1)
Ejemplo n.º 29
0
class SaveGui:

    __name = None

    def __init__(self, main_controller, window):
        self.__main_controller = main_controller
        self.__window = window
        self.__menu = None

    def show(self):
        self.__menu = Frame(self.__window)
        self.__menu.configure(padx=10, pady=20)
        self.__menu.pack(fill=BOTH, expand=True)
        line1 = Frame(self.__menu)
        line1.pack(fill=X)
        self.__name = StringVar()
        self.__name.set("my_game_at_"+strftime("%H:%M")+"-"+strftime("%d.%m.%Y"))
        name_input = Entry(line1)
        name_input.configure(textvariable=self.__name)
        name_input.pack(fill=X)
        line2 = Frame(self.__menu)
        line2.pack(fill=X, pady=20)
        save_btn = Button(line2)
        save_btn.configure(text="Save Game", command=self.save)
        save_btn.pack(fill=X)

    def remove(self):
        if self.__menu is not None:
            self.__menu.destroy()
            self.__memu = None

    def save(self):
        if self.__name is not None:
            self.__main_controller.save_game(self.__name.get())
        self.remove()
        self.__main_controller.show_game()
        self.__main_controller.toggle_game()
        self.__main_controller.toggle_game()
Ejemplo n.º 30
0
class ProgressBarScreen(Toplevel):
    def __init__(self, master):
        super().__init__(master = master) 
        self.title("Progress Screen") 
        self.geometry("300x150") 
        setWindowStyle(self)
        self.labelFrame = Frame(self)
        self.labelFrame.configure(background=window_bg)
        self.minLabel = createLabel(self.labelFrame)
        self.maxLabel = createLabel(self.labelFrame)
        setStyleText(self.minLabel, "0%")
        setStyleText(self.maxLabel, "100%")
        self.minLabel.grid(row = 0, column= 0, padx = 20)
        self.maxLabel.grid(row = 0, column= 4, padx = 20)
        self.labelFrame.grid(row = 0, column = 1, pady = (40, 0))
        
        self.progressBar = Progressbar(self)
        self.progressBar.grid(row = 1, column = 1, pady = 5)
        self.progressLabel = createLabel(self)
        setStyleText(self.progressLabel, "INITIALIZING...")
        self.progressLabel.grid(row = 2, column = 1)
        
    def updatePercentage(self, percentage, message):
        if percentage < 98:
            self.progressBar["value"] = percentage
            self.progressBar.update_idletasks()
            self.minLabel["text"] = str(percentage) + "%"
            self.progressLabel["text"] = message
        else:
            global usingMergedData
            if not usingMergedData:
                clearSplittedChannelsSelected(0)
                clearSplittedChannelsSelected(1)
            else:
                clearMergedChannelsSelected(0)
                clearMergedChannelsSelected(1)
            generate_btn["state"] ="normal"
            self.destroy()
def startpage():
    form5 = Frame(t)
    bb = Button(form5,
                text='TEST NOW!',
                font=("Times", 35),
                width=20,
                bg="black",
                fg="white",
                relief="raised",
                bd=40,
                activebackground="black",
                command=logpage,
                activeforeground="black")

    def sdff(Event):
        form5.destroy()
        s.destroy()
        logpage()

    bb.bind('<Button-1>', sdff)
    bb.grid(row=0, column=0)
    form5.place(x=700, y=180)
    form5.configure(bg='white')
Ejemplo n.º 32
0
def buildMergedDataButtons(row):
    fr_buttons = Frame(window)
    fr_buttons.configure(background=window_bg)
    
    label = createLabel(fr_buttons)
    setStyleText(label, "N90E, N00E and VERTICAL", True)
    label.grid(row=0, column=1, padx=5, pady=5)
        
    for sensor in range(2):
        clearChannelsButton(
            fr_buttons, sensor, 
            lambda x=sensor: clearMergedChannelsSelected(x))
        btn_channel = TransparentButton(fr_buttons, 
            command = lambda index=sensor:selectFilesSystem(index))
        setStyleText(
            btn_channel, 
            "NOT SELECTED {} DATA".format("H" if sensor == 0 else "L"))
        btn_channel.grid(row=sensor + 1, column=1, padx=5, pady=5)
        fr_buttons.grid(row=row, column=1) 
        mergedData_buttons.append(btn_channel)
        mergedData_filepath.append([])
        mergedData_names.append([])  
    return fr_buttons
Ejemplo n.º 33
0
 def __init__(self, master):
     super().__init__(master = master) 
     self.inputs = []
     self.title("Advanced Settings") 
     self.geometry("190x350") 
     setWindowStyle(self)
     label = createLabel(self)
     setStyleText(label, "", True)
     label.grid(row=0, column=0, sticky="nw", padx=(20, 0), pady=5)
     
     self.textAndInput("Sampling Rate:", 2)
     self.textAndInput("Segment Lenght:", 3)
     self.textAndInput("Start H Whole:", 4)
     self.textAndInput("Start L Whole:", 5)
     self.textAndInput("End H Whole:", 6)
     self.textAndInput("End L Whole:", 7)
     self.loadData()
     
     global usingMergedData, use_baseline_correction
     self.checkMerge = IntVar(value=usingMergedData)
     self.checkBaseline = IntVar(value=use_baseline_correction)
     check1 = Checkbutton(self, variable=self.checkMerge)#, command =self.changeCheckValue)
     check2 = Checkbutton(self, variable=self.checkBaseline)
     setStyleText(check1, " Use Merged Data")
     setStyleText(check2, " Use Baseline Corr.")
     check1.grid(row=8, column=0, padx=(20, 0), pady=(10, 0), sticky="nw")
     check2.grid(row=9, column=0, padx=(20, 0), sticky="nw")
     
     frame = Frame(self)
     frame.configure(background=window_bg)
     submit = Button(frame, command = self.submit)
     cancel = Button(frame, command = lambda: self.destroy())
     setStyleText(cancel, "Cancel")
     setStyleText(submit, "Submit")
     submit.grid(row=0, column=0, padx=(0, 5), sticky="nw")
     cancel.grid(row=0, column=1, padx=(0, 5), sticky="nw")
     frame.grid(row=10, column=0, padx=(20, 0), pady=(10, 0))
Ejemplo n.º 34
0
class GUI:
    def __init__(self, master):
        """initialize GUI"""
        self.root = master
        self.on = True
        Tk().withdraw()

        self.starttime = datetime.now()

        # status bar, info for user
        self.statusString = StringVar()
        self.statusText = 'Ready'
        self.statusString.set(self.statusText)

        self.lvlStatus = StringVar()
        self.ifmStatus = StringVar()

        self.active = 0  # 0 - inactive state, 1 - active (in motion), 2 - steady (waiting while taking data)
        self.auto = 0

        # COMPARATOR MOTION CONTROL
        self.step = StringVar()  # mm
        self.begin = StringVar()  # mm
        self.end = StringVar()  # mm

        self.autoVal = IntVar()

        self.labelTop = StringVar()
        self.labelTop.set('VERTICAL COMPARATOR')

        # LABELS ON BUTTONS
        self.label10 = StringVar()  # start/stop
        self.label21 = StringVar()  # manual
        self.label22 = StringVar()  # auto
        self.label31 = StringVar()  # step
        self.label32 = StringVar()  # start
        self.label33 = StringVar()  # stop
        self.label51 = StringVar()  # read interferometer
        self.label52 = StringVar()  # read digi level

        self.autoVal.set(0)

        # init PLC, interferometer and level
        self.plc = PLC(comsettings['PLCPORT'], int(comsettings['PLCBAUD']))
        self.conn = self.plc.conn
        self.ifm = IFM(comsettings['IFMPORT'], int(comsettings['IFMBAUD']))
        self.lvl = LVL(comsettings['LVLPORT'], int(comsettings['LVLBAUD']))

        self.observer = ''  # operator

        self.label10.set({0: 'START', 1: 'STOP', 2:'STOP'}[self.active])  # start/stop
        self.setStatus({0: 'ready', 1: 'active', 2:'steady'}[self.active])
        self.label21.set('MANUAL')  # manual
        self.label22.set('AUTO')  # auto

        self.label31.set('LOW')  # start height
        self.label32.set('HIGH')  # stop height
        self.label33.set('STEP')  # step

        self.label51.set('READ IFM')  # read interferometer
        self.label52.set('READ LVL')  # read digi level

        self.timestring = StringVar()
        self.connstring = StringVar()

        # self.queue = queue.Queue()
        self.timerthread = threading.Thread(target=self.timer)
        self.timerthread.start()

        self.readdata = ''
        self.connthread = threading.Thread(target=self.checkconnection)
        self.connthread.start()

        self.statusthread = threading.Thread(target=self.checkstatus)
        self.statusthread.start()

        self.autologthread = threading.Thread(target=self.autolog)
        self.autologthread.start()

        # starttimer()
        # startautolog()
        # startautoserialcheck()

    # def toggleStartStop(self):
    #    # if start then stop else otherwise
    #    # change button and text color if possible
    #    pass

    def timer(self):
        while self.on:
            dt = datetime.now() - self.starttime
            self.timestring.set('%-10s' % str(dt).split('.')[0])
            time.sleep(1)

    def autolog(self, timeout=60):
        while self.on:
            print('Autolog')
            s, low, hi, step, ifm, lvl, obs = '', '', '', '', '', '', ''
            try:
                s = self.statusText
                low = self.lowEntry.get().strip()
                hi = self.hiEntry.get().strip()
                step = self.stepEntry.get().strip()
                ifm = IFM().read()
                lvl = LVL().read()
                obs = self.entryObserver.get().strip()
            except:
                print('problem with values')
            log('AUTOLOG! status: %s, low: %s, hi: %s, step: %s, ifm: %s, lvl: %s, obs: %s' % (
            s, low, hi, step, ifm, lvl, obs))
            time.sleep(timeout)

    def checkconnection(self):
        connection = False
        while self.on:
            if self.conn:
                try:
                    d = self.conn.read(1)
                    self.readdata += d
                    connection = True
                except:
                    self.conn.close()
                    try:
                        self.connect()
                    except:
                        connection = False
            else:
                try:
                    self.connect()
                except:
                    connection = False
            self.connstring.set({True: 'isConn', False: 'notConn'}[connection])
            time.sleep(0.5)

    def checkstatus(self):
        st = None
        if self.conn:
            try:
                st = self.plc.query('status')
                if st == commands['ACTIVE']:
                    self.plc.status = 'active'
                elif st == commands['INACTIVE']:
                    self.status = 'ready'
                else:
                    self.status = 'unknown'
            except:
                self.status = 'unknown'
        else:
            self.status = 'not connected'

    def evaluateEntries(self):
        s, b, e = self.stepEntry, self.beginEntry, self.endEntry
        res = [None, None, None]
        for i in range(3):
            try:
                res[i] = float([s, b, e][i])
            except:
                pass  # leave it None
        if b > e and s > 0:  # if step is negative, it can move downwards (from hi to low)
            b, e = e, b  # otherwise it begin and end must be changed if b>e
        elif b < e and s < 0:
            b, e = e, b

            # INPUT IN MM !! cannot recognize 0.5mm from 0.5m  step or 3mm vs 3m end
        # input values converted to mm
        # [s,b,e] = [i*1000. if (i is not None and i<5.) else i for i in [s,b,e]]
        return s, b, e

    def emptyRow(self, nrow):
        Label(self.fr, text="", bg=bgcolor).grid(row=nrow, column=0)

    def setStatus(self, text):
        self.statusText = text
        self.statusString.set(self.statusText)

    def setLvlStatus(self, text):
        self.lvlStatus.set(text)

    def setIfmStatus(self, text):
        self.ifmStatus.set(text)

    def getIfm(self):
        ifm = IFM()
        response = ifm.read()
        if not response: response = "No response"
        self.setIfmStatus(response)
        return response

    def getLevel(self):
        lvl = LVL()  # možno naèíta� pri __init__
        response = lvl.read()
        if not response: response = "No response"
        self.setLvlStatus(response)
        return response

    #    #set stop button
    #    def setStop(self):
    #        pass
    #
    #    #set start
    #    def setStart(self):
    #        pass

    # toggle start stop
    def startStop(self):
        self.active = not self.active
        self.label10.set({0: 'START', 1: 'STOP'}[self.active])
        self.setStatus({0: 'ready', 1: 'active'}[self.active])

        self.butStartStop.configure(bg=startstopbg[self.active],
                                    fg=startstopfg[self.active])

        self.observer = self.entryObserver.get().strip()

        if not self.active:
            log('CMP stopped %s' % self.observer)
        else:
            log('CMP started %s' % self.observer)

        if self.active:
            pass  # action after comparator is stopped
        else:
            pass  # action after comparator is started

    def getEntries(self):
        return self.stepEntry, self.beginEntry, self.endEntry

    def close(self):
        self.on = False
        if self.active:
            self.startStop()
        self.root.destroy()
        self.root.quit()

    def gotoLow(self):
        low = None
        self.setStatus('Going to LOW')
        try:
            low = float(self.lowEntry.get().strip())
        except:
            pass
        pass  # move carriage to set low
        return low

    def gotoHi(self):
        hi = None
        self.setStatus('Going to HIGH')
        try:
            hi = float(self.hiEntry.get().strip())
        except:
            pass
        pass  # move carriage to set low
        return hi

    def moveStep(self):
        pos = self.plc.getPos()
        step = 0
        try:
            step = float(self.stepEntry.get().strip())
        except:
            pass
        targetpos = pos + step

        if step != 0:
            self.setStatus('Moving to %f' % targetpos)
            self.plc.moveto(targetpos)
        return targetpos

    def resetLvlStatus(self):
        self.lvlStatus.set('')

    def resetIfmStatus(self):
        self.ifmStatus.set('')

    def mainDialog(self):

        self.basicframe = Frame(self.root)
        self.basicframe.grid()
        self.basicframe.configure(bg=bgcolor)

        self.fr = Frame(self.basicframe)
        self.fr.grid(row=0, column=0, sticky='new')  # , sticky='W')
        self.fr.configure(bg=bgcolor)

        # Grid.rowconfigure(root, 0, weight=1)
        Grid.columnconfigure(root, 0, weight=1)

        self.emptyRow(0)

        Label(self.fr, textvariable=self.labelTop,
              justify='center', bg=bgcolor, font=("Calibri", 24)
              ).grid(row=1, column=0, columnspan=3, sticky='we')

        self.emptyRow(2)

        Label(self.fr, text='STATUS:', justify='left', anchor='w',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
              ).grid(row=3, column=0, sticky='we', padx=(5, 0))

        self.statusLine = Label(self.fr, textvariable=self.statusString,
                                justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                font=("Calibri", 14, "bold")
                                ).grid(row=3, column=1, columnspan=2, sticky='we')

        self.emptyRow(4)

        self.butStartStop = Button(self.fr, textvariable=self.label10,
                                   command=self.startStop,
                                   bg=startstopbg[self.active],
                                   fg=startstopfg[self.active],
                                   font=("Calibri", 16, "bold"),
                                   width=10)
        self.butStartStop.grid(row=5, column=1, sticky='nsew')

        # AUTO / MANUAL  self.my_var.set(1)
        self.butManual = Radiobutton(self.fr, text="MANUAL",
                                     variable=self.auto,
                                     value=0,
                                     width=15,
                                     justify='center',
                                     # bg=buttoncolor2,
                                     bg="moccasin",
                                     indicatoron=0)  # self.exit_root)
        self.butManual.grid(row=5, column=0, sticky='ew', padx=(0, 10))
        # self.butManual.configure(state='selected')

        self.butAuto = Radiobutton(self.fr, text="AUTO",
                                   variable=self.auto,
                                   value=1,
                                   width=15, justify='center',
                                   # bg=buttoncolor2,
                                   bg="moccasin",
                                   indicatoron=0)  # self.exit_root)
        self.butAuto.grid(row=5, column=2, sticky='ew', padx=(10, 0))

        self.emptyRow(6)
        self.emptyRow(7)

        # put Labels here

        Label(self.fr, textvariable=self.label31, justify='center',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 10)
              ).grid(row=8, column=0, sticky='we')
        Label(self.fr, textvariable=self.label32, justify='center',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 10)
              ).grid(row=8, column=1, sticky='we')
        Label(self.fr, textvariable=self.label33, justify='center',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 10)
              ).grid(row=8, column=2, sticky='we')

        # input boxes: step start stop (mm)
        self.lowEntry = Entry(self.fr, width=20, bd=3, justify='right',
                              bg=inputbox, fg=statuscolor)
        self.lowEntry.grid(row=9, column=0, sticky='we')  # , columnspan=2)
        # SET DEFAULT LOW
        # self.lowEntry.delete(0,END)
        # self.lowEntry.insert(0, MINPOS)

        self.hiEntry = Entry(self.fr, width=20, bd=3, justify='right',
                             bg=inputbox, fg=statuscolor)
        self.hiEntry.grid(row=9, column=1, sticky='we')  # , columnspan=2)
        # SET DEFAULT HIGH
        # self.hiEntry.delete(0,END)
        # self.hiEntry.insert(0, MAXPOS)

        self.stepEntry = Entry(self.fr, width=20, bd=3, justify='right',
                               bg=inputbox, fg=statuscolor)
        self.stepEntry.grid(row=9, column=2, sticky='we')  # , columnspan=2)

        # put buttons for  GOTO and MOVE
        self.butGotoLow = Button(self.fr, text="Go To Low",
                                 justify='center', bg=buttoncolor, command=self.gotoLow)
        self.butGotoLow.grid(row=10, column=0, sticky='we')

        self.butGotoHi = Button(self.fr, text="Go To High",
                                justify='center', bg=buttoncolor, command=self.gotoHi)
        self.butGotoHi.grid(row=10, column=1, sticky='we')

        self.butMoveStep = Button(self.fr, text="Move a Step",
                                  justify='center', bg=buttoncolor, command=self.moveStep)
        self.butMoveStep.grid(row=10, column=2, sticky='we')

        self.emptyRow(11)

        Label(self.fr, text='EXTERNAL SENSORS', justify='left',
              anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
              ).grid(row=12, column=0, columnspan=3, sticky='we', padx=(5, 0))

        # function buttons


        # RIadok 12: Externals
        butIFM = Button(self.fr, text="Read IFM", width=15, justify='center',
                        bg=buttoncolor, command=self.getIfm)  # self.exit_root)
        butIFM.grid(row=13, column=0, sticky='we')

        self.labIfmStatus = Label(self.fr, textvariable=self.ifmStatus,
                                  justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                  font=("Calibri", 12))
        self.labIfmStatus.grid(row=13, column=1, columnspan=2,
                               sticky='we', padx=(15, 0))
        self.labIfmStatus.bind('<Button-1>', self.resetIfmStatus)

        butLVL = Button(self.fr, text="Read level", width=15, justify='center',
                        bg=buttoncolor, command=self.getLevel)  # self.exit_root)
        butLVL.grid(row=14, column=0, sticky='we')

        self.labLvlStatus = Label(self.fr, textvariable=self.lvlStatus,
                                  justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                  font=("Calibri", 12))
        self.labLvlStatus.grid(row=14, column=1, columnspan=2,
                               sticky='we', padx=(15, 0))
        self.labLvlStatus.bind('<Button-1>', self.resetLvlStatus)

        self.emptyRow(15)

        Label(self.fr, text='OBSERVER:', anchor='w', justify='left',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
              ).grid(row=16, column=0, sticky='we', padx=(5, 0))
        self.entryObserver = Entry(self.fr, textvariable=self.observer,
                                   bg=inputbox, fg=statuscolor, font=("Calibri", 12),
                                   justify='left')
        self.entryObserver.grid(row=16, column=1, columnspan=2, sticky='we')

        # row 18> empty (or test connection)
        self.emptyRow(18)
        self.timeLabel = Label(self.fr, textvariable=self.timestring,
                               anchor='w', bg=bgcolor, fg=statuscolor,
                               font=("Calibri", 9))
        self.timeLabel.grid(row=19, column=0)

        self.connLabel = Label(self.fr, textvariable=self.connstring,
                               anchor='w', bg=bgcolor, fg=statuscolor,
                               font=("Calibri", 9))
        self.connLabel.grid(row=19, column=1)

        butexit = Button(self.fr, text="EXIT", width=15, justify='center',
                         bg="black", fg="yellow", command=self.close,
                         font=("Calibri", 14, "bold"))
        butexit.grid(row=19, column=2)
Ejemplo n.º 35
0
class testGUI:
    def __init__(self, master):
        """initialize GUI"""
        self.root = master
        self.on = True
        self.connection = None
        Tk().withdraw()
        self.basicframe = Frame(self.root)
        self.basicframe.grid()
        self.basicframe.configure(bg=bgcolor)

        self.fr = Frame(self.basicframe)
        self.fr.grid(row=0, column=0, sticky='new')  # , sticky='W')
        self.fr.configure(bg=bgcolor)
        Grid.columnconfigure(self.root, 0, weight=1)

        self.port = None
        self.baud = None
        # self.inputTypes = ['ascii', 'bin', 'hex', 'mix']
        self.inputType = StringVar()
        self.inputType.set('ascii')
        self.input = 'ascii'

        self.labelPort = Label(self.fr, width=10, text='PORT', justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12))
        self.entryPort = Entry(self.fr, width=20, bd=3, justify='left', bg=inputbox, fg=fgcolor)

        self.labelBaud = Label(self.fr, text='BAUD', justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12))
        self.entryBaud = Entry(self.fr, width=20, bd=3, justify='right', bg=inputbox, fg=fgcolor)

        self.labelType = Label(self.fr, text='TYPE', justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12))
        self.radioType1 = Radiobutton(self.fr, text='ascii', variable=self.inputType, value='ascii', indicatoron=0)
        self.radioType2 = Radiobutton(self.fr, text='bin', variable=self.inputType, value='bin', width=20, indicatoron=0)
        self.radioType3 = Radiobutton(self.fr, text='hex', variable=self.inputType, value='hex', indicatoron=0)
        self.radioType4 = Radiobutton(self.fr, text='mix', variable=self.inputType, value='mix', width=20, indicatoron=0)

        self.labelInput = Label(self.fr, text='INPUT', justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12))
        self.entryInput = Entry(self.fr, width=20, bd=3, justify='left', bg=inputbox, fg=fgcolor)

        self.buttonSend = Button(self.fr, text='SEND', justify='center', bg=buttoncolor, command=self.send)
        self.buttonRead = Button(self.fr, text='READ', justify='center', bg=buttoncolor, command=self.read)
        self.buttonExit = Button(self.fr, text='EXIT', justify='center', bg='red', fg='white', command=self.exit)

        self.response = StringVar()
        self.response.set('')
        self.responseBar = Label(self.fr, textvariable=self.response, justify='left', anchor='w',
                                 bg=bgcolor, fg=fgcolor, font=("Calibri", 12))
        self.status = StringVar()
        self.statusBar = Label(self.fr, textvariable=self.status, justify='left', anchor='nw',
                               bg=bgcolor, fg=fgcolor, font=("Calibri", 10))
        self.status.set('Initialized')


    def emptyRow(self, nrow):
        Label(self.fr, text="", bg=bgcolor).grid(row=nrow, column=0)

    def configure_connection(self):
        self.status.set('Configuring connection')
        print ('Configuring connection')
        self.port = self.entryPort.get()
        self.baud = self.entryBaud.get()
        print ('{}:{}'.format(self.port, self.baud))
        try:
            self.baud = int(self.baud)
        except:
            print ('Something went wrong, setting baud to 0')
            self.entryBaud.delete(0, END)
            self.entryBaud.insert(0, '0')
            self.baud = 0

        self.connection = RS232(comport=self.port, baud=self.baud, dictionary={}, timeout=1)
        self.connection.connect()
        print ('Connection status: {}'.format(self.connection))

        if self.connection and self.connection.conn:
            print ('Connection established, locking current settings')
            self.entryPort.configure(state='disabled')
            self.entryBaud.configure(state='disabled')
        else:
            print ('No connection')
            self.status.set('<No connection>')

    def convertInput(self):
        self.status.set('Converting input')
        typ = self.inputType.get()
        self.input = self.entryInput.get()
        if typ == 'bin':
            newInput = ''.join(lambda x: x in '01', self.input)
            self.input = chr(int(newInput, 2))
        elif typ == 'hex':
            newInput = ''.join(lambda x: x in '0123456789ABCDEF', self.input)
            self.input = chr(int(newInput, 16))
        elif typ == 'mix':
            newInput = self.input
            for i in re.findall('<(\d+?)>', inp):
                newInput = newInput.replace('<{}>'.format(i), chr(int(i)))
            self.input = newInput
        print ('Converted input: {}'.format(self.input))

    def send(self):
        # self.input = self.entryInput.get()
        self.convertInput()
        self.status.set('Sending Data: {}'.format(self.input[:5]))
        if not self.connection or not self.connection.conn:
            # print ('Connection must be configured')
            self.configure_connection()
        if self.connection and self.connection.conn:
            # print ('Connection seems to be OK')
            stat = self.connection.send(bytes(self.input, 'utf-8'))
            self.status.set('')
            if not stat:
                print ('Sending not successful.')
            return stat
        else:
            # print ('Connection probably not established')
            pass
            return None
            # self.status.set('<No connection>')

    def read(self):
        self.status.set('Reading Data')
        print ('Read data')
        if not self.connection or not self.connection.conn:
            print ('Configuring connection')
            self.configure_connection()
        # self.input = self.entryInput.get()
        response = self.connection.receive()
        if response:
            print ('Response {}'.format(response))
            self.response.set(response)
        else:
            print ('No response')
            self.response.set('<No response>')
        # self.status.set('')

    def exit(self):
        # for thread in (self.timerthread, self.connthread, self.statusthread, self.autologthread, self.readexternalsthread):
        #     thread.join()
        # if self.active:
        #     self.startStop()
        self.on = False
        self.connection and self.connection.disconnect()
        self.root.destroy()
        self.root.quit()

    def mainDialog(self):
        self.labelPort.grid(row=0, column=0, sticky='we', padx=(5, 0))
        self.entryPort.grid(row=0, column=1, sticky='we')
        self.labelBaud.grid(row=1, column=0, sticky='we', padx=(5, 0))
        self.entryBaud.grid(row=1, column=1, sticky='we')
        self.labelType.grid(row=2, column=0, sticky='we', padx=(5, 0))
        self.radioType1.grid(row=2, column=1, sticky='we')
        self.radioType2.grid(row=2, column=2, sticky='we')
        self.radioType3.grid(row=3, column=1, sticky='we')
        self.radioType4.grid(row=3, column=2, sticky='we')
        self.labelInput.grid(row=4, column=0, sticky='we', padx=(5, 0))
        self.entryInput.grid(row=4, column=1)
        self.responseBar.grid(row=5, column=1)
        self.statusBar.grid(row=6, column=1)
        Label(self.fr, text="", bg=bgcolor).grid(row=7, column=0)
        self.buttonSend.grid(row=8, column=0)
        self.buttonRead.grid(row=8, column=1)
        self.buttonExit.grid(row=8, column=2)
Ejemplo n.º 36
0
		inwidget.delete(0.0, "end")




t = tkinter.Tk()

sw = t.winfo_screenwidth()
sh = t.winfo_screenheight()
fw = 720
fh = 406
sw = (sw - fw) / 2
sh = (sh - fh) / 3
t.geometry('%dx%d+%d+%d' % (fw, fh, sw, sh))
f = Frame(t)
f.configure(bg="#008888")
f.pack(fill="both", expand=1)

print('Reddit')
r=bot.rG()
print('Inbox')
inbox = list(r.get_inbox())
done = False
while not done:
	done = True
	for x in inbox:
		if x.new:
			done = False
			inbox.remove(x)
additems(inbox)
Ejemplo n.º 37
0
class Keypad(Frame):
    def __init__(self, master, gui, password):
        Frame.__init__(self, master, bg='sky blue', width=450, height=550)
        self.master.geometry('400x550')
        self.master = master
        self.master.configure(bg='sky blue')
        self.gui = gui
        self.password = password
        self.frame = Frame(master)
        self.frame.pack()
        self.frame.configure(bg='sky blue')

        index = 0
        while index < 5:
            self.frame.grid_rowconfigure(index, minsize=50)
            index += 1

        index = 0
        while index < 5:
            self.frame.grid_columnconfigure(index, minsize=50)
            index += 1

        self.box = Entry(self.frame)

        self.box.grid(row=0, columnspan=3)
        self.box.config(font=('Lucida Console', 78), width=6)

        self.list1 = [Button(self.frame, font=('Lucida Console', 30), text='1', command=lambda: self.bob_print(1)),
                 Button(self.frame, font=('Lucida Console', 30), text='2', command=lambda: self.bob_print(2)),
                 Button(self.frame, font=('Lucida Console', 30), text='3', command=lambda: self.bob_print(3))
                ]

        index = 0
        for each in self.list1:
            each.grid(row=1, column=index)
            each.config(bg='SkyBlue4', activebackground='midnight blue', fg='white', activeforeground='white')
            each.config(height=2, width=4)
            index += 1

        self.list2 = [Button(self.frame, font=('Lucida Console', 30), text='4', command=lambda: self.bob_print(4)),
                 Button(self.frame, font=('Lucida Console', 30), text='5', command=lambda: self.bob_print(5)),
                 Button(self.frame, font=('Lucida Console', 30), text='6', command=lambda: self.bob_print(6))
                ]

        index = 0
        for each in self.list2:
            each.grid(row=2, column=index)
            each.config(bg='SkyBlue4', activebackground='midnight blue', fg='white', activeforeground='white')
            each.config(height=2, width=4)
            index += 1

        self.list3 = [Button(self.frame, font=('Lucida Console', 30), text='7', command=lambda: self.bob_print(7)),
                 Button(self.frame, font=('Lucida Console', 30), text='8', command=lambda: self.bob_print(8)),
                 Button(self.frame, font=('Lucida Console', 30), text='9', command=lambda: self.bob_print(9))
                ]

        index = 0
        for each in self.list3:
            each.grid(row=3, column=index)
            each.config(bg='SkyBlue4', activebackground='midnight blue', fg='white', activeforeground='white')
            each.config(height=2, width=4)
            index += 1

        self.list4 = [Button(self.frame, font=('Lucida Console', 30), text='<', command=lambda: self.bob_print('<')),
                 Button(self.frame, font=('Lucida Console', 30), text='0', command=lambda: self.bob_print(0)),
                 Button(self.frame, font=('Lucida Console', 30), text='E', command=lambda: self.bob_print('E'))
                ]

        index = 0
        for each in self.list4:
            each.grid(row=4, column=index)
            each.config(bg='SkyBlue4', activebackground='midnight blue', fg='white', activeforeground='white')
            each.config(height=2, width=4)
            index += 1

    def bob_print(self, character):
        if not (character is '<' or character is 'E'):
            self.box.insert("end", character)
        elif character is '<':
            string = self.box.get()
            self.box.delete(0, 'end')
            self.box.insert('end', string[:-1])
        else:
            if self.box.get() == self.password:
                self.gui.access_granted()
                self.master.destroy()
            else:
                self.box.delete(0, 'end')
Ejemplo n.º 38
0
class GUI:
    def __init__(self, master):
        """initialize GUI"""
        self.root = master
        self.on = True
        Tk().withdraw()

        self.starttime = datetime.now()

        # status bar, info for user
        self.statusString = StringVar()
        self.statusText = 'Ready'
        self.statusString.set(self.statusText)
        self.comparatorStatus = 'inactive'
        # self.comparatorStatuses = ['inactive', 'active',
        #                            'steady', 'moving', 'paused', 'finished']
                                   # 2 manual statuses + 4 auto statuses

        self.levelStatus = StringVar()
        self.ifmStatus = StringVar()
        self.nivelStatus = StringVar()
        self.thermoStatus = StringVar()

        self.active = 0  # 0 - inactive state, 1 - active (in motion), 2 - steady (waiting while taking data)
        self.auto = 0

        # COMPARATOR MOTION CONTROL
        self.step = StringVar()  # mm
        self.begin = StringVar()  # mm
        self.end = StringVar()  # mm

        self.autoVal = IntVar()

        self.labelTop = StringVar()
        self.labelTop.set('VERTICAL COMPARATOR')

        # LABELS ON BUTTONS
        self.label10 = StringVar()  # initialize
        self.label11 = StringVar()  # start/stop
        self.label12 = StringVar()  # pause/continue
        self.label21 = StringVar()  # manual
        self.label22 = StringVar()  # auto
        self.label31 = StringVar()  # step
        self.label32 = StringVar()  # start
        self.label33 = StringVar()  # stop
        self.label51 = StringVar()  # manual read interferometer
        self.label52 = StringVar()  # manual read digi level
        self.label53 = StringVar()  # manual read nivel (inclinometer)
        self.label54 = StringVar()  # manual read thermometer

        self.autoVal.set(0)

        # init PLC, interferometer and level
        self.plc = Comparator(comsettings['COMPARATOR_PORT'], int(comsettings['COMPARATOR_BAUD']))
        self.conn = self.plc.conn
        self.paused = None
        self.ifm = Interferometer(comsettings['IFM_PORT'], int(comsettings['IFM_BAUD']))
        self.level = Level(comsettings['LEVEL_PORT'], int(comsettings['LEVEL_BAUD']))
        self.nivel = Nivel(comsettings['NIVEL_PORT'], int(comsettings['NIVEL_BAUD']))
        self.thermo = Thermometer(comsettings['THERMO_PORT'], int(comsettings['THERMO_BAUD']))

        self.observer = ''  # operator

        self.label10.set('Initialize')
        self.label11.set({0: 'START', 1: 'STOP', 2:'STOP'}[self.active])  # start/stop
        self.setStatus({0: 'ready', 1: 'active', 2:'steady'}[self.active])

        self.label12.set('PAUSE')

        self.label21.set('MANUAL')  # manual
        self.label22.set('AUTO')  # auto

        self.label31.set('LOW')  # start height
        self.label32.set('HIGH')  # stop height
        self.label33.set('STEP')  # step

        self.label51.set('READ IFM')  # read interferometer
        self.label52.set('READ LVL')  # read digi level
        self.label53.set('READ NVL')  # read inclinometer
        self.label54.set('READ THM')  # read thermometer

        self.chksumText = StringVar()
        self.responseText = StringVar()

        self.timestring = StringVar()
        self.connstring = StringVar()

        # self.queue = queue.Queue()
        self.timerthread = threading.Thread(target=self.timer, name='Timer')
        self.timerthread.start()

        self.readdata = ''
        self.connthread = threading.Thread(target=self.checkConnection, name='ConnChk')
        self.connthread.start()

        self.statusthread = threading.Thread(target=self.checkStatus, name='StatChk')
        self.statusthread.start()

        self.readexternalsthread = threading.Thread(target=self.readExternals, name='ReadExt')
        self.readexternalsthread.start()

        self.autologthread = threading.Thread(target=self.autolog, name='Autolog')
        self.autologthread.start()

        # starttimer()
        # startautolog()
        # startautoserialcheck()

    # def toggleStartStop(self):
    #    # if start then stop else otherwise
    #    # change button and text color if possible
    #    pass

    def timer(self):
        while self.on:
            dt = datetime.now() - self.starttime
            self.timestring.set('%-10s' % str(dt).split('.')[0])
            time.sleep(0.1)

    def autolog(self, timeout=60):
        while self.on:
            print('Autolog')
            (s, low, hi, step, ifm, lvl, nvl, thm, obs) = tuple(['']*9)
            try:
                s = self.statusText
            except BaseException:
                s = 'N/A'
            try:
                low = self.lowEntry.get().strip()
            except BaseException:
                low = 'N/A'
            try:
                hi = self.hiEntry.get().strip()
            except BaseException:
                hi = 'N/A'
            try:
                step = self.stepEntry.get().strip()
            except BaseException:
                step = 'N/A'
            try:
                ifm = self.ifm.getReading()
            except BaseException:
                ifm = 'N/A'
            try:
                lvl = self.level.getReading()
            except BaseException:
                lvl = 'N/A'
            try:
                nvl = self.nivel.getReading()
            except BaseException:
                nvl = 'N/A'
            try:
                thm = self.thermo.getReading()
            except BaseException:
                thm = 'N/A'
            try:
                obs = self.entryObserver.get().strip()
            except BaseException:
                obs = 'N/A'
            log('AUTOLOG! status: %s, low: %s, hi: %s, step: %s, ifm: %s, lvl: %s, nvl:%s, thm: %s, obs: %s' % (
            s, low, hi, step, ifm, lvl, nvl, thm, obs))
            time.sleep(timeout)

    def checkConnection(self):
        connection = False
        while self.on:
            if self.conn:
                try:
                    d = self.conn.read(1)
                    self.readdata += d
                    connection = True
                except:
                    self.conn.close()
                    try:
                        self.connect()
                    except:
                        connection = False
            else:
                try:
                    self.connect()
                except:
                    connection = False
            self.connstring.set({True: 'isConn', False: 'notConn'}[connection])
            time.sleep(0.5)

    def checkStatus(self):
        if self.conn:
            moving = self.plc.query('is_moving')
            if moving is None:
                self.status = 'unknown'
            elif not self.auto:
                if moving:
                    self.status = 'active'
                else:
                    self.status = 'inactive'
            else:
                if moving:
                    self.status = 'moving'
                else:
                    if self.paused:
                        self.status = 'paused'
                    else:
                        self.status = 'steady'
        else:
            self.status = 'not connected'

    def readExternals(self):
        while self.on:
            # self.getIfm()
            # self.getLevel()
            self.getNivel()
            self.getThermo()
            time.sleep(15)

    def evaluateEntries(self):
        s, b, e = self.stepEntry, self.beginEntry, self.endEntry
        res = [None, None, None]
        for i in range(3):
            try:
                res[i] = float([s, b, e][i])
            except:
                pass  # leave it None
        if b > e and s > 0:  # if step is negative, it can move downwards (from hi to low)
            b, e = e, b  # otherwise it begin and end must be changed if b>e
        elif b < e and s < 0:
            b, e = e, b

        # INPUT IN MM !! cannot recognize 0.5mm from 0.5m  step or 3mm vs 3m end
        # input values converted to mm
        # [s,b,e] = [i*1000. if (i is not None and i<5.) else i for i in [s,b,e]]
        return s, b, e

    def emptyRow(self, nrow):
        Label(self.fr, text="", bg=bgcolor).grid(row=nrow, column=0)

    def setStatus(self, text):
        self.statusText = text
        self.statusString.set(self.statusText)

    def setIfmStatus(self, text):
        self.ifmStatus.set(text)

    def setLevelStatus(self, text):
        self.levelStatus.set(text)

    def setNivelStatus(self, text):
        self.nivelStatus.set(text)

    def setThermoStatus(self, text):
        self.thermoStatus.set(text)

    def getIfm(self):
        # log('Get Ifm reading')
        response = self.ifm.getReading() or "No response"
        self.setIfmStatus(response)
        return response

    def getLevel(self):
        # log('Get Level reading')
        response = self.level.getReading() or "No response"
        self.setLevelStatus(response)
        return response

    def getNivel(self):
        # log('Get Nivel reading')
        response = '-'.join(map(str,self.nivel.getReading())) if any(self.nivel.getReading()) else "No response"
        self.setNivelStatus(response)
        return response

    def getThermo(self):
        # log('Get Thermo reading')
        response = self.thermo.getReading() or "No response"
        self.setThermoStatus(response)
        return response

    #    #set stop button
    #    def setStop(self):
    #        pass
    #
    #    #set start
    #    def setStart(self):
    #        pass

    # toggle start stop
    def startStop(self):
        # ask comparator if moving, then set "not response"
        self.active = not self.active
        # self.setStatus({0: 'ready', 1: 'active'}[self.active])
        self.setStatus(self.comparatorStatus)

        self.label10.set({0: 'START', 1: 'STOP'}[self.active])
        self.buttonStartStop.configure(bg=startstopbg[self.active],
                                       fg=startstopfg[self.active])
        print(self.active)

        self.observer = self.entryObserver.get().strip()

        if not self.active:
            log('CMP stopped %s' % self.observer)
        else:
            log('CMP started %s' % self.observer)

        if self.active:
            pass  # action after comparator is stopped
        else:
            pass  # action after comparator is started

    # CURRENT_POSITION, NEXT_POSITION, TARGET_POSITION, ITERATION
    def writePauseParams(self,**params):
        with open('.pause') as f:
            f.write('\n'.join([k+' '+' '.join(vals) for k, vals in params.items()]))
        return True

    def readPauseParams(self):
        params = {}
        with open('.pause','r') as f:
            for line in f.readlines():
                key = line.split()[0]
                vals = line.split()[1:]
                params[key] = vals
        os.remove('.pause')
        return params

    def pauseSession(self):
        self.paused = True
        self.stop()
        self.writePauseParams()

    def continueSession(self):
        self.paused = False
        params = self.readPauseParams()
        self.moveto(params['NEXT_POS'])
        self.session(float(params['NEXT_POS']), float(params['TARGET_POS']),
                          float(params['STEP']), int(params['NEXT_ITER']))

    def session(self, **params):
        start = float(params.get('START_POS'))
        target = float(params.get('TARGET_POS'))
        step = float(params.get('STEP',5))
        iteration = int(params.get('NEXT_ITER',0))
        self.plc.moveto(start)
        self.paused = False
        op = operator.le if step > 0 else operator.ge
        while op(self.plc.getPosition(), target):
            iteration += 1
            self.getMeasurement()
            next_position = self.plc.getPosition() + step
            if next_position < target:
                self.plc.moveto(next_position)


    def initialize(self):
        if not self.plc.isInit():
            log('Initialize')
        else:
            log('Already initialized, reinitialize.')
        self.plc.initialize()

    def pause(self):
        # comparator status:
        # man/inactive, man/active,
        # auto/steady (measurement), auto/active, auto/paused, auto/finished
        #['inactive', 'active', 'steady', 'moving', 'paused', 'finished']
        if self.comparatorStatus in ('moving', 'steady'):
            self.pauseSession()

        elif self.comparatorStatus == 'paused':
            self.continueSession()

        # active / inactive - button should be disabled


    def stop(self):
        self.plc.command('STOP')

    def getEntries(self):
        return self.stepEntry, self.beginEntry, self.endEntry

    def close(self):
        self.on = False
        # for thread in (self.timerthread, self.connthread, self.statusthread, self.autologthread, self.readexternalsthread):
        #     thread.join()
        # TODO CLOSE ALL CONNECTIONS!!
        if self.active:
            self.startStop()
        self.root.destroy()
        self.root.quit()

    def gotoLow(self):
        low = None
        self.setStatus('Going to LOW')
        try:
            low = float(self.lowEntry.get().strip())
        except:
            pass
        pass  # move carriage to set low
        return low

    def gotoHi(self):
        hi = None
        self.setStatus('Going to HIGH')
        try:
            hi = float(self.hiEntry.get().strip())
        except:
            pass
        pass  # move carriage to set low
        return hi

    def moveStep(self):
        pos = self.plc.getPosition() or 0  # remove 0 when connection established
        step = 0
        try:
            step = float(self.stepEntry.get().strip())
        except BaseException:
            log('Cannot determine step entry.')
        targetpos = pos + step
        if step != 0:
            self.setStatus('Moving to %f' % targetpos)
            self.plc.moveto(targetpos)
        return targetpos

    def resetIfmStatus(self):
        self.ifmStatus.set('')

    def resetLevelStatus(self):
        self.levelStatus.set('')

    def resetNivelStatus(self):
        self.nivelStatus.set('')

    def resetThermoStatus(self):
        self.thermoStatus.set('')

    def submit(self):
        calculate_checksum = True

        port = self.portEntry.get().strip()
        message = self.messageEntry.get()
        chksumtyp = self.portChecksumType.get()

        from externals import RS232
        from pycrc import pycrc, crc_algorithms, Crc

        rs = RS232()
        r = rs.connect(port, baud=38400)
        if r:
            print ('Successfully connected to %s' % r.name)


        checksum = ''
        if calculate_checksum:
            from pycrc.crc_algorithm import Crc

            # params = filter(lambda x: x['name']==chksumtyp, cmodels)[0]
            params = {'width': 16, 'poly':0x1021, 'reflect_in':True,
                      'xor_in':0x0000, 'reflect_out':True, 'xor_out':0x0000}

            crc = Crc(**params)
            print("{0:#x}".format(crc.bit_by_bit(message)))
            # crc = Crc(width=16, poly=0x8005,
            #             reflect_in = True, xor_in = 0x0000,
            #             reflect_out = True, xor_out = 0x0000)
            # >> > print("{0:#x}".format(crc.bit_by_bit("123456789")))
            # >> > print("{0:#x}".format(crc.bit_by_bit_fast("123456789")))
            # >> > print("{0:#x}".format(crc.table_driven("123456789")))



        rs.send()


        # self.chksumLabel = (self.fr, textvariable = self.chksumText, anchor = 'w',
        #                                                                       bg = bgcolor, fg = statuscolor, font = (
        # "Calibri", 9))
        # self.chksumLabel.grid(row=23, column=2)
        #
        # buttonSubmit = Button(self.fr, text="SUBMIT", width=15, justify='center',
        #                       bg="black", fg="yellow", command=self.submit,
        #                       font=("Calibri", 14, "bold"))
        # buttonSubmit.grid(row=23, column=0)
        #
        # self.responseLabel = (self.fr, textvariable = self.responseText, anchor = 'w',
        #                                                                           bg = bgcolor, fg = statuscolor, font = (
        # "Calibri", 9))
        # self.responseLabel.grid(row=23, column=1)
        #
        # self.emptyRow(24)



    def mainDialog(self):

        self.basicframe = Frame(self.root)
        self.basicframe.grid()
        self.basicframe.configure(bg=bgcolor)

        self.fr = Frame(self.basicframe)
        self.fr.grid(row=0, column=0, sticky='new')  # , sticky='W')
        self.fr.configure(bg=bgcolor)

        # Grid.rowconfigure(root, 0, weight=1)
        Grid.columnconfigure(root, 0, weight=1)

        self.emptyRow(0)

        Label(self.fr, textvariable=self.labelTop,
              justify='center', bg=bgcolor, font=("Calibri", 24)
              ).grid(row=1, column=0, columnspan=3, sticky='we')

        self.emptyRow(2)

        Label(self.fr, text='STATUS:', justify='left', anchor='w',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
              ).grid(row=3, column=0, sticky='we', padx=(5, 0))

        self.statusLine = Label(self.fr, textvariable=self.statusString,
                                justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                font=("Calibri", 14, "bold")
                                ).grid(row=3, column=1, columnspan=2, sticky='we')

        self.emptyRow(4)

        # AUTO / MANUAL  self.my_var.set(1)
        self.buttonManual = Radiobutton(self.fr, text="MANUAL",
                                     variable=self.auto,
                                     value=0,
                                     width=15,
                                     justify='center',
                                     # bg=buttoncolor2,
                                     bg="moccasin",
                                     indicatoron=0)  # self.exit_root)
        self.buttonManual.grid(row=5, column=0, sticky='ew', padx=(0, 10))
        # self.buttonManual.configure(state='selected')

        self.buttonAuto = Radiobutton(self.fr, text="AUTO",
                                   variable=self.auto,
                                   value=1,
                                   width=15, justify='center',
                                   # bg=buttoncolor2,
                                   bg="moccasin",
                                   indicatoron=0)  # self.exit_root)
        self.buttonAuto.grid(row=5, column=2, sticky='ew', padx=(10, 0))

        self.emptyRow(6)

        #should be disabled if initialized already
        self.buttonInitialize = Button(self.fr, text='Initialize',
                                   justify='center', bg=buttoncolor, command=self.initialize)
        self.buttonInitialize.grid(row=7, column=0, sticky='nsew')

        self.buttonStartStop = Button(self.fr, textvariable=self.label11,
                                   command=self.startStop,
                                   bg=startstopbg[self.active],
                                   fg=startstopfg[self.active],
                                   font=("Calibri", 16, "bold"),
                                   width=10)
        self.buttonStartStop.grid(row=7, column=1, sticky='nsew')

        self.buttonPause = Button(self.fr, textvariable=self.label12,
                                   justify='center', bg=buttoncolor,
                                   state={0: 'disabled', 1: 'enabled'}[self.auto],
                                   command=self.pause)
        self.buttonPause.grid(row=7, column=2, sticky='nsew')

        self.emptyRow(8)

        # put Labels here

        Label(self.fr, textvariable=self.label31, justify='center',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 10)
              ).grid(row=8, column=0, sticky='we')
        Label(self.fr, textvariable=self.label32, justify='center',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 10)
              ).grid(row=8, column=1, sticky='we')
        Label(self.fr, textvariable=self.label33, justify='center',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 10)
              ).grid(row=8, column=2, sticky='we')

        # input boxes: step start stop (mm)
        self.lowEntry = Entry(self.fr, width=20, bd=3, justify='right',
                              bg=inputbox, fg=statuscolor)
        self.lowEntry.grid(row=9, column=0, sticky='we')  # , columnspan=2)
        # SET DEFAULT LOW
        # self.lowEntry.delete(0,END)
        # self.lowEntry.insert(0, MINPOS)

        self.hiEntry = Entry(self.fr, width=20, bd=3, justify='right',
                             bg=inputbox, fg=statuscolor)
        self.hiEntry.grid(row=9, column=1, sticky='we')  # , columnspan=2)
        # SET DEFAULT HIGH
        # self.hiEntry.delete(0,END)
        # self.hiEntry.insert(0, MAXPOS)

        self.stepEntry = Entry(self.fr, width=20, bd=3, justify='right',
                               bg=inputbox, fg=statuscolor)
        self.stepEntry.grid(row=9, column=2, sticky='we')  # , columnspan=2)

        # put buttons for  GOTO and MOVE
        self.butGotoLow = Button(self.fr, text="Go To Low",
                                 justify='center', bg=buttoncolor, command=self.gotoLow)
        self.butGotoLow.grid(row=10, column=0, sticky='we')

        self.butGotoHi = Button(self.fr, text="Go To High",
                                justify='center', bg=buttoncolor, command=self.gotoHi)
        self.butGotoHi.grid(row=10, column=1, sticky='we')

        self.butMoveStep = Button(self.fr, text="Move a Step",
                                  justify='center', bg=buttoncolor, command=self.moveStep)
        self.butMoveStep.grid(row=10, column=2, sticky='we')

        self.emptyRow(11)

        Label(self.fr, text='EXTERNAL SENSORS', justify='left',
              anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
              ).grid(row=12, column=0, columnspan=3, sticky='we', padx=(5, 0))

        # function buttons


        # RIadok 13-16: Externals
        # Interferometer
        buttonIfm = Button(self.fr, text="Read IFM", width=15, justify='center',
                        bg=buttoncolor, command=self.getIfm)  # self.exit_root)
        buttonIfm.grid(row=13, column=0, sticky='we')

        self.labelIfmStatus = Label(self.fr, textvariable=self.ifmStatus,
                                  justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                  font=("Calibri", 12))
        self.labelIfmStatus.grid(row=13, column=1, columnspan=2,
                               sticky='we', padx=(15, 0))
        self.labelIfmStatus.bind('<Button-1>', self.resetIfmStatus)

        # Digital level (Leica /Trimble)
        buttonLevel = Button(self.fr, text="Read Level", width=15, justify='center',
                        bg=buttoncolor, command=self.getLevel)  # self.exit_root)
        buttonLevel.grid(row=14, column=0, sticky='we')

        self.labelLevelStatus = Label(self.fr, textvariable=self.levelStatus,
                                  justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                  font=("Calibri", 12))
        self.labelLevelStatus.grid(row=14, column=1, columnspan=2,
                               sticky='we', padx=(15, 0))
        self.labelLevelStatus.bind('<Button-1>', self.resetLevelStatus)

        # Nivel - inclinometer
        buttonNivel = Button(self.fr, text="Read Nivel", width=15, justify='center',
                        bg=buttoncolor, command=self.getNivel)  # self.exit_root)
        buttonNivel.grid(row=15, column=0, sticky='we')

        self.labelNivelStatus = Label(self.fr, textvariable=self.nivelStatus,
                                  justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                  font=("Calibri", 12))
        self.labelNivelStatus.grid(row=15, column=1, columnspan=2,
                               sticky='we', padx=(15, 0))
        self.labelNivelStatus.bind('<Button-1>', self.resetNivelStatus)

        # Thermometer line
        buttonThermo = Button(self.fr, text="Read Thermo", width=15, justify='center',
                        bg=buttoncolor, command=self.getThermo)  # self.exit_root)
        buttonThermo.grid(row=16, column=0, sticky='we')

        self.labelThermoStatus = Label(self.fr, textvariable=self.thermoStatus,
                                  justify='left', anchor='w', bg=bgcolor, fg=statuscolor,
                                  font=("Calibri", 12))
        self.labelThermoStatus.grid(row=16, column=1, columnspan=2,
                               sticky='we', padx=(15, 0))
        self.labelThermoStatus.bind('<Button-1>', self.resetThermoStatus)

        self.emptyRow(17)

        Label(self.fr, text='OBSERVER:', anchor='w', justify='left',
              bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
              ).grid(row=19, column=0, sticky='we', padx=(5, 0))
        self.entryObserver = Entry(self.fr, textvariable=self.observer,
                                   bg=inputbox, fg=statuscolor, font=("Calibri", 12),
                                   justify='left')
        self.entryObserver.grid(row=19, column=1, columnspan=2, sticky='we')

        # row 18> empty (or test connection)
        self.emptyRow(20)

        if ADMIN_MODE:
            # port, message, checksum_type?, resulting checksum?, submit, response
            self.portEntry = Entry(self.fr, width=20, bd=3, justify='left',
                                   bg=inputbox, fg=statuscolor)
            self.portEntry.grid(row=21, column=0, sticky='we')
            Label(self.fr, text='PORT', anchor='w', justify='left',
                  bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
                  ).grid(row=22, column=0, sticky='we', padx=(5, 0))

            self.messageEntry = Entry(self.fr, width=20, bd=3, justify='left',
                                   bg=inputbox, fg=statuscolor)
            self.messageEntry.grid(row=21, column=1, sticky='we')
            Label(self.fr, text='MESSAGE', anchor='w', justify='left',
                  bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
                  ).grid(row=22, column=1, sticky='we', padx=(5, 0))

            self.portChecksumType = Entry(self.fr, width=20, bd=3, justify='left',
                                   bg=inputbox, fg=statuscolor)
            self.portChecksumType.grid(row=21, column=2, sticky = 'we')
            Label(self.fr, text='CHKSUM TYPE', anchor='w', justify='left',
                        bg=bgcolor, fg=statuscolor, font=("Calibri", 12)
                        ).grid(row=22, column=2, sticky='we', padx=(5, 0))


            self.chksumLabel = Label(self.fr, textvariable=self.chksumText, anchor='w',
                                bg=bgcolor, fg=statuscolor, font=("Calibri", 9))
            self.chksumLabel.grid(row=23, column=2)

            buttonSubmit = Button(self.fr, text="SUBMIT", width=15, justify='center',
                             bg="black", fg="yellow", command=self.submit,
                             font=("Calibri", 14, "bold"))
            buttonSubmit.grid(row=23, column=0)


            self.responseLabel = Label(self.fr, textvariable=self.responseText, anchor='w',
                                bg=bgcolor, fg=statuscolor, font=("Calibri", 9))
            self.responseLabel.grid(row=23, column=1)

            self.emptyRow(24)


        lastLine = 21 if not ADMIN_MODE else 25

        self.timeLabel = Label(self.fr, textvariable=self.timestring,
                               anchor='w', bg=bgcolor, fg=statuscolor,
                               font=("Calibri", 9))
        self.timeLabel.grid(row=lastLine, column=0)

        self.connLabel = Label(self.fr, textvariable=self.connstring,
                               anchor='w', bg=bgcolor, fg=statuscolor,
                               font=("Calibri", 9))
        self.connLabel.grid(row=lastLine, column=1)

        butexit = Button(self.fr, text="EXIT", width=15, justify='center',
                         bg="black", fg="yellow", command=self.close,
                         font=("Calibri", 14, "bold"))
        butexit.grid(row=lastLine, column=2)
Ejemplo n.º 39
0
class Momentary:
    def __init__(self, master, valves):
        self.valves = valves

        self.master = master
        self.frame1 = Frame(master)
        self.frame2 = Frame(master)

        self.master.configure(bg='sky blue')
        self.frame1.configure(bg='sky blue')
        self.frame2.configure(bg='sky blue')

        index = 0
        while index < 6:
            self.frame1.grid_columnconfigure(index, minsize=6)
            self.frame2.grid_columnconfigure(index, minsize=6)

            self.frame1.grid_rowconfigure(index, minsize=140)
            self.frame2.grid_rowconfigure(index, minsize=140)
            index += 1

        self.end_all_image = PhotoImage(file="img/stop.png").subsample(x=6, y=6)
        self.end_all_button = Button(self.master, image=self.end_all_image, command=lambda: self.end_all() )
        self.end_all_button.config(bg='brown3', activebackground='brown4', border=5, width=850)

        self.label = [Label(self.frame1, textvariable=self.valves[0].get_name()),
                      Label(self.frame1, textvariable=self.valves[1].get_name()),
                      Label(self.frame1, textvariable=self.valves[2].get_name()),
                      Label(self.frame1, textvariable=self.valves[3].get_name()),
                      Label(self.frame2, textvariable=self.valves[4].get_name()),
                      Label(self.frame2, textvariable=self.valves[5].get_name()),
                      Label(self.frame2, textvariable=self.valves[6].get_name()),
                      Label(self.frame2, textvariable=self.valves[7].get_name())]

        row = 0
        for each in self.label:
            each.config(width=7, height=2)
            each.config(bg='sky blue', fg='RoyalBlue4', font=('Lucida Console', 30), padx=18)
            each.grid(row=row % 4, column=0)
            row += 1

        self.lightsA = [LED(self.frame1, 30, 'green1', 'green', 'dark green', 'Dark Green', False),
                        LED(self.frame1, 30, 'green1', 'green', 'dark green', 'Dark Green', False),
                        LED(self.frame1, 30, 'green1', 'green', 'dark green', 'Dark Green', False),
                        LED(self.frame1, 30, 'green1', 'green', 'dark green', 'Dark Green', False),
                        LED(self.frame2, 30, 'green1', 'green', 'dark green', 'Dark Green', False),
                        LED(self.frame2, 30, 'green1', 'green', 'dark green', 'Dark Green', False),
                        LED(self.frame2, 30, 'green1', 'green', 'dark green', 'Dark Green', False),
                        LED(self.frame2, 30, 'green1', 'green', 'dark green', 'Dark Green', False)
                        ]

        self.lightsB = [LED(self.frame1, 30, 'red', 'dark red', 'red4', 'DarkRed', False),
                        LED(self.frame1, 30, 'red', 'dark red', 'red4', 'DarkRed', False),
                        LED(self.frame1, 30, 'red', 'dark red', 'red4', 'DarkRed', False),
                        LED(self.frame1, 30, 'red', 'dark red', 'red4', 'DarkRed', False),
                        LED(self.frame2, 30, 'red', 'dark red', 'red4', 'DarkRed', False),
                        LED(self.frame2, 30, 'red', 'dark red', 'red4', 'DarkRed', False),
                        LED(self.frame2, 30, 'red', 'dark red', 'red4', 'DarkRed', False),
                        LED(self.frame2, 30, 'red', 'dark red', 'red4', 'DarkRed', False)
                        ]

        self.v = [IntVar(),
                  IntVar(),
                  IntVar(),
                  IntVar(),
                  IntVar(),
                  IntVar(),
                  IntVar(),
                  IntVar()]

        for each in self.v:
            each.set(3)

        self.a = [Radiobutton(self.frame1, text='A', command=lambda: self.activate_a(0), value=1),
                  Radiobutton(self.frame1, text='A', command=lambda: self.activate_a(1), value=1),
                  Radiobutton(self.frame1, text='A', command=lambda: self.activate_a(2), value=1),
                  Radiobutton(self.frame1, text='A', command=lambda: self.activate_a(3), value=1),
                  Radiobutton(self.frame2, text='A', command=lambda: self.activate_a(4), value=1),
                  Radiobutton(self.frame2, text='A', command=lambda: self.activate_a(5), value=1),
                  Radiobutton(self.frame2, text='A', command=lambda: self.activate_a(6), value=1),
                  Radiobutton(self.frame2, text='A', command=lambda: self.activate_a(7), value=1)]

        index = 0
        for each in self.a:
            each.grid(row=index % 4, column=2)
            each.config(width=4, height=2,  indicatoron=0, variable=self.v[index], font=('Lucida Console', 30))
            each.config(bg='SkyBlue4', activebackground='midnight blue', selectcolor='midnight blue', fg='white')
            each.config(activeforeground='white')
            index += 1

        self.b = [Radiobutton(self.frame1, text='B', command=lambda: self.activate_b(0), value=0),
                  Radiobutton(self.frame1, text='B', command=lambda: self.activate_b(1), value=0),
                  Radiobutton(self.frame1, text='B', command=lambda: self.activate_b(2), value=0),
                  Radiobutton(self.frame1, text='B', command=lambda: self.activate_b(3), value=0),
                  Radiobutton(self.frame2, text='B', command=lambda: self.activate_b(4), value=0),
                  Radiobutton(self.frame2, text='B', command=lambda: self.activate_b(5), value=0),
                  Radiobutton(self.frame2, text='B', command=lambda: self.activate_b(6), value=0),
                  Radiobutton(self.frame2, text='B', command=lambda: self.activate_b(7), value=0)]

        index = 0
        for each in self.b:
            each.grid(row=index % 4, column=3)
            each.config(width=4, height=2,  indicatoron=0, variable=self.v[index], font=('Lucida Console', 30))
            each.config(bg='SkyBlue4', activebackground='midnight blue', selectcolor='midnight blue', fg='white')
            each.config(activeforeground='white')
            index += 1

        self.end_image = PhotoImage(file="img/no.png").subsample(x=6, y=6)
        self.end_button = [Radiobutton(self.frame1, image=self.end_image, command=lambda: self.end(0)),
                           Radiobutton(self.frame1, image=self.end_image, command=lambda: self.end(1)),
                           Radiobutton(self.frame1, image=self.end_image, command=lambda: self.end(2)),
                           Radiobutton(self.frame1, image=self.end_image, command=lambda: self.end(3)),
                           Radiobutton(self.frame2, image=self.end_image, command=lambda: self.end(4)),
                           Radiobutton(self.frame2, image=self.end_image, command=lambda: self.end(5)),
                           Radiobutton(self.frame2, image=self.end_image, command=lambda: self.end(6)),
                           Radiobutton(self.frame2, image=self.end_image, command=lambda: self.end(7)),
                           ]

        index = 0
        for each in self.end_button:
            each.grid(row=index % 4, column=5)
            each.config(value=2, variable=self.v[index], indicatoron=0)
            each.config(bg='brown3', activebackground='brown4')
            index += 1
        

    def make_frame(self):
        self.frame1.grid(row=2, column=0, rowspan=5)
        self.frame2.grid(row=2, column=1, rowspan=5)
        self.end_all_button.grid(row=1, column=0, columnspan=2)

        row = 0
        for each in self.lightsA:
            each.grid(row=row % 4, column=1, padx=20, pady=20)
            row += 1

        row = 0
        for each in self.lightsB:
            each.grid(row=row % 4, column=4, padx=20, pady=20)
            row += 1


    def delete_frame(self):
        self.frame1.grid_remove()
        self.frame2.grid_remove()
        self.end_all_button.grid_remove()

        for each in self.lightsA:
            each.grid_remove()

        for each in self.lightsB:
            each.grid_remove()

    def activate_a(self, number):
        pin_number = 65 + number
        pin_opposite = 80 - number

        if self.v[number].get() == 1:
            self.lightsA[number].set_state(True)
            self.lightsB[number].set_state(False)
            
            wiringpi.digitalWrite(pin_number, 1)
            wiringpi.digitalWrite(pin_opposite, 0)

    def activate_b(self, number):
        pin_number = 80 - number
        pin_opposite = 65 + number

        if self.v[number].get() == 0:
            self.lightsA[number].set_state(False)
            self.lightsB[number].set_state(True)
            wiringpi.digitalWrite(pin_number, 1)
            wiringpi.digitalWrite(pin_opposite, 0)
            

    def end(self, number):
        pin_number = 65 + number
        pin_opposite = 80 - number

        wiringpi.digitalWrite(pin_number, 0)
        wiringpi.digitalWrite(pin_opposite, 0)

        self.v[number].set(3)
        self.lightsA[number].set_state(False)
        self.lightsB[number].set_state(False)

    def end_all(self):
        number = 0
        while number < 8:
            self.end(number)
            number += 1