Exemplo n.º 1
0
 def build_widgets(self):
     "Build the various widgets that will be used in the program."
     # Create processing frame widgets.
     self.processing_frame = LabelFrame(self, text='Processing Mode:')
     self.mode_var = StringVar(self, 'encode')
     self.decode_button = Radiobutton(self.processing_frame,
                                      text='Decode Cipher-Text',
                                      command=self.handle_radiobuttons,
                                      value='decode',
                                      variable=self.mode_var)
     self.encode_button = Radiobutton(self.processing_frame,
                                      text='Encode Plain-Text',
                                      command=self.handle_radiobuttons,
                                      value='encode',
                                      variable=self.mode_var)
     self.freeze_var = BooleanVar(self, False)
     self.freeze_button = Checkbutton(self.processing_frame,
                                      text='Freeze Key & Primer',
                                      command=self.handle_checkbutton,
                                      offvalue=False,
                                      onvalue=True,
                                      variable=self.freeze_var)
     # Create encoding frame widgets.
     self.encoding_frame = LabelFrame(self, text='Encoding Options:')
     self.chain_size_label = Label(self.encoding_frame, text='Chain Size:')
     self.chain_size_entry = Entry(self.encoding_frame)
     self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:')
     self.plain_text_entry = Entry(self.encoding_frame)
     # Create input frame widgets.
     self.input_frame = LabelFrame(self, text='Input Area:')
     self.input_text = ScrolledText(self.input_frame, **self.TEXT)
     # Create output frame widgets.
     self.output_frame = LabelFrame(self, text='Output Area:')
     self.output_text = ScrolledText(self.output_frame, **self.TEXT)
Exemplo n.º 2
0
    def _addNeueMahlzeitFrame(self):
        self.fr_neue_mz = Frame(self.fr_mahlzeit)
        self.fr_neue_mz.grid_rowconfigure(2, weight=1)
        self.fr_neue_mz.grid(row=0, column=1, sticky="WSNE")
        
        lbl_name = Label(self.fr_neue_mz, text="Name:")
        lbl_name.grid(row=0, column=0, sticky="NW")
        
        self.en_name = Entry(self.fr_neue_mz)
        self.en_name.grid(row=0, column=1, columnspan=2, sticky="WNE")
        
        lbl_zutat = Label(self.fr_neue_mz, text="Zutaten:")
        lbl_zutat.grid(row=1, column=0, sticky="NW")
        

        self.lb_zutat = Listbox(self.fr_neue_mz)
        sb_zutat = Scrollbar(self.lb_zutat, orient=VERTICAL)
        self.lb_zutat.configure(yscrollcommand=sb_zutat.set)
        sb_zutat.configure(command=self.lb_zutat.yview)
        sb_zutat.pack(side="right", fill="both")
        self.lb_zutat.grid(row=2, column=0, columnspan=3, sticky="NWSE")
        
        self.var_zutat = StringVar(self.fr_neue_mz)
        
        self.opt_zutat = OptionMenu(self.fr_neue_mz, self.var_zutat, "Auswahl")
        self.opt_zutat.grid(row=3, column=0)
        
        self.en_menge = Entry(self.fr_neue_mz)
        self.en_menge.grid(row=3, column=1)
        
        self.btn_mahlzeit_hinzu = Button(self.fr_neue_mz, text="Hinzu")
        self.btn_mahlzeit_hinzu.grid(row=3, column=2, sticky="E")
Exemplo n.º 3
0
class DlgDelay(Dialog):
    def body(self, master, cfg={}):
        "place user dialog widgets"
        self.config = cfg
        self.config["OK button"] = False
        self.delay = StringVar()
        self.delay.set(cfg.get("delay", ""))
        self.edelay = Entry(master, width=15, textvariable=self.delay)
        self.edelay.grid(column=1, row=0, sticky="e")
        Label(master, text=_("Delay:")).grid(column=0, row=0, sticky="w")
        self.resizable(width=0, height=0)
        return self.edelay

    def validate(self):
        try:
            flt = float(self.delay.get())
        except ValueError:
            return self.edelay
        if flt < 0 or flt > 5:
            return self.edelay
        return None

    def apply(self):
        "On ok button pressed"
        self.config["delay"] = self.delay.get()
        self.config["OK button"] = True
Exemplo n.º 4
0
    def initUI(self):
        self.parent.title("Pi computation")
        self.pack(fill=BOTH, expand=True)

        self.grid_columnconfigure(4, weight=1)
        self.grid_rowconfigure(3, weight=1)

        lbl1 = Label(self, text="Digits:")
        lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10)

        self.ent1 = Entry(self, width=10)
        self.ent1.insert(END, "4000")
        self.ent1.grid(row=0, column=1, sticky=W)

        lbl2 = Label(self, text="Accuracy:")
        lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10)

        self.ent2 = Entry(self, width=10)
        self.ent2.insert(END, "100")
        self.ent2.grid(row=0, column=3, sticky=W)

        self.startBtn = Button(self, text="Start",
                               command=self.onStart)
        self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W)

        self.pbar = Progressbar(self, mode='indeterminate')
        self.pbar.grid(row=1, column=1, columnspan=3, sticky=W+E)

        self.txt = scrolledtext.ScrolledText(self)
        self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5,
                      columnspan=5, sticky=E+W+S+N)
    def add_file_info_box(self, mainframe, name, labeldict, btncallback, fvar):
        """
        Create and add a infobox containing the info about a loaded
        savegame.
        """
        title = {'source':'Copy face from source file:',
                 'target':'To target file:'}
        frame = LabelFrame(mainframe, text=title[name])
        frame.pack(anchor=N, fill=X, expand=1, side=TOP, padx=0, pady=0)
        frame.columnconfigure(1, weight=1)

        btn = Button(frame, text='Browse', command=btncallback)
        btn.grid(column=0, row=0, padx=2, pady=2)

        field = Entry(frame, width=50, textvariable=fvar)
        field.grid(column=1, row=0, columnspan=2, padx=2, pady=2, sticky=W+E)

        l = ('name','gender','level','race','location','save number','playing time')
        for n, (i, j) in enumerate([(x.capitalize()+':', x) for x in l]):
            Label(frame, text=i, state=DISABLED).grid(column=0, row=n+1, padx=4,
                                                      pady=3, sticky=E)
            labeldict[j] = StringVar()
            Label(frame, textvariable=labeldict[j]).grid(column=1, row=n+1,
                                                     padx=4, pady=3, sticky=W)
        self.screenshot[name] = Label(frame)
        self.screenshot[name].grid(column=2, row=1, rowspan=len(l),
                                   padx=4, pady=4)
Exemplo n.º 6
0
class Form(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent

        self.parent.title("Example Form")
        self.pack(fill=BOTH, expand=True)

        f = Frame(self)
        f.pack(fill=X)

        l = Label(f, text='First Name', width=10)
        l.pack(side=LEFT, padx=5, pady=5)
       
        self.firstName = Entry(f)
        self.firstName.pack(fill=X, padx=5, expand=True)
        
        f = Frame(self)
        f.pack(fill=X)
        
        l = Label(f, text='Last Name', width=10)
        l.pack(side=LEFT, padx=5, pady=5)

        self.lastName = Entry(f)
        self.lastName.pack(fill=X, padx=5, expand=True)
        
        f = Frame(self)
        f.pack(fill=X)

        l = Label(f, text='Full Name', width=10)
        l.pack(side=LEFT, padx=5, pady=5)

        self.fullName = Label(f, text='ALEX POOPKIN', width=10)
        self.fullName.pack(fill=X, padx=5, expand=True)

        f = Frame(self)
        f.pack(fill=X)

        l = Label(f, text='', width=10)
        l.pack(side=LEFT, padx=5, pady=0)

        self.errorMessage = Label(f, text='Invalid character int the name!', foreground='red', width=30)
        self.errorMessage.pack(fill=X, padx=5, expand=True)

        f = Frame(self)
        f.pack(fill=X)

        b = Button(f, text='Close', command=lambda : self.parent.quit())
        b.pack(side=RIGHT, padx=5, pady=10)
        b['default'] = ACTIVE
        b.focus_set()

        self.clearButton = Button(f, text='Clear')
        self.clearButton.pack(side=RIGHT, padx=5, pady=10)
        self.clearButton['state'] = DISABLED

        self.sendButton = Button(f, text='Send')
        self.sendButton.pack(side=RIGHT, padx=5, pady=10)
Exemplo n.º 7
0
 def insert_entry_field(self, txt):
     frame = Frame(self.frame)
     frame.pack(fill="x")
     label = Label(frame, text=txt, width=6)
     label.pack(side="left", anchor="n", padx=5, pady=5)
     entry = Entry(frame)
     entry.pack(fill="x", padx=5, pady=5, expand=True)
     self.entries["Entry"][txt] = entry
Exemplo n.º 8
0
    def initUI(self):

        self.parent.title("Book Manager")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)
        self.rowconfigure(5, pad=3)
        self.rowconfigure(6, pad=3)


        self.input_bname=''
        self.input_aname=''
        self.input_price=0
        self.delete=''

        lb_bookname = Label(self, text="bookname:")
        lb_bookname.grid(row=0, column =0 ,sticky=W, pady=4, padx=5)

        self.entry_bookname = Entry(self)
        self.entry_bookname.grid(row=0, column = 1 )

        lb_author = Label(self, text="author:")
        lb_author.grid(row=0, column =2,sticky=W, pady=4, padx=5)

        self.entry_author = Entry(self)
        self.entry_author.grid(row=0, column = 3 )


        lb_price = Label(self, text="price:")
        lb_price.grid(row=0, column =4 ,sticky=W, pady=4, padx=5)

        self.entry_price = Entry(self)
        self.entry_price.grid(row=0, column = 5 ,padx=15)


        abtn = Button(self, text="Add", command=lambda:self.clicked_add())
        abtn.grid(row=0, column=6)

        sbtn = Button(self, text="Serach", command = lambda:self.clicked_search())
        sbtn.grid(row=1, column=6, pady=4)

        dbtn = Button(self, text="Delete", command = lambda:self.clicked_delete())
        dbtn.grid(row=2, column=6, pady=4)

        self.lb = Listbox(self)

        self.lb.grid(row=3,column = 0, columnspan = 6,rowspan= 4, sticky = E+W+S+N)
        self.lb.bind("<<ListboxSelect>>", self.onSelect)
Exemplo n.º 9
0
 def apagar_caracter_invalido(evento_char, ref_entry: ttk.Entry, caracteres_inválidos: str):
     """ Método estático para apagar os caracteres inseridos em um Entry no momento da digitação(evento Release).
     Pode ser usado sem instanciação.
     :param evento_char: event.char do evento.
     :param ref_entry: Referência do componente Entry.
     :param caracteres_inválidos: string de caracteres que deseja-se que sejam apagados.
     :return: none. """
     if evento_char in caracteres_inválidos:
         ref_entry.delete(len(ref_entry.get()) - 1, 'end')
Exemplo n.º 10
0
class Main(Frame):
    """Main class for our browser.
        Note that we inherit from Frame, making this a Frame object.
    """
    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.master.title("Browser")
        self.header = {"User-Agent":"Tkinter Browser 0.1"}

        # Here we make our widgets.
        self.top_frame = Frame(self)
        self.url_frame = Frame(self.top_frame)
        self.url_label = Label(self.url_frame, text="Url: ", anchor="n")
        self.url_entry = Entry(self.url_frame, width=80)
        self.url_button = Button(self.url_frame, text="Go", command=self.go_button)
        self.bottom_frame = Frame(self)
        self.text_field = Text(self.bottom_frame)

        #Here we pack our widgets.
        self.top_frame.pack(side="top", padx=15, pady=15)
        self.url_frame.pack(anchor="center")
        self.bottom_frame.pack(side="bottom", fill="both", expand=True)
        self.text_field.pack(side="bottom", fill="both", expand=True)
        self.url_label.pack(side="left")
        self.url_entry.pack(side="left", fill="x", expand=True)
        self.url_button.pack(side="left", padx=5)
        self.text_field.config(state="disabled", padx=5, pady=5)

    def go_button(self):
        url = self.url_entry.get()
        if url:
            if "http://" not in url:
                url = "http://"+url
            page_text = self.get_page(url)
            self.text_field.config(state="normal")
            self.text_field.delete(1.0, "end")
            self.text_field.insert("end", page_text)
            self.text_field.config(state="disable")

    def get_page(self, url):
        s = requests.Session()
        resp = s.get(url, headers=self.header)
        data = resp.text
        soup = bs(data, "html.parser")
        page_text = soup.find_all(text=True)
        page_text = filter(self.visible, page_text)
        return "".join([str(i)+'\n' for i in page_text])


    def visible(self, e):
        if e.parent.name in ('style', 'script', '[document]', 'head', 'title'):
            return False
        elif re.match('<!--.*-->', str(e.encode('utf-8'))):
            return False
        return True
Exemplo n.º 11
0
 def body(self, master, cfg={}):
     "place user dialog widgets"
     self.config = cfg
     self.config["OK button"] = False
     self.site = StringVar()
     self.site.set(cfg.get("site", ""))
     self.login = StringVar()
     self.login.set(cfg.get("user", ""))
     self.password = StringVar()
     self.password.set(str(cfg.get("password", "")))
     site = Entry(master, width=15, textvariable=self.site)
     site.grid(column=1, row=0, sticky="e")
     Label(master, text=_("Site:")).grid(column=0, row=0, sticky="w")
     loge = Entry(master, width=15, textvariable=self.login)
     loge.grid(column=1, row=1, sticky="e")
     Label(master, text=_("Username:"******"w")
     pase = Entry(master, width=15, textvariable=self.password, show="*")
     pase.grid(column=1, row=2, sticky="e")
     Label(master, text=_("Password:"******"w")
     self.to_remember = IntVar()
     self.to_remember.set(cfg.get("remember_passwd", 1))
     chk1 = Checkbutton(master, text="Remember",
                        variable=self.to_remember)
     chk1.grid(column=0, row=3, sticky="w", columnspan=2)
     self.resizable(width=0, height=0)
     return loge
Exemplo n.º 12
0
    def make_entry(self, label_text, var):
        '''Return (entry, label), .

        entry - gridded labeled Entry for text entry.
        label - Label widget, returned for testing.
        '''
        label = Label(self.top, text=label_text)
        label.grid(row=self.row, column=0, sticky="nw")
        entry = Entry(self.top, textvariable=var, exportselection=0)
        entry.grid(row=self.row, column=1, sticky="nwe")
        self.row = self.row + 1
        return entry, label
Exemplo n.º 13
0
 def initialize_ui(self):
   default_padding = {'padx': 10, 'pady' : 10}
   
   labels = ["Name", "Surname", "Email",  "Cellphone"]
   for label in labels:
     frame = Frame(self)
     Label(frame, text = label, style="BW.TLabel").pack(default_padding, side = LEFT)
     entry = Entry(frame)
     entry.pack(default_padding, side = RIGHT)
     self.entries.append(entry)
     frame.pack(expand = True, fill = "x", side = TOP)
     
   button_frame = Frame(self)
   Button(button_frame, text = "Create Customer", command =  self.save_customer).pack(default_padding)
   button_frame.pack(expand = True, fill = "x")
Exemplo n.º 14
0
    def create_widgets(self):  # Call from override, if any.
        # Bind to self widgets needed for entry_ok or unittest.
        self.frame = frame = Frame(self, padding=10)
        frame.grid(column=0, row=0, sticky='news')
        frame.grid_columnconfigure(0, weight=1)

        entrylabel = Label(frame, anchor='w', justify='left',
                           text=self.message)
        self.entryvar = StringVar(self, self.text0)
        self.entry = Entry(frame, width=30, textvariable=self.entryvar)
        self.entry.focus_set()
        self.error_font = Font(name='TkCaptionFont',
                               exists=True, root=self.parent)
        self.entry_error = Label(frame, text=' ', foreground='red',
                                 font=self.error_font)
        self.button_ok = Button(
                frame, text='OK', default='active', command=self.ok)
        self.button_cancel = Button(
                frame, text='Cancel', command=self.cancel)

        entrylabel.grid(column=0, row=0, columnspan=3, padx=5, sticky=W)
        self.entry.grid(column=0, row=1, columnspan=3, padx=5, sticky=W+E,
                        pady=[10,0])
        self.entry_error.grid(column=0, row=2, columnspan=3, padx=5,
                              sticky=W+E)
        self.button_ok.grid(column=1, row=99, padx=5)
        self.button_cancel.grid(column=2, row=99, padx=5)
Exemplo n.º 15
0
    def body( self, master ):
        """
        Override the empty ModalDialog.body function
            to set up the dialog how we want it.
        """
        from tkinter.ttk import Label, Entry

        Label( master, text="First:" ).grid( row=0 )
        Label( master, text="Second:" ).grid( row=1 )

        self.e1 = Entry( master )
        self.e2 = Entry( master )

        self.e1.grid( row=0, column=1 )
        self.e2.grid( row=1, column=1 )
        return self.e1 # initial focus
Exemplo n.º 16
0
    def __init__(self, url):
        self.url = url

        self.root = Tk()
        self.root.title("验证码")

        while True:
            try:
                image_bytes = urlopen(self.url).read()
                break
            except socket.timeout:
                print('获取验证码超时:%s\r\n重新获取.' % (self.url))
                continue
            except urllib.error.URLError as e:
                if isinstance(e.reason, socket.timeout):
                    print('获取验证码超时:%s\r\n重新获取.' % (self.url))
                    continue
        # internal data file
        data_stream = io.BytesIO(image_bytes)
        # open as a PIL image object
        self.pil_image = Image.open(data_stream)
        # convert PIL image object to Tkinter PhotoImage object
        self.tk_image = ImageTk.PhotoImage(self.pil_image)
        self.label = Label(self.root, image=self.tk_image, background='brown')
        self.label.pack(padx=5, pady=5)
        self.button = Button(self.root, text="刷新验证码", command=self.refreshImg)
        self.button.pack(padx=5, pady=5)

        randCodeLable = Label(self.root, text="验证码:")
        randCodeLable.pack(padx=5, pady=5)
        self.randCode = Entry(self.root)
        self.randCode.pack(padx=5, pady=5)

        self.loginButton = Button(self.root, text="登录", default=tkinter.ACTIVE)
        self.loginButton.pack(padx=5, pady=5)
Exemplo n.º 17
0
  def initUI(self):
    self.master.title("3D Printer - Add Customer")
    self.style = Style()

    default_padding = {'padx': 10, 'pady' : 10}

    #TODO change alignment    
    #Left frame for labels
    self.left_frame = Frame(self.master)
    
    self.name_label = Label(self.left_frame, text = "Name", style="BW.TLabel")
    self.name_label.pack(default_padding)

    self.surname_label = Label(self.left_frame, text = "Surname", style="BW.TLabel")
    self.surname_label.pack(default_padding)    

    self.email_label = Label(self.left_frame, text = "Email", style="BW.TLabel")
    self.email_label.pack(default_padding)

    self.cellphone_label = Label(self.left_frame, text = "Cellphone", style="BW.TLabel")
    self.cellphone_label.pack(default_padding)

    #Right frame for entries
    self.right_frame = Frame(self.master)
    
    self.name_entry = Entry(self.right_frame)
    self.name_entry.pack(default_padding)    

    self.surname_entry = Entry(self.right_frame)
    self.surname_entry.pack(default_padding)

    self.email_entry = Entry(self.right_frame)
    self.email_entry.pack(default_padding)

    self.cellphone_entry = Entry(self.right_frame)
    self.cellphone_entry.pack(default_padding)
    
    #Bottom frame for button
    self.button_frame = Frame(self.master)
    self.create_customer_button = Button(self.button_frame, text = "Create Customer", command = self.save_customer)
    self.create_customer_button.pack(default_padding)

    self.button_frame.pack(side = BOTTOM, fill = "x", expand = True)
    self.left_frame.pack(side = LEFT, expand = True, fill = "y")
    self.right_frame.pack(side = RIGHT, expand = True, fill = "y")

    self.frame.pack()
Exemplo n.º 18
0
 def add_entry(self, text):
     entry = Entry(self)
     entry.insert(0, ",".join(text))
     entry.pack(fill="both", expand=True)
     entry.config(state="readonly")
     self.bindings(entry)
     self.entries.append(entry)
Exemplo n.º 19
0
    def create_widgets(self):
        super().create_widgets()
        frame = self.frame
        pathlabel = Label(frame, anchor="w", justify="left", text="Help File Path: Enter URL or browse for file")
        self.pathvar = StringVar(self, self.filepath)
        self.path = Entry(frame, textvariable=self.pathvar, width=40)
        browse = Button(frame, text="Browse", width=8, command=self.browse_file)

        pathlabel.pack(anchor="w", padx=5, pady=3)
        self.path.pack(anchor="w", padx=5, pady=3)
        browse.pack(pady=3)
Exemplo n.º 20
0
 def body(self, master, cfg={}):
     "place user dialog widgets"
     self.config = cfg
     self.config["OK button"] = False
     self.delay = StringVar()
     self.delay.set(cfg.get("delay", ""))
     self.edelay = Entry(master, width=15, textvariable=self.delay)
     self.edelay.grid(column=1, row=0, sticky="e")
     Label(master, text=_("Delay:")).grid(column=0, row=0, sticky="w")
     self.resizable(width=0, height=0)
     return self.edelay
Exemplo n.º 21
0
    def __init__(self):
        Tk.__init__(self)
        self.title("uT to qBt convertor")

        #main frame
        self.main_frame = Frame(self, padding="3 3 12 12")
        self.main_frame.grid(column=0, row=0, sticky=(N, W, E, S))
        self.main_frame.columnconfigure(0, weight=1)
        self.main_frame.rowconfigure(0, weight=1)

        #uT part
        self.ut_data = StringVar()
        self.ut_label = Label(self.main_frame, text="uT data")
        self.ut_label.grid(column=0, row=1, sticky=(W))
        self.ut_entry = Entry(self.main_frame, width=100, textvariable=self.ut_data)
        self.ut_entry.grid(column=1, row=1, sticky=(W))
        self.ut_button = Button(self.main_frame, text="Browse", command=self.load_file)
        self.ut_button.grid(column=2, row=1)

        #qBt part
        self.qbt_folder = StringVar()
        self.qbt_label = Label(self.main_frame, text="qBt folder")
        self.qbt_label.grid(column=0, row=4, sticky=(W))
        self.qbt_entry = Entry(self.main_frame, width=100, textvariable=self.qbt_folder)
        self.qbt_entry.grid(column=1, row=4, sticky=(W))
        self.qbt_button = Button(self.main_frame, text="Browse", command=self.open_dir)
        self.qbt_button.grid(column=2, row=4, sticky=(W, E))


        #convertor
        self.convertor_button = Button(self.main_frame, text="Convert", command=self.convert,
                                       width=50)
        self.convertor_button.grid(column=1, columnspan=2, row=5)

        self.progress_bar = Progressbar(self.main_frame, orient=HORIZONTAL, length=300, mode="indeterminate")
        self.progress_bar.grid(column=1, columnspan=3, row=6)

        #set padding for each element
        for child in self.main_frame.winfo_children():
            child.grid_configure(padx=5, pady=5)
Exemplo n.º 22
0
    def initUI(self, mainFrame):
        """initialize the User Interface"""
        
        # styles
        style = Style()
        style.configure("GRN.TLabel", background="#ACF059")
        style.configure("GRN.TFrame", background="#ACF059")
        style.configure("BLK.TFrame", background="#595959")
        
        
        # create top frame
        topFrame = Frame(mainFrame, style="GRN.TFrame", padding=8)
        topFrame.pack(fill=BOTH, side=TOP)
        
        # create black border
        borderFrame = Frame(mainFrame, style="BLK.TFrame")
        borderFrame.pack(fill=BOTH, side=TOP)
        
        # create add player frame
        addPlayerFrame = Frame(mainFrame, padding=8)
        addPlayerFrame.pack(side=TOP)
        
        # create text field for add button
        self.nameFieldVar = StringVar()
        self.playerNameEntry = Entry(addPlayerFrame, textvariable = self.nameFieldVar)
        self.playerNameEntry.pack(side=LEFT)
        # create add player button
        addButton = Button(addPlayerFrame, text="Add player")
        addButton.pack(side=LEFT)
        
        # create choose game list
        self.currentGame = StringVar()
        self.currentGame.set(self.gameList[0])
        gameDropDown = OptionMenu(mainFrame, self.currentGame, self.gameList[0], *self.gameList)
        gameDropDown.pack(side=TOP)

        # create start game button
        startGameButton = Button(mainFrame, text="Start")
        
        startGameButton.bind("<Button-1>", self.startGame)
        startGameButton.pack(side=TOP)
        
        # create label and set text
        self.playerString = StringVar()
        self.playerString.set(self.buildPlayerHeaderString())
        headerLabel = Label(topFrame, textvariable=self.playerString, style="GRN.TLabel")
        headerLabel.pack(side=TOP)     
        addButton.bind("<Button-1>", self.onAddPlayerClick)
        self.playerNameEntry.bind("<Key>", self.onAddPlayerEnter)
        
        #set focus
        self.playerNameEntry.focus()
Exemplo n.º 23
0
 def insert_entry_field(self, txt, default=None, focus=False):
     frame = Frame(self.frame)
     frame.pack(fill="x")
     label = Label(frame, text=txt, width=6)
     label.pack(side="left", anchor="n", padx=5, pady=5)
     entry = Entry(frame)
     entry.pack(fill="x", padx=5, pady=5, expand=True)
     if default:
         entry.insert("end", default)
     if focus:
         entry.focus_force()
     self.entries["Entry"][txt] = entry
Exemplo n.º 24
0
 def _addNeueZutatFrame(self):
     fr_neue_zt = Frame(self.fr_zutaten)
     fr_neue_zt.grid(row=0, column=2,sticky="NWSE")
     
     lbl_name = Label(fr_neue_zt, text="Name:")
     lbl_name.grid(row=0, column=0, sticky="W")
     
     self.en_name_zt = Entry(fr_neue_zt)
     self.en_name_zt.grid(row=0, column=1, columnspan=2, sticky="WE")
     
     lbl_fett = Label(fr_neue_zt, text="Fett:")
     lbl_fett.grid(row=1, column=0, sticky="W")        
     
     self.en_fett = Entry(fr_neue_zt)
     self.en_fett.grid(row=1, column=1, columnspan=2)
     
     lbl_eiweiss = Label(fr_neue_zt, text="Eiweiss:")
     lbl_eiweiss.grid(row=2, column=0, sticky="W")        
     
     self.en_eiweiss = Entry(fr_neue_zt)
     self.en_eiweiss.grid(row=2, column=1, columnspan=2)
     
     lbl_kh = Label(fr_neue_zt, text="Kohlenhy.:")
     lbl_kh.grid(row=3, column=0, sticky="W")        
     
     self.en_kh = Entry(fr_neue_zt)
     self.en_kh.grid(row=3, column=1, columnspan=2)
     
     self.btn_zutat_insert = Button(fr_neue_zt, text="Hinzu")
     self.btn_zutat_insert.grid(row=4, column=1, sticky="E")
     
     self.btn_zutat_update = Button(fr_neue_zt, text="Update")
     self.btn_zutat_update.grid(row=5, column=1, sticky="E")
     
     self.btn_zutat_delete = Button(fr_neue_zt, text="Loeschen")
     self.btn_zutat_delete.grid(row=6, column=1, sticky="E")
Exemplo n.º 25
0
 def __init__(self, parent, url=None, buttonSEC=False, buttonRSS=False):
     super(DialogURL, self).__init__(parent)
     self.parent = parent
     parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
     dialogX = int(parentGeometry.group(3))
     dialogY = int(parentGeometry.group(4))
     self.accepted = False
     self.url = None
     self.transient(self.parent)
     self.title("Enter URL")
     self.urlVar = StringVar()
     self.urlVar.set(url if url is not None else "http://")
     
     frame = Frame(self)
     urlLabel = Label(frame, text=_("URL:"), underline=0)
     urlEntry = Entry(frame, textvariable=self.urlVar, width=60)
     urlEntry.focus_set()
     okButton = Button(frame, text=_("OK"), command=self.ok)
     cancelButton = Button(frame, text=_("Cancel"), command=self.close)
     if buttonSEC:
         usSecButton = Button(frame, text=_("SEC search"), command=self.usSec)
         usSecButton.grid(row=1, column=1, sticky=W, pady=3)
         ToolTip(usSecButton, text=_("Opens US SEC Edgar Company Search (in web browser)\n\n"
                                  "(1) Find the company in web browser,\n"
                                  "(2) Click 'documents' button for desired filing,\n"
                                  "(3) Find 'data files' panel, instance document row, 'document' column,\n"
                                  "(4) On instance document file name, right-click browser menu: 'copy shortcut',\n"
                                  "(5) Come back to this dialog window,\n"
                                  "(6) Ctrl-v (paste) shortcut into above URL text box,\n"
                                  "(7) Click ok button to load instance document"),
                                  wraplength=480)
     if buttonRSS:
         rssButton = Button(frame, text=_("SEC RSS"), command=self.rssFeed)
         rssButton.grid(row=1, column=1, pady=3)
         ToolTip(rssButton, text=_("Opens current US SEC Edgar RSS feed"),
                                  wraplength=480)
     urlLabel.grid(row=0, column=0, sticky=W, pady=3, padx=3)
     urlEntry.grid(row=0, column=1, columnspan=3, sticky=EW, pady=3, padx=3)
     okButton.grid(row=1, column=2, sticky=E, pady=3)
     ToolTip(okButton, text=_("Opens above URL from web cache, downloading to cache if necessary"), wraplength=240)
     cancelButton.grid(row=1, column=3, sticky=EW, pady=3, padx=3)
     ToolTip(cancelButton, text=_("Cancel operation"))
                 
     frame.grid(row=0, column=0, sticky=(N,S,E,W))
     frame.columnconfigure(1, weight=1)
     window = self.winfo_toplevel()
     window.columnconfigure(0, weight=1)
     self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
     
     self.bind("<Alt-u>", lambda *ignore: urlEntry.focus_set())
     self.bind("<Return>", self.ok)
     self.bind("<Escape>", self.close)
     
     self.protocol("WM_DELETE_WINDOW", self.close)
     self.grab_set()
     self.wait_window(self)
Exemplo n.º 26
0
    def create_widgets(self):  # Call from override, if any.
        frame = Frame(self, borderwidth=2, relief="sunken")
        label = Label(frame, anchor="w", justify="left", text=self.message)
        self.entry = Entry(frame, width=30)  # Bind name for entry_ok.
        self.entry.focus_set()

        buttons = Frame(self)  # Bind buttons for invoke in unittest.
        self.button_ok = Button(buttons, text="Ok", width=8, command=self.ok)
        self.button_cancel = Button(buttons, text="Cancel", width=8, command=self.cancel)

        frame.pack(side="top", expand=TRUE, fill="both")
        label.pack(padx=5, pady=5)
        self.entry.pack(padx=5, pady=5)
        buttons.pack(side="bottom")
        self.button_ok.pack(side="left", padx=5)
        self.button_cancel.pack(side="right", padx=5)
Exemplo n.º 27
0
 def __init__(self, master):
     """Make boxes, register callbacks etc."""
     Frame.__init__(self, master)
     self.label = Label(self, text="När är du född?")
     self.label.pack()
     self.entry_text = StringVar()
     self.entry_text.trace("w", lambda *args: self.onEntryChanged())
     self.entry = Entry(self, width=date_entry_width,
          textvariable=self.entry_text)
     self.entry.insert(0, "ÅÅÅÅ-MM-DD")
     self.entry.pack(pady=small_pad)
     self.button = Button(self, text="Uppdatera",
          command=lambda: self.onDateChanged())
     self.button.pack()
     self.entry.focus_set()
     self.entry.select_range(0, END)
     self.entry.bind("<Return>", lambda x: self.onDateChanged())
Exemplo n.º 28
0
class MyTestDialog( ModalDialog ):

    def body( self, master ):
        """
        Override the empty ModalDialog.body function
            to set up the dialog how we want it.
        """
        from tkinter.ttk import Label, Entry

        Label( master, text="First:" ).grid( row=0 )
        Label( master, text="Second:" ).grid( row=1 )

        self.e1 = Entry( master )
        self.e2 = Entry( master )

        self.e1.grid( row=0, column=1 )
        self.e2.grid( row=1, column=1 )
        return self.e1 # initial focus
    # end of MyTestDialog.apply


    def validate( self ):
        """
        Override the empty ModalDialog.validate function
            to check that the results are how we need them.
        """
        try: int( self.e1.get() ) and int( self.e2.get() )
        except ValueError:
            print( "ERROR: We need two valid integers!" )
            return False
        return True
    # end of MyTestDialog.validate


    def apply( self ):
        """
        Override the empty ModalDialog.apply function
            to process the results how we need them.
        """
        first = int( self.e1.get() )
        second = int( self.e2.get() )
        print( first, second ) # or something
        self.result = (first, second,)
Exemplo n.º 29
0
    def create_widgets(self):  # Call from override, if any.
        # Bind to self widgets needed for entry_ok or unittest.
        self.frame = frame = Frame(self, borderwidth=2, relief="sunken")
        entrylabel = Label(frame, anchor="w", justify="left", text=self.message)
        self.entryvar = StringVar(self, self.text0)
        self.entry = Entry(frame, width=30, textvariable=self.entryvar)
        self.entry.focus_set()

        buttons = Frame(self)
        self.button_ok = Button(buttons, text="Ok", default="active", width=8, command=self.ok)
        self.button_cancel = Button(buttons, text="Cancel", width=8, command=self.cancel)

        frame.pack(side="top", expand=True, fill="both")
        entrylabel.pack(padx=5, pady=5)
        self.entry.pack(padx=5, pady=5)
        buttons.pack(side="bottom")
        self.button_ok.pack(side="left", padx=5)
        self.button_cancel.pack(side="right", padx=5)
Exemplo n.º 30
0
    def create_widgets(self):
        super().create_widgets()
        frame = self.frame
        pathlabel = Label(frame, anchor='w', justify='left',
                          text='Help File Path: Enter URL or browse for file')
        self.pathvar = StringVar(self, self.filepath)
        self.path = Entry(frame, textvariable=self.pathvar, width=40)
        browse = Button(frame, text='Browse', width=8,
                        command=self.browse_file)
        self.path_error = Label(frame, text=' ', foreground='red',
                                font=self.error_font)

        pathlabel.grid(column=0, row=10, columnspan=3, padx=5, pady=[10,0],
                       sticky=W)
        self.path.grid(column=0, row=11, columnspan=2, padx=5, sticky=W+E,
                       pady=[10,0])
        browse.grid(column=2, row=11, padx=5, sticky=W+S)
        self.path_error.grid(column=0, row=12, columnspan=3, padx=5,
                             sticky=W+E)
Exemplo n.º 31
0
    def layout_components(self):
        self.pack(fill=tk.BOTH, expand=False, padx=PADX, pady=PADY)
        error_font = font.Font(family="Ariel", size=8)

        # Variables
        self.username = tk.StringVar()
        self.username.set("")

        self.password = tk.StringVar()
        self.password.set("")

        # Username Row
        user_Frame = Frame(self)
        user_Frame.pack(fill=tk.X)
        user_Label = Label(user_Frame, text="Username:"******"<FocusOut>", self.enable_sign_in)
        self.user_Entry.pack(fill=tk.X, padx=PADX, pady=PADY, expand=True)

        # Password Row
        pass_Frame = Frame(self)
        pass_Frame.pack(fill=tk.X)
        pass_Label = Label(pass_Frame, text="Password:"******"*")
        self.pass_Entry.bind("<FocusOut>", self.enable_sign_in)
        self.pass_Entry.pack(fill=tk.X, padx=PADX, pady=PADY, expand=True)

        # Error Row
        err_Frame = Frame(self)
        err_Frame.pack(fill=tk.X)
        self.err_Label = Label(err_Frame,
                               text="",
                               foreground="red",
                               font=error_font)
        self.err_Label.pack(side=tk.LEFT,
                            anchor="center",
                            expand=True,
                            padx=PADX,
                            pady=PADY)

        # Button Row
        button_Frame = Frame(self)
        button_Frame.pack(fill=tk.X)
        # Cancel Button
        cncl_Button = Button(button_Frame, text="Cancel", command=self.cancel)
        cncl_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False)
        # Sign in Button
        self.sgnn_Button = Button(button_Frame,
                                  text="Sign in",
                                  state="disabled",
                                  command=self._sign_in)
        self.sgnn_Button.pack(side=tk.RIGHT,
                              padx=PADX,
                              pady=PADY,
                              expand=False)

        # Register Row
        register_Frame = Frame(self)
        register_Frame.pack(fill=tk.X)
        register_Button = Button(register_Frame,
                                 text="Register",
                                 command=self._show_register)
        register_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False)
        register_Label = Label(register_Frame,
                               text="Not a Member of ExchangeGram?")
        register_Label.pack(side=tk.RIGHT, padx=PADX, pady=PADY)
Exemplo n.º 32
0
    def __init__(self, parent, txt=dict()):
        """Instanciating the output workbook."""
        self.parent = parent
        Frame.__init__(self)

        # subframe
        self.FrDb = Labelframe(self,
                               name="database",
                               text=txt.get("gui_fr2", "SGBD"))

        # DB variables
        self.opt_pgvw = IntVar(self.FrDb)  # able/disable PostGIS views
        self.host = StringVar(self.FrDb, "localhost")
        self.port = IntVar(self.FrDb, 5432)
        self.dbnb = StringVar(self.FrDb)
        self.user = StringVar(self.FrDb, "postgres")
        self.pswd = StringVar(self.FrDb)

        # Form widgets
        self.ent_H = Entry(self.FrDb, textvariable=self.host)
        self.ent_P = Entry(self.FrDb, textvariable=self.port, width=5)
        self.ent_D = Entry(self.FrDb, textvariable=self.dbnb)
        self.ent_U = Entry(self.FrDb, textvariable=self.user)
        self.ent_M = Entry(self.FrDb, textvariable=self.pswd, show="*")

        caz_pgvw = Checkbutton(
            self.FrDb,
            text=txt.get("gui_views", "Views enabled"),
            variable=self.opt_pgvw,
        )

        # Label widgets
        self.lb_H = Label(self.FrDb, text=txt.get("gui_host", "Host"))
        self.lb_P = Label(self.FrDb, text=txt.get("gui_port", "Port"))
        self.lb_D = Label(self.FrDb, text=txt.get("gui_db", "Database"))
        self.lb_U = Label(self.FrDb, text=txt.get("gui_user", "User"))
        self.lb_M = Label(self.FrDb, text=txt.get("gui_mdp", "Password"))
        # widgets placement
        self.ent_H.grid(row=1,
                        column=1,
                        columnspan=2,
                        sticky="NSEW",
                        padx=2,
                        pady=2)
        self.ent_P.grid(row=1,
                        column=3,
                        columnspan=1,
                        sticky="NSE",
                        padx=2,
                        pady=2)
        self.ent_D.grid(row=2,
                        column=1,
                        columnspan=1,
                        sticky="NSEW",
                        padx=2,
                        pady=2)
        self.ent_U.grid(row=2,
                        column=3,
                        columnspan=1,
                        sticky="NSEW",
                        padx=2,
                        pady=2)
        self.ent_M.grid(row=3,
                        column=1,
                        columnspan=3,
                        sticky="NSEW",
                        padx=2,
                        pady=2)
        self.lb_H.grid(row=1, column=0, sticky="NSEW", padx=2, pady=2)
        self.lb_P.grid(row=1, column=3, sticky="NSW", padx=2, pady=2)
        self.lb_D.grid(row=2, column=0, sticky="NSW", padx=2, pady=2)
        self.lb_U.grid(row=2, column=2, sticky="NSW", padx=2, pady=2)
        self.lb_M.grid(row=3, column=0, sticky="NSWE", padx=2, pady=2)
        caz_pgvw.grid(row=4, column=0, sticky="NSWE", padx=2, pady=2)

        # frame position
        self.FrDb.grid(row=3, column=1, sticky="NSWE", padx=2, pady=2)
Exemplo n.º 33
0
class SignInView(Frame):
    def __init__(self, master):
        super().__init__(master=master)
        self.layout_components()
        # Setup Callbacks
        self.show_register: Callable = None
        self.sign_in: Callable = None
        self.user_Entry.focus()

    def layout_components(self):
        self.pack(fill=tk.BOTH, expand=False, padx=PADX, pady=PADY)
        error_font = font.Font(family="Ariel", size=8)

        # Variables
        self.username = tk.StringVar()
        self.username.set("")

        self.password = tk.StringVar()
        self.password.set("")

        # Username Row
        user_Frame = Frame(self)
        user_Frame.pack(fill=tk.X)
        user_Label = Label(user_Frame, text="Username:"******"<FocusOut>", self.enable_sign_in)
        self.user_Entry.pack(fill=tk.X, padx=PADX, pady=PADY, expand=True)

        # Password Row
        pass_Frame = Frame(self)
        pass_Frame.pack(fill=tk.X)
        pass_Label = Label(pass_Frame, text="Password:"******"*")
        self.pass_Entry.bind("<FocusOut>", self.enable_sign_in)
        self.pass_Entry.pack(fill=tk.X, padx=PADX, pady=PADY, expand=True)

        # Error Row
        err_Frame = Frame(self)
        err_Frame.pack(fill=tk.X)
        self.err_Label = Label(err_Frame,
                               text="",
                               foreground="red",
                               font=error_font)
        self.err_Label.pack(side=tk.LEFT,
                            anchor="center",
                            expand=True,
                            padx=PADX,
                            pady=PADY)

        # Button Row
        button_Frame = Frame(self)
        button_Frame.pack(fill=tk.X)
        # Cancel Button
        cncl_Button = Button(button_Frame, text="Cancel", command=self.cancel)
        cncl_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False)
        # Sign in Button
        self.sgnn_Button = Button(button_Frame,
                                  text="Sign in",
                                  state="disabled",
                                  command=self._sign_in)
        self.sgnn_Button.pack(side=tk.RIGHT,
                              padx=PADX,
                              pady=PADY,
                              expand=False)

        # Register Row
        register_Frame = Frame(self)
        register_Frame.pack(fill=tk.X)
        register_Button = Button(register_Frame,
                                 text="Register",
                                 command=self._show_register)
        register_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False)
        register_Label = Label(register_Frame,
                               text="Not a Member of ExchangeGram?")
        register_Label.pack(side=tk.RIGHT, padx=PADX, pady=PADY)

    def _sign_in(self):
        if self.sign_in is not None:
            self.sign_in()

    def enable_sign_in(self, event):
        if self.username.get() != "" and self.password.get() != "":
            self.sgnn_Button.configure(state="normal")
        else:
            self.sgnn_Button.configure(state="disabled")

    def failed_sign_in(self):
        self.err_Label.configure(text="Username/Password Incorrect")

    def cancel(self):
        self.username.set("")
        self.password.set("")
        self.user_Entry.focus()

    def _show_register(self):
        if self.show_register is not None:
            self.cancel()
            self.show_register()
        else:
            pass
Exemplo n.º 34
0
class MainWindow(Frame):
    def __init__(self, parent):

        Frame.__init__(self, parent)
        self.parent = parent
        self.streamrate_name_array = {}
        self.streamrate_cb_array = {}
        self.streamDataRate_array = {}
        self.streamrate_edit_array = {}
        # you can change this one to make the GUI wider
        self.columns = 3
        self.initUI()

        self.parent.bind('<Return>', self.updateCombo)
        self.updateCombo()

    def updateCombo(self, event=None):
        totalBits = 0
        for frame_name in mavlink_streams_list:
            bits = 0
            for frame_boxes in frame_name[2]:
                temp = self.streamrate_name_array[frame_name[0]][
                    frame_boxes[0]].get()
                if (self.streamrate_cb_array[frame_name[0]][
                        frame_boxes[0]].get()):
                    bits = bits + (
                        8 * mavlink_message_lengths_dict[temp]
                    )  # convert number of bytes to number of bits
            datarate = float(self.streamrate_edit_array[frame_name[0]].get())
            tempDataBits = int(bits * datarate)
            self.streamDataRate_array[frame_name[0]].config(
                text=str(tempDataBits) + " bits/s")
            totalBits = int(totalBits + tempDataBits)
        self.end_total_data_rate_label.config(text="Total Data Rate is " +
                                              str(totalBits) + " bits/s")

    def initUI(self):

        self.parent.title("Calculate Mavlink UAV->GCS telemetry datarate")
        self.pack(fill=BOTH, expand=1)

        count = 0
        count_frame = 0
        count_row = 0
        for frame_name in mavlink_streams_list:
            child_frame = Frame(self, borderwidth=2, relief=RIDGE)
            child_frame.grid(row=count_row, column=count_frame % self.columns)
            if (count_frame % self.columns == self.columns - 1):
                count_row = count_row + 1
            count_frame = count_frame + 1

            frame_label = Label(child_frame,
                                text=frame_name[0] + " message stream")
            frame_label.pack(side=TOP)

            self.streamrate_name_array[frame_name[0]] = {}
            self.streamrate_cb_array[frame_name[0]] = {}

            comboFrame = Frame(child_frame)
            comboFrame.pack(side=LEFT)
            for frame_boxes in frame_name[2]:

                comboframe = Frame(comboFrame)
                comboframe.pack(side=TOP)

                combo = Combobox(
                    comboframe,
                    values=tuple(
                        mavlink_msg_temp
                        for mavlink_msg_temp in mavlink_message_lengths_dict))
                combo.grid(row=count, column=0)
                index = list(mavlink_message_lengths_dict.keys()).index(
                    frame_boxes[0])
                combo.current(index)

                var = IntVar()
                if (frame_boxes[1]):
                    var.set(1)
                else:
                    var.set(0)
                checkbox = Checkbutton(comboframe,
                                       variable=var,
                                       command=self.updateCombo)
                checkbox.grid(row=count, column=1)

                self.streamrate_name_array[frame_name[0]][
                    frame_boxes[0]] = combo
                self.streamrate_cb_array[frame_name[0]][frame_boxes[0]] = var

                combo.bind("<<ComboboxSelected>>", self.updateCombo)
                count = count + 1

            streamrate_frame = Frame(child_frame)
            streamrate_frame.pack(side=TOP, anchor=CENTER)
            data_rate_label = Label(streamrate_frame, text="Stream Rate")
            data_rate_label.pack()

            self.data_rate_edit = Entry(streamrate_frame, width=2)
            self.data_rate_edit.insert(0, frame_name[1])
            self.streamrate_edit_array[frame_name[0]] = self.data_rate_edit
            self.data_rate_edit.pack(side=LEFT, anchor=CENTER)

            unit_Label = Label(streamrate_frame, text="Hz")
            unit_Label.pack(side=RIGHT, anchor=CENTER)

            datarate_frame = Frame(child_frame)
            datarate_frame.pack(side=TOP, anchor=CENTER)
            total_data_rate_label = Label(datarate_frame, text="Data Rate")
            total_data_rate_label.pack(side=TOP, anchor=CENTER)
            self.total_data_rate_answer = Label(datarate_frame,
                                                text="   bits/s")
            self.total_data_rate_answer.pack(side=TOP, anchor=CENTER)
            self.streamDataRate_array[
                frame_name[0]] = self.total_data_rate_answer

        self.end_total_data_rate_label = Label(self.parent,
                                               text="Total Data Rate")
        self.end_total_data_rate_label.pack(side=TOP)
class Window(Frame):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        """
        Function defines basic layout of whole program.
        """

        # Start instances atributes
        self.master.title("Image Compare")
        self.pack(fill=BOTH, expand=1)
        self.listOfPaths = []
        self.lenght = 0
        self.i = 0
        self.directory1 = "C:\\Plots1"
        self.directory2 = "C:\\Plots2"

        Style().configure("TFrame", background="#333")

        # Defining entrys, lables and text fields
        self.path1 = Entry(self, width=50)
        self.path1.place(x=10, y=10)

        self.path2 = Entry(self, width=50)
        self.path2.place(x=10, y=35)

        self.startFromEntry = Entry(self, width=5)
        self.startFromEntry.place(x=550, y=10)

        self.plot1PathText = Text(self, height=3, width=75)
        self.plot1PathText.place(x=620, y=670)

        self.plot2PathText = Text(self, height=3, width=75)
        self.plot2PathText.place(x=1230, y=670)

        self.lb = Listbox(self, height=15, width=100)
        self.lb.place(x=620, y=740)

        self.numberOfPlotsText = Text(self, height=1, width=5)
        self.numberOfPlotsText.place(x=790, y=10)

        self.currentPlotsText = Text(self, height=1, width=5)
        self.currentPlotsText.place(x=930, y=10)

        numberOfPlotsLabel = Label(self, text="Nuber of plots:")
        numberOfPlotsLabel.place(x=700, y=10)

        currentPlotsLabel = Label(self, text="Current plot:")
        currentPlotsLabel.place(x=850, y=10)

        # Defining buttons
        previousButton = Button(self,
                                text="Previous",
                                command=self.previousButtonFunction)
        previousButton.place(x=10, y=670)

        nextButton = Button(self, text="Next", command=self.nextButtonFunction)
        nextButton.place(x=100, y=670)

        differentButton = Button(self,
                                 text="Different",
                                 command=self.differentButtonFunction)
        differentButton.place(x=300, y=670)

        deleteButton = Button(self,
                              text="Delete",
                              command=self.deleteButtonFunction)
        deleteButton.place(x=380, y=670)

        getPathButton = Button(self,
                               text="Get Path",
                               command=self.get_filepaths)
        getPathButton.place(x=350, y=8)

        startFromButton = Button(self,
                                 text="Start From",
                                 command=self.startFromButtonFunction)
        startFromButton.place(x=600, y=8)

    #Defining messageboxes
    def onNoPlot(self):
        string = self.listOfPaths[self.i]
        string = string.replace(self.directory1, self.directory2)
        mbox.showerror("Error", "There is no plot {}".format(string))

    def onEqualPath(self):
        mbox.showerror("Error", "The same paths")

    def onLastPicture(self):
        mbox.showinfo("Last plot", "That is the last plot.")

    def onFirstPicture(self):
        mbox.showinfo("First plot", "That is the first plot.")

    # Defining buttons function
    def deleteButtonFunction(self):
        """
        deleteButton functionality, deleting item from listbox.
        """
        result = mbox.askquestion("Delete",
                                  "Delete highlighted item?",
                                  icon='warning')
        if result == 'yes':
            self.lb.delete(ANCHOR)  #self.lb is listbox
        else:
            return None

    def startFromButtonFunction(self):
        """
        startFromButton functionality, from which chart program is starting.
        """
        # Get value from entry
        a = int(self.startFromEntry.get()) - 1
        # Check if value is proper
        if a < 0 or a >= self.lenght:
            print("Wrong number")
        else:
            self.i = a
            self.picture(self.i)

    def nextButtonFunction(self):
        """
        nextButton functionality, next picture is choosen.
        """
        if self.i == self.lenght - 1:
            self.onLastPicture()
        else:
            self.i += 1
            self.picture(self.i)

    def previousButtonFunction(self):
        """
        previousButton functionality, previousPicture picture is choosen.
        """
        if self.i == 0:
            self.onFirstPicture()
        else:
            self.i -= 1
            self.picture(self.i)

    def differentButtonFunction(self):
        """
        differentButton functionality.
        """
        adr = self.listOfPaths[self.i]
        self.addToListbox(adr)

    def addToListbox(self, adr):
        """
        This function add path to listbox when charts are differentButton.

        Parameters:
        ----------
        adr: str
            Path to chart.
        """
        try:
            if adr in self.lb.get(0, END):
                return None
            else:
                self.lb.insert(0, adr)
        except TypeError:
            self.lb.insert(0, adr)

    def picture(self, adr):
        """
        This function creates three lables with pictures, first label show
        differences between pictures in next two labels.

        Parameters:
        ----------
        adr: str
            Path to chart.
        """
        adress_1 = self.listOfPaths[adr]
        adress_2 = adress_1.replace(self.directory1, self.directory2)

        file_img1 = Image.open(adress_1)
        try:
            file_img2 = Image.open(adress_2)
        except FileNotFoundError:
            adr = self.listOfPaths[self.i]
            self.addToListbox(adr)
            self.onNoPlot()
            return None

        self.fill_text_fields(adress_1, adress_2)
        diff = ImageChops.difference(file_img1, file_img2)
        diff = diff.resize((600, 600))
        diffjov = ImageTk.PhotoImage(diff)
        label1 = Label(self, image=diffjov)
        label1.image = diffjov
        label1.place(x=10, y=60)

        file_img1 = file_img1.resize((600, 600))
        image_2 = ImageTk.PhotoImage(file_img1)
        label2 = Label(self, image=image_2)
        label2.image = image_2
        label2.place(x=620, y=60)

        file_img2 = file_img2.resize((600, 600))
        image_3 = ImageTk.PhotoImage(file_img2)
        label3 = Label(self, image=image_3)
        label3.image = image_3
        label3.place(x=1230, y=60)

    def fill_text_fields(self, adr_1, adr_2):
        """
        This function is added plots pathes to labels and added curent plot
        number to label

        Parameters:
        ----------
        adr_1: str
            Path to chart.
        adr_2: str
             Path to chart.
        """
        self.plot1PathText.config(state="normal")
        self.plot1PathText.delete("1.0", END)
        self.plot1PathText.insert(INSERT, adr_1)
        self.plot1PathText.config(state="disabled")

        self.plot2PathText.config(state="normal")
        self.plot2PathText.delete("1.0", END)
        self.plot2PathText.insert(INSERT, adr_2)
        self.plot1PathText.config(state="disabled")

        self.currentPlotsText.config(state="normal")
        self.currentPlotsText.delete("1.0", END)
        self.currentPlotsText.insert(INSERT, self.i + 1)
        self.currentPlotsText.config(state="disabled")

    def get_filepaths(self):
        """
        This function will generate the file names in a directory
        tree by walking the tree either top-down or bottom-up. For each
        directory in the tree rooted at directory top (including top itself),
        it yields a 3-tuple (dirpath, dirnames, filenames).
        """
        self.directory1 = self.path1.get()
        self.directory2 = self.path2.get()
        if self.directory1 == self.directory2:
            self.onEqualPath()
            return None

        file_paths = []  # List which will store all of the full filepaths.
        self.i = 0

        # Walk the tree.
        for root, directories, files in os.walk(self.directory1):
            for filename in files:
                # Join the two strings in order to form the full filepath.
                filepath = os.path.join(root, filename)
                file_paths.append(filepath)  # Add it to the list.

        self.listOfPaths = file_paths
        self.lenght = len(file_paths)
        self.picture(self.i)
        self.numberOfPlotsText.insert(INSERT, self.lenght)
        self.numberOfPlotsText.config(state="disabled")

    def saveToFile(self):
        """
        This function write to file all elemens from listbox to file.
        """
        pathList = self.lb.get(0, END)
        currentPath = os.path.abspath(__file__)
        pathToSave = currentPath.split("\\")
        pathToSave[-1] = "path.txt"
        pathToSave.pop(-2)
        path = "\\".join(pathToSave)
        with open(path, "w") as fp:
            for item in pathList:
                fp.write(item + "\n")
Exemplo n.º 36
0
class UnrealAirSimGUI(multiprocessing.Process):
    
    def __init__(self, dataPipe, vehicle_names):
        multiprocessing.Process.__init__(self)
        self.dataPipe = dataPipe
        self.vehicle_names = vehicle_names
        self.WIDTH = 580
        self.HEIGHT = 500
        self.update_tracking_interval = 20
        self.start()
    
    def run(self):
        
    # 1/2 Configure the Individual GUI Tabs    
        print("Start GUI Setup!")
        
        self.root = tk.Tk() # The GUI
        self.root.title("Unreal Vehicle GUI")
        self.nb = Notebook(self.root)
        
        # Add Main Tab
        self.StateFrame = Frame(self.nb, width = self.WIDTH, height = self.HEIGHT) # Top of Gui 
        self.nb.add(self.StateFrame, text = "Vehicle State")
        
        # Get Notebook Gridded
        self.nb.grid(row = 0, column = 0)
        
        # Configure Video Tab
        self.VideoFrame = Frame(self.nb, width = self.WIDTH, height = self.HEIGHT)
        self.nb.add(self.VideoFrame, text = "Video Feed")
        
        # Configure Plotting Tab
        self.PlottingFrame = Frame(self.nb, width = self.WIDTH, height = self.HEIGHT)
        self.nb.add(self.PlottingFrame, text = "Track n' Map")
        self.fig = plt.figure(1, figsize= (4,4))
        self.ax = Axes3D(self.fig)
        self.last_3d_viz_x_pos = 0
        self.last_3d_viz_y_pos = 0
        self.last_3d_viz_z_pos = 0
        self.ax.scatter(self.last_3d_viz_x_pos,self.last_3d_viz_y_pos,self.last_3d_viz_z_pos)
        self.canvas = FigureCanvasTkAgg(self.fig, self.PlottingFrame)
        self.canvas.get_tk_widget().grid(row = 1, column = 0)
        
        # Configure Virtual IMU Tab:
        self.embed = tk.Frame(self.root, width = self.WIDTH, height = self.HEIGHT)
        self.nb.add(self.embed, text="Virtual IMU")
        os.environ['SDL_WINDOWID'] = str(self.embed.winfo_id())  #Tell pygame's SDL window which window ID to use
        
        # Start PYGAME for IMU Visualization
        pygame.init()
        self.screen = Screen(500,500, scale=1.5)
        self.cube = Cube(40,40,40)
        # END Initialization
        self.root.update()
        
    # 2/2 Configure the Labels and Entries on the GUI    
        # For Switch Vehicle Feeds
        self.current_vehicle_feed = tk.StringVar(self.StateFrame) # Linked to current vehicle choice
        self.switch_vehicle_feed = Combobox(self.StateFrame, textvariable = self.current_vehicle_feed)
        self.switch_vehicle_feed['values'] = self.vehicle_names
        self.switch_vehicle_feed.grid(row = 0, column = 3)
        self.switch_vehicle_feed.current(0)
        
        # Labels for state variables
        self.label_posx = Label(self.StateFrame, text = "PosX:")
        self.label_posy = Label(self.StateFrame, text = "PosY:")
        self.label_posz = Label(self.StateFrame, text = "PosZ:")
        self.label_velx = Label(self.StateFrame, text = "Vel X:")
        self.label_vely = Label(self.StateFrame, text = "Vel Y:")
        self.label_velz = Label(self.StateFrame, text = "Vel Z:")
        self.label_accx = Label(self.StateFrame, text = "Acc X:")
        self.label_accy = Label(self.StateFrame, text = "Acc Y:")
        self.label_accz = Label(self.StateFrame, text = "Acc Z:")
        self.label_rollrate = Label(self.StateFrame, text = "Roll Rate:")
        self.label_pitchrate = Label(self.StateFrame, text = "Pitch Rate:")
        self.label_yawrate = Label(self.StateFrame, text = "Yaw Rate:")
        self.label_angaccx = Label(self.StateFrame, text = "AngAcc X:")
        self.label_angaccy = Label(self.StateFrame, text = "AngAcc Y:")
        self.label_angaccz = Label(self.StateFrame, text = "AngAcc Z:")
        self.label_roll = Label(self.StateFrame, text = "Roll:")
        self.label_pitch = Label(self.StateFrame, text = "Pitch:")
        self.label_yaw = Label(self.StateFrame, text = "Yaw:")        
        
        # Assemble into grid -- No need to pack if you are using grid
        self.label_posx.grid(row = 0, column = 0)
        self.label_posy.grid(row = 1, column = 0)
        self.label_posz.grid(row = 2, column = 0)
        self.label_velx.grid(row = 3, column = 0)
        self.label_vely.grid(row = 4, column = 0)
        self.label_velz.grid(row = 5, column = 0)
        self.label_accx.grid(row = 6, column = 0)
        self.label_accy.grid(row = 7, column = 0)
        self.label_accz.grid(row = 8, column = 0)
        self.label_rollrate.grid(row = 9, column = 0)
        self.label_pitchrate.grid(row = 10, column = 0)
        self.label_yawrate.grid(row = 11, column = 0)
        self.label_angaccx.grid(row = 12, column = 0)
        self.label_angaccy.grid(row = 13, column = 0)
        self.label_angaccz.grid(row = 14, column = 0)
        self.label_roll.grid(row = 15, column = 0)
        self.label_pitch.grid(row = 16, column = 0)
        self.label_yaw.grid(row = 17, column = 0)
        
        # Entries for State Updates:
        self.entry_posx = Entry(self.StateFrame, text = "PosX:")
        self.entry_posy = Entry(self.StateFrame, text = "PosY:")
        self.entry_posz = Entry(self.StateFrame, text = "PosZ:")
        self.entry_velx = Entry(self.StateFrame, text = "Vel X:")
        self.entry_vely = Entry(self.StateFrame, text = "Vel Y:")
        self.entry_velz = Entry(self.StateFrame, text = "Vel Z:")
        self.entry_accx = Entry(self.StateFrame, text = "Acc X:")
        self.entry_accy = Entry(self.StateFrame, text = "Acc Y:")
        self.entry_accz = Entry(self.StateFrame, text = "Acc Z:")
        self.entry_roll = Entry(self.StateFrame, text = "Roll:")
        self.entry_pitch = Entry(self.StateFrame, text = "Pitch:")
        self.entry_yaw = Entry(self.StateFrame, text = "Yaw:")
        self.entry_rollrate = Entry(self.StateFrame, text = "Roll Rate:")
        self.entry_pitchrate = Entry(self.StateFrame, text = "Pitch Rate:")
        self.entry_yawrate = Entry(self.StateFrame, text = "Yaw Rate:")
        self.entry_angaccx = Entry(self.StateFrame, text = "AngAcc X:")
        self.entry_angaccy = Entry(self.StateFrame, text = "AngAcc Y:")
        self.entry_angaccz = Entry(self.StateFrame, text = "AngAcc Z:")

        # Entries Gridded
        self.entry_posx.grid(row = 0, column = 1)
        self.entry_posy.grid(row = 1, column = 1)
        self.entry_posz.grid(row = 2, column = 1)
        self.entry_velx.grid(row = 3, column = 1)
        self.entry_vely.grid(row = 4, column = 1)
        self.entry_velz.grid(row = 5, column = 1)
        self.entry_accx.grid(row = 6, column = 1)
        self.entry_accy.grid(row = 7, column = 1)
        self.entry_accz.grid(row = 8, column = 1)
        self.entry_roll.grid(row = 15, column = 1)
        self.entry_pitch.grid(row = 16, column = 1)
        self.entry_yaw.grid(row = 17, column = 1)
        self.entry_rollrate.grid(row = 9, column = 1)
        self.entry_pitchrate.grid(row = 10, column = 1)
        self.entry_yawrate.grid(row = 11, column = 1)
        self.entry_angaccx.grid(row = 12, column = 1)
        self.entry_angaccy.grid(row = 13, column = 1)
        self.entry_angaccz.grid(row = 14, column = 1)
        
        # Meta Data For the State Page
        self.entry_action = Entry(self.StateFrame, text = "Action")
        self.entry_action_name = Entry(self.StateFrame, text = "Action Name")
        self.entry_env_state = Entry(self.StateFrame, text = "Env State")
        self.entry_mode = Entry(self.StateFrame, text = "GUI Mode")
        self.entry_act_time = Entry(self.StateFrame, text = "Action Time")
        self.entry_sim_image_time = Entry(self.StateFrame, text = "Sim Image Get Time")
        self.entry_sim_state_time = Entry(self.StateFrame, text = "Sim State Get Time")
        self.entry_reward_time = Entry(self.StateFrame, text = "Sim Calc Reward Time")
        self.entry_step_time = Entry(self.StateFrame, text = "Step Time")
        self.entry_reward = Entry(self.StateFrame, text = "Reward")
        self.entry_done = Entry(self.StateFrame, text = "Done Flag")
        
        
        self.label_action = Label(self.StateFrame, text = "Action:")
        self.label_action_name = Label(self.StateFrame, text = "Action Name:")
        self.label_env_state = Label(self.StateFrame, text = "Env State:")
        self.label_mode = Label(self.StateFrame, text = "GUI Mode:")
        self.label_act_time = Label(self.StateFrame, text = "Action Time:")
        self.label_sim_image_time = Label(self.StateFrame, text = "Sim Image Get Time:")
        self.label_sim_state_time = Label(self.StateFrame, text = "Sim State Get Time:")
        self.label_reward_time = Label(self.StateFrame, text = "Calc Reward Time:")
        self.label_step_time = Label(self.StateFrame, text = "Env Step Time:")
        self.label_reward = Label(self.StateFrame, text = "Reward:")
        self.label_done = Label(self.StateFrame, text = "Done:")
        
        # Grid Meta Data Display
        self.label_action.grid(row = 5, column = 2)
        self.label_action_name.grid(row = 6, column = 2)
        self.label_env_state.grid(row = 7, column = 2)
        self.label_mode.grid(row = 8, column = 2)
        self.label_act_time.grid(row = 9, column = 2)
        self.label_sim_image_time.grid(row = 10, column = 2)
        self.label_sim_state_time.grid(row = 11, column = 2)
        self.label_reward_time.grid(row = 12, column = 2)
        self.label_step_time.grid(row = 13, column = 2)
        self.label_reward.grid(row = 14, column = 2)
        self.label_done.grid(row = 15, column = 2)
        
        self.entry_action.grid(row = 5, column = 3)
        self.entry_action_name.grid(row = 6, column = 3)
        self.entry_env_state.grid(row = 7, column = 3)
        self.entry_mode.grid(row = 8, column = 3)
        self.entry_act_time.grid(row = 9, column = 3)
        self.entry_sim_image_time.grid(row = 10, column = 3)
        self.entry_sim_state_time.grid(row = 11, column = 3)
        self.entry_reward_time.grid(row = 12, column = 3)
        self.entry_step_time.grid(row = 13, column = 3)
        self.entry_reward.grid(row = 14, column = 3)
        self.entry_done.grid(row = 15, column = 3)
        
        # Initialize the Vehicle's Virtual IMU Visualization
        self.label_yaw = Label(self.embed, text = "Yaw:")
        self.label_pitch = Label(self.embed, text = "Pitch:")
        self.label_roll = Label(self.embed, text = "Roll:")
        self.label_yaw.place(x=500,y = 0) # Place the Labels on the far right of the frame
        self.label_pitch.place(x=500, y = 50)
        self.label_roll.place(x=500, y = 100)
        
        self.entry_imu_yaw = Entry(self.embed, text = "Yaw:")
        self.entry_imu_pitch = Entry(self.embed, text = "Pitch:")
        self.entry_imu_roll = Entry(self.embed, text = "Roll:")
        self.entry_yaw.place(x = 500, y = 25)
        self.entry_pitch.place(x = 500, y = 75)
        self.entry_roll.place(x = 500, y = 125)
        
        print("GUI Setup DONE!")
        t_upd = threading.Thread(target = self.updates)
        t_upd.start()
        self.root.mainloop()
        

    
    def updates(self):
        time.sleep(1.5)
        while True:
            # Data comes in as a dictionary of 'obs', 'state', 'meta'
            data = self.dataPipe.recv()
            vehicle_name = self.current_vehicle_feed.get()
            # Run the inertial update thread
            self.t_states = threading.Thread(target = self.update_inertial_states, 
                                             args = (data[vehicle_name]['state'],))
            self.t_states.start() # Start Updater thread by setting the event
            # Run the Image Data thread
            self.t_imgs = threading.Thread(target = self.update_image_feeds,
                                           args = (data[vehicle_name]['obs'],))
            self.t_imgs.start()
            # Run the meta data update
            self.t_meta = threading.Thread(target = self.update_metas,
                                            args = (data[vehicle_name]['meta'],))
            self.t_meta.start()
            
            self.t_v_imu_viz = threading.Thread(target = self.update_virtual_imu_visualization,
                                                args = (data[vehicle_name]['state'],))
            self.t_v_imu_viz.start()
            
            self.t_3d_track_viz = threading.Thread(target = self.update_object_3DVisualization, 
                                                   args = (data[vehicle_name]['state'],))
            self.t_3d_track_viz.start()
            
            # Join Threads
            self.t_states.join()
            self.t_imgs.join()
            self.t_meta.join()
            self.t_v_imu_viz.join()
            self.t_3d_track_viz.join()
            
        
    def update_metas(self, data):
        meta = data
        self.entry_action_name.delete(0,tk.END)
        self.entry_action_name.insert(0,str(meta['action_name']))
        self.entry_action.delete(0,tk.END)
        self.entry_action.insert(0,str(meta['action']))
        self.entry_env_state.delete(0,tk.END)
        self.entry_env_state.insert(0,str(meta['env_state']))
        self.entry_mode.delete(0,tk.END)
        self.entry_mode.insert(0,str(meta['mode']))
        self.entry_act_time.delete(0, tk.END)
        self.entry_act_time.insert(0, str(meta['times']['act_time']))
        self.entry_sim_image_time.delete(0,tk.END)
        self.entry_sim_image_time.insert(0,str(meta['times']['sim_img_time']))
        self.entry_sim_state_time.delete(0,tk.END)
        self.entry_sim_state_time.insert(0,str(meta['times']['sim_state_time']))
        self.entry_reward_time.delete(0,tk.END)
        self.entry_reward_time.insert(0,str(meta['times']['reward_time']))
        self.entry_step_time.delete(0, tk.END)
        self.entry_step_time.insert(0, str(meta['times']['step_time']))
        self.entry_reward.delete(0, tk.END)
        self.entry_reward.insert(0, str(meta['reward']))
        self.entry_done.delete(0, tk.END)
        self.entry_done.insert(0, str(meta['done']))

    def update_image_feeds(self, data):
        scalar = 3
        col_count = 0
        row_count = 0
        
        sim_images = data
        print("GUI Image Update:")
        start_time = time.time()
        
        for key in sim_images:
            if len(sim_images[key][0]) > 0:
                
        
        
        for i in range(self.num_video_feeds):
            sim_image = sim_images[:,:,scalar*i:scalar*(i+1)]
            if scalar == 1:
                sim_image = np.reshape(sim_image, (sim_image.shape[0], sim_image.shape[1]))
            if ((i % 3) == 0):
                col_count = 0
                row_count += 1
            #print('sim image shape ', sim_image.shape, type(sim_image), sim_image, self.isNormal)
            if self.isNormal:
                sim_image = np.array(sim_image * 255, dtype = np.uint8)
            else:
                sim_image = np.array(sim_image, dtype = np.uint8)
            img = Image.fromarray(sim_image)
            imgtk = ImageTk.PhotoImage(image = img)
            if self.VideoFeeds[i] is None: # Initialize the image panel
                self.VideoFeeds[i] = Label(self.VideoFrame, image=imgtk)
                self.VideoFeeds[i].image = imgtk
                self.VideoFeeds[i].grid(row = row_count, column = col_count)
            else:
                self.VideoFeeds[i].configure(image = imgtk)
                self.VideoFeeds[i].image = imgtk
            col_count += 1
        col_count = 0
        row_count = 0
        print("Feed Update Time: ", time.time() - start_time)
    

    
    def update_inertial_states(self, data):
            #print(current_inertial_states)
            current_inertial_state = data
            quatx, quaty, quatz, quatw = current_inertial_state[15:]
            yaw, pitch, roll = SO3Rotation.quaternion_to_euler_angles((quatw, quatx, quaty, quatz))

            print('GUI State Update!')
            start_time = time.time()
            #print(current_inertial_states, current_inertial_state)
            self.entry_posx.delete(0,tk.END)
            self.entry_posx.insert(0, str(current_inertial_state[0]))
            self.entry_posy.delete(0,tk.END)
            self.entry_posy.insert(0, str(current_inertial_state[1]))
            self.entry_posz.delete(0,tk.END)
            self.entry_posz.insert(0, str(current_inertial_state[2]))
            self.entry_velx.delete(0,tk.END)
            self.entry_velx.insert(0, str(current_inertial_state[3]))
            self.entry_vely.delete(0,tk.END)
            self.entry_vely.insert(0, str(current_inertial_state[4]))
            self.entry_velz.delete(0,tk.END)
            self.entry_velz.insert(0, str(current_inertial_state[5]))
            self.entry_accx.delete(0,tk.END)
            self.entry_accx.insert(0, str(current_inertial_state[6]))
            self.entry_accy.delete(0,tk.END)
            self.entry_accy.insert(0, str(current_inertial_state[7]))
            self.entry_accz.delete(0,tk.END)
            self.entry_accz.insert(0, str(current_inertial_state[8]))
            self.entry_roll.delete(0,tk.END)
            self.entry_roll.insert(0, str(roll))
            self.entry_pitch.delete(0,tk.END)
            self.entry_pitch.insert(0, str(pitch))
            self.entry_yaw.delete(0,tk.END)
            self.entry_yaw.insert(0, str(yaw))
            self.entry_rollrate.delete(0,tk.END)
            self.entry_rollrate.insert(0, str(current_inertial_state[9]))
            self.entry_pitchrate.delete(0,tk.END)
            self.entry_pitchrate.insert(0, str(current_inertial_state[10]))
            self.entry_yawrate.delete(0,tk.END)
            self.entry_yawrate.insert(0, str(current_inertial_state[11]))
            self.entry_angaccx.delete(0,tk.END)
            self.entry_angaccx.insert(0, str(current_inertial_state[12]))
            self.entry_angaccy.delete(0,tk.END)
            self.entry_angaccy.insert(0, str(current_inertial_state[13]))
            self.entry_angaccz.delete(0,tk.END)
            self.entry_angaccz.insert(0, str(current_inertial_state[14]))
            print('GUI State Update Time! ', time.time() - start_time)        
             

    def update_virtual_imu_visualization(self, data):

        quatx = data[15]
        quaty = data[16]
        quatz = data[17]
        quatw = data[18]
        yaw, pitch, roll = SO3Rotation.quaternion_to_euler_angles((quatw, quatx, quaty, quatz))
        self.entry_yaw.delete(0,tk.END)
        self.entry_yaw.insert(0, str(yaw))
        self.entry_pitch.delete(0,tk.END)
        self.entry_pitch.insert(0, str(pitch))
        self.entry_roll.delete(0,tk.END)
        self.entry_roll.insert(0, str(roll))
        q = Quaternion(quatw, quatx, quaty, quatz).normalized()
        self.cube.draw(self.screen,q)
        event = pygame.event.poll()
        pygame.display.flip()
        pygame.time.delay(10) # ms
        self.cube.erase(self.screen)
        #TKINTER
        self.root.update()

    def update_object_3DVisualization(self, data):
        if self.update_tracking_interval % 20 == 0:
            print("RUNNING 3D VISULIZATION")
            print(data[0], data[1], data[2])
            xpos = data[0]
            ypos = data[1]
            zpos = data[2]
            self.ax.plot3D([self.last_3d_viz_x_pos, xpos],
                           [self.last_3d_viz_y_pos,ypos],
                           zs = [self.last_3d_viz_z_pos, zpos])
            self.ax.scatter(xpos, ypos, zpos, color = 'green')
            self.canvas.draw()
            
            self.last_3d_viz_x_pos = xpos
            self.last_3d_viz_y_pos = ypos
            self.last_3d_viz_z_pos = zpos
        self.update_tracking_interval += 1
Exemplo n.º 37
0
    def __init__(self, tab_control, username, user_controller, expense_tab):
        """Initializes the preferences tab, where the user can customise the application, with all visual elements"""
        # create preference tab with title 'Preferences'
        self.preferences_tab = ttk.Frame(tab_control)
        tab_control.add(self.preferences_tab, text='Preferences')

        self.expense_tab = expense_tab
        self.username = username
        self.user_controller = user_controller

        # Category list is saved as list variable and as StringVar instance:
        # The list represents the custom categories of the user and is loaded from the database,
        # the StringVar is the TK representation and is the object containing the values for the Listbox
        self.category_list = self.user_controller.get_categories(self.username)
        self.category_var = StringVar(value=self.category_list)

        # Previously set budget is loaded from the database
        new_category = StringVar()
        b, p = self.user_controller.get_budget(self.username)
        budget = StringVar(value=b)
        chosen_period = StringVar(value=p)

        Label(self.preferences_tab,
              text="Your categories:",
              font='Helvetica 16 bold').grid(row=0,
                                             column=0,
                                             padx=15,
                                             pady=15,
                                             sticky='w')

        y_scroll = Scrollbar(self.preferences_tab, orient='vertical')
        y_scroll.grid(row=1, column=0, pady=15, padx=(0, 15), sticky='nse')
        listbox = Listbox(self.preferences_tab,
                          listvar=self.category_var,
                          yscrollcommand=y_scroll.set,
                          bd=0,
                          height=15)
        listbox.grid(row=1, column=0, padx=(15, 0), pady=15, sticky='w')
        y_scroll['command'] = listbox.yview

        Button(self.preferences_tab, text='Remove', command=lambda: self.remove_category(listbox), style='W.TButton')\
            .grid(row=1, column=1, padx=15, pady=15, sticky='s')

        Label(self.preferences_tab, text='Add category:').grid(row=2,
                                                               column=0,
                                                               padx=15,
                                                               sticky='w')
        Entry(self.preferences_tab,
              textvariable=new_category).grid(row=3,
                                              column=0,
                                              padx=15,
                                              sticky='ew')
        Button(self.preferences_tab,
               text='Add',
               command=lambda: self.add_category(new_category)).grid(row=3,
                                                                     column=1)

        Label(self.preferences_tab, text="Set yourself a budget!", font='Helvetica 16 bold')\
            .grid(row=6, column=0, padx=(15, 0), pady=20, sticky='w')

        Entry(self.preferences_tab, textvariable=budget).grid(row=7,
                                                              column=0,
                                                              padx=(15, 0),
                                                              sticky='w')
        Label(self.preferences_tab, text='€').grid(row=7, column=0, sticky='e')
        OptionMenu(self.preferences_tab, chosen_period, p,
                   *period_list).grid(row=7, column=1)
        Button(self.preferences_tab, text='Set budget', command=lambda: self.set_budget(budget, chosen_period))\
            .grid(row=7, column=2)
Exemplo n.º 38
0
    def showChanSettings(self, value, return_index):

        self.center = Frame(root,
                            bg=config.bgcolor,
                            width=50,
                            height=40,
                            padx=3,
                            pady=3)

        # layout all of the main containers
        root.grid_rowconfigure(1, weight=1)
        root.grid_columnconfigure(0, weight=1)
        self.center.grid(row=1, sticky="nsew")
        # set header label
        self.HeaderTitle.configure(text=value + " Channel Settings")

        #set center frame
        channelData = database.get_channel_info(value, 0)
        # feedArray = get_feed(channelData[3])

        ##########
        ## top menu

        linklabel = Label(self.center,
                          text=value + " URL-->",
                          fg="blue",
                          bg=config.bgcolor,
                          cursor="hand2",
                          font=("Arial Bold", 12))
        linklabel.grid(column=0, row=0)
        linklabel.bind(
            "<Button-1>", lambda e: self.callback(config.YTPrefix +
                                                  channelData[3] + "/videos"))
        #get_feed(channelData[3])
        rssbtn = Button(
            self.center,
            text=value + " RSS-->",
            bg=config.bgcolor,
            fg="blue",
            cursor="hand2",
            font=("Arial Bold", 12),
            command=lambda: self.show_feed(self.center, channelData[3]))
        rssbtn.grid(column=1, row=0)

        updateChanBtn = Button(
            self.center,
            text="Update Channel",
            fg="green",
            font=("Arial Bold", 12),
            command=lambda: self.open_new_window(channelData[3]))
        updateChanBtn.grid(column=2, row=0, columnspan=3)

        ##########
        ## channel info
        chanlbl = Label(self.center,
                        text="Enter Channel URL",
                        bg=config.bgcolor,
                        font=("Arial", config.fontSize))
        chanlbl.grid(column=0, row=1, sticky=left)

        channelString = Entry(self.center, width=config.textBoxWidth)
        channelString.insert(END, channelData[3])
        channelString.grid(column=1, columnspan=3, row=1)

        chanNameLbl = Label(self.center,
                            text="Channel Name",
                            bg=config.bgcolor,
                            font=("Arial", config.fontSize))
        chanNameLbl.grid(column=0, row=2, sticky=left)
        channelName = Entry(self.center, width=config.textBoxWidth)
        channelName.insert(END, channelData[1])
        channelName.grid(column=1, columnspan=3, row=2)

        channelDirLbl = Label(self.center,
                              text="Channel Directory",
                              bg=config.bgcolor,
                              font=("Arial", config.fontSize))
        channelDirLbl.grid(column=0, row=3, sticky=left)
        channelDirTxt = Entry(self.center, width=config.textBoxWidth)
        channelDirTxt.insert(END, channelData[2])
        channelDirTxt.grid(column=1, columnspan=3, row=3)

        ct = database.get_video_count(channelData[3])

        ##########
        ## bottom buttons
        showVidsBtn = Button(self.center,
                             text="Show Downloaded " + "(" + ct + ")",
                             fg="Blue",
                             bg=config.bgcolor,
                             font=("Arial", config.fontSize),
                             command=lambda: self.menudo(
                                 "List Videos chan=" + value, self.center))
        showVidsBtn.grid(column=0, row=4, pady=3, sticky=left)
        archive = channelData[6]
        if archive == 0:
            arcbutton = Button(self.center,
                               text="Archive Channel",
                               fg="Blue",
                               bg=config.bgcolor,
                               font=("Arial", config.fontSize),
                               command=lambda: self.menudo(
                                   "Archive Channel", channelData[3], 1))
            arcbutton.grid(column=1, row=4, pady=3)
        else:
            arcbutton = Button(self.center,
                               text="UnArchive Channel",
                               fg="Blue",
                               bg=config.bgcolor,
                               font=("Arial", config.fontSize),
                               command=lambda: self.menudo(
                                   "Archive Channel", channelData[3], 0))
            arcbutton.grid(column=1, row=4, pady=3)

        delbutton = Button(
            self.center,
            text="Delete Channel",
            fg="Blue",
            bg=config.bgcolor,
            font=("Arial", config.fontSize),
            command=lambda: self.menudo("Delete Channel", channelData[1],
                                        channelData[6]))
        delbutton.grid(column=2, row=4, pady=3)

        btn = Button(self.center,
                     text="Return",
                     fg="Blue",
                     bg=config.bgcolor,
                     font=("Arial", config.fontSize),
                     command=lambda: self.menudo("List Channels", return_index,
                                                 channelData[6]))
        btn.grid(column=3, row=4, pady=3)

        savebtn = Button(self.center,
                         text="Save",
                         fg="Blue",
                         bg=config.bgcolor,
                         font=("Arial", config.fontSize),
                         command=lambda: self.update_channel_settings(
                             channelData[0], channelString, channelName,
                             channelDirTxt, channelData[1]))
        savebtn.grid(column=4, row=4, pady=3)
Exemplo n.º 39
0
    def initUI(self):

        self.parent.title("Calculate Mavlink UAV->GCS telemetry datarate")
        self.pack(fill=BOTH, expand=1)

        count = 0
        count_frame = 0
        count_row = 0
        for frame_name in mavlink_streams_list:
            child_frame = Frame(self, borderwidth=2, relief=RIDGE)
            child_frame.grid(row=count_row, column=count_frame % self.columns)
            if (count_frame % self.columns == self.columns - 1):
                count_row = count_row + 1
            count_frame = count_frame + 1

            frame_label = Label(child_frame,
                                text=frame_name[0] + " message stream")
            frame_label.pack(side=TOP)

            self.streamrate_name_array[frame_name[0]] = {}
            self.streamrate_cb_array[frame_name[0]] = {}

            comboFrame = Frame(child_frame)
            comboFrame.pack(side=LEFT)
            for frame_boxes in frame_name[2]:

                comboframe = Frame(comboFrame)
                comboframe.pack(side=TOP)

                combo = Combobox(
                    comboframe,
                    values=tuple(
                        mavlink_msg_temp
                        for mavlink_msg_temp in mavlink_message_lengths_dict))
                combo.grid(row=count, column=0)
                index = list(mavlink_message_lengths_dict.keys()).index(
                    frame_boxes[0])
                combo.current(index)

                var = IntVar()
                if (frame_boxes[1]):
                    var.set(1)
                else:
                    var.set(0)
                checkbox = Checkbutton(comboframe,
                                       variable=var,
                                       command=self.updateCombo)
                checkbox.grid(row=count, column=1)

                self.streamrate_name_array[frame_name[0]][
                    frame_boxes[0]] = combo
                self.streamrate_cb_array[frame_name[0]][frame_boxes[0]] = var

                combo.bind("<<ComboboxSelected>>", self.updateCombo)
                count = count + 1

            streamrate_frame = Frame(child_frame)
            streamrate_frame.pack(side=TOP, anchor=CENTER)
            data_rate_label = Label(streamrate_frame, text="Stream Rate")
            data_rate_label.pack()

            self.data_rate_edit = Entry(streamrate_frame, width=2)
            self.data_rate_edit.insert(0, frame_name[1])
            self.streamrate_edit_array[frame_name[0]] = self.data_rate_edit
            self.data_rate_edit.pack(side=LEFT, anchor=CENTER)

            unit_Label = Label(streamrate_frame, text="Hz")
            unit_Label.pack(side=RIGHT, anchor=CENTER)

            datarate_frame = Frame(child_frame)
            datarate_frame.pack(side=TOP, anchor=CENTER)
            total_data_rate_label = Label(datarate_frame, text="Data Rate")
            total_data_rate_label.pack(side=TOP, anchor=CENTER)
            self.total_data_rate_answer = Label(datarate_frame,
                                                text="   bits/s")
            self.total_data_rate_answer.pack(side=TOP, anchor=CENTER)
            self.streamDataRate_array[
                frame_name[0]] = self.total_data_rate_answer

        self.end_total_data_rate_label = Label(self.parent,
                                               text="Total Data Rate")
        self.end_total_data_rate_label.pack(side=TOP)
Exemplo n.º 40
0
def save_record():
    # Obtener la información de los widgets de entrada y colocarla en la estructura de datos
    print(txt_name.get())


root = Tk()

root.geometry('350x400')
root.title('Registro de participantes')

frm_name = Frame(root)
Label(frm_name, text="Nombre").pack(side=LEFT)
txt_name = StringVar()
Entry(frm_name, textvariable=txt_name).pack(side=LEFT,
                                            padx=10,
                                            fill=X,
                                            expand=1)
frm_name.pack(fill=X, padx=10, pady=10)

frm_lastname = Frame(root)
Label(frm_lastname, text="Apellidos").pack(side=LEFT)
txt_lastname = StringVar()
Entry(frm_lastname, textvariable=txt_lastname).pack(side=LEFT,
                                                    padx=10,
                                                    fill=X,
                                                    expand=1)
frm_lastname.pack(fill=X, padx=10, pady=10)

frm_emails = Frame(root)
Label(frm_emails, text="Correos electrónicos").pack(anchor=W)
Exemplo n.º 41
0
class DaxModelParameter():
    '''The UI elements and logic to set model parameter values.

    For this application; all model parameters are assumed to be
    floats (or ints cast to floats). Strings and Logicals need not
    apply.
    '''
    def __init__(self, parent, label_frame, sherpa_model_parameter):
        '''Create model parameter UI element'''
        self.sherpa_par = sherpa_model_parameter
        self.parent = parent
        self.label_frame = label_frame
        self.initial_value = {
            'val': self.sherpa_par.val,
            'min': self.sherpa_par.min,
            'max': self.sherpa_par.max
        }
        self.render_ui()

    def _freeze_thaw(self):
        '''ACTION: set the freeze() or thaw() based on the
        checkbox value.'''
        if 1 == self.fz_box.get():
            self.sherpa_par.freeze()
        else:
            self.sherpa_par.thaw()

    @staticmethod
    def __format_val(val):
        'Format parameter values'
        retval = "{:.5g}".format(val)
        return retval

    def reset(self):
        """Reset values to original"""
        for field in ['max', 'min', 'val']:
            to_mod = getattr(self, field)
            to_mod.delete(0, END)
            to_mod.insert(0, self.__format_val(self.initial_value[field]))
            to_mod.configure(foreground="black")
            setattr(self.sherpa_par, field, self.initial_value[field])

    def update(self):
        """Reset values to original"""
        for field in ['max', 'min', 'val']:
            to_mod = getattr(self, field)
            newval = getattr(self.sherpa_par, field)
            to_mod.delete(0, END)
            to_mod.insert(0, self.__format_val(newval))
            # ~ to_mod.configure(foreground="black")
            # ~ setattr(self.sherpa_par, field, self.initial_value[field])

    def entry_callback(self, keyevt, field):
        '''ACTION: set the model parameter value when the user
        type <<Return>>.  Otherwise, when user edits value
        it turns red so user knows it hasn't been set yet.

        All values are cast|set to doubles.

        There is no validation in the UI against the min|max
        values.  Sherpa raises an exception if you try to go beyond
        the limits so the color remains red until valid value is
        entered.
        '''
        from sherpa.utils.err import ParameterErr

        # Note: use .char instead of .keysym because Return
        # and Enter on the keypad are different keysym's but both
        # generate CR. This makes sense since can remap keyboard
        # keys -- the action we want is CR, whichever key generates it.
        # Update: Unfortunately the .char field is cleared
        # in newer versions of python in the KeyRelease callback, and
        # the Key callback doesn't work (order of callback doesn't change
        # text color correctly).  So, I'm back to using the keysym.

        to_mod = getattr(self, field)

        if keyevt.keysym in ['Return', 'KP_Enter', 'Enter']:
            try:
                fval = float(to_mod.get())
                setattr(self.sherpa_par, field, fval)
                to_mod.configure(foreground="black")
                to_mod.last_value = to_mod.get()
            except (ValueError, ParameterErr) as val_err:
                messagebox.showerror("DAX Model Editor", str(val_err))

        else:
            if to_mod.get() != to_mod.last_value:
                to_mod.configure(foreground="red")

    def render_ui(self):
        '''Render the parameter UI elements and attach bindings'''

        row = self.parent.get_row()
        win = self.label_frame

        # The parameter name
        lab = Label(win, text=self.sherpa_par.name, width=12, anchor="e")
        lab.grid(row=row, column=0, padx=(5, 5), pady=2)

        # The current parameter value
        self.val_str = StringVar()
        self.val = Entry(win,
                         textvariable=self.val_str,
                         foreground="black",
                         width=12,
                         justify="right")
        self.val.grid(row=row, column=1, padx=(5, 5), pady=2)
        self.val.delete(0, END)
        self.val.insert(0, self.__format_val(self.sherpa_par.val))
        self.val.last_value = self.val.get()
        self.val.bind("<KeyRelease>",
                      lambda x: self.entry_callback(x, field='val'))

        # Frozen|Thawed checkbox.  Checked if frozen.
        self.fz_box = IntVar()
        if self.sherpa_par.frozen is True:
            self.fz_box.set(1)
        else:
            self.fz_box.set(0)
        fzbtn = Checkbutton(win,
                            text="",
                            variable=self.fz_box,
                            command=self._freeze_thaw)
        fzbtn.grid(row=row, column=2, padx=(5, 5), pady=2)

        # The min value
        self.min_str = StringVar()
        self.min = Entry(win,
                         textvariable=self.min_str,
                         foreground="black",
                         width=12,
                         justify="right")
        self.min.grid(row=row, column=3, padx=(5, 5), pady=2)
        self.min.delete(0, END)
        self.min.insert(0, self.__format_val(self.sherpa_par.min))
        self.min.last_value = self.min.get()
        self.min.bind("<KeyRelease>",
                      lambda x: self.entry_callback(x, field='min'))

        # The max value
        self.max_str = StringVar()
        self.max = Entry(win,
                         textvariable=self.max_str,
                         foreground="black",
                         width=12,
                         justify="right")
        self.max.grid(row=row, column=4, padx=(5, 5), pady=2)
        self.max.delete(0, END)
        self.max.insert(0, self.__format_val(self.sherpa_par.max))
        self.max.last_value = self.max.get()
        self.max.bind("<KeyRelease>",
                      lambda x: self.entry_callback(x, field='max'))

        # The units of the parameter
        par_units = Label(win,
                          text="{}".format(self.sherpa_par.units),
                          width=20,
                          anchor="e")
        par_units.grid(row=row, column=5, padx=(5, 5), pady=2)
Exemplo n.º 42
0
class Main_Window(Frame):

    def __init__(self, parent):

        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar, tearoff=False)
        fileMenu.add_command(label="Open CSV's for EN", command=self.openCSVs)
        menubar.add_cascade(label="Files", menu=fileMenu)

        self.parent.title('PM_allInOne')
        self.pack()
        topFrame = Frame(self.parent)
        topFrame.pack(side='top', anchor='nw')
        bottomFrame = Frame(self.parent)
        bottomFrame.pack(side='top', anchor='nw')
        self.entrySaveBatch = Entry(topFrame)
        self.entrySaveBatch.pack(anchor='nw', fill='both')
        buttonSaveBatch = tk.Button(topFrame, 
                                    text="DL-Save", 
                                    width=8, 
                                    command=self.DLbatchSave)
        buttonSaveBatch.pack(side='left')
        buttonSendBatch = tk.Button(topFrame, 
                                    text="DL-Reply", 
                                    width=8, 
                                    command=self.DLbatchSend)
        buttonSendBatch.pack(side='left')
        buttonSaveKFD = tk.Button(bottomFrame, 
                                  text="Save KFD", 
                                  width=8, 
                                  command=self.convertXMLFiles)
        buttonSaveKFD.pack(side='left')
        buttonTest = tk.Button(bottomFrame, 
                                 text="Evening", 
                                 width=8, 
                                 command=self.evening_routines)
        buttonTest.pack(side='left')

    def openCSVs(self):

        Super_Duper = os.path.expanduser('~\Documents\SUPER DUPER\\')
        if not os.path.exists(Super_Duper):
            os.makedirs(Super_Duper)

        if getattr(sys, 'frozen', False):
            script_dir = os.path.dirname(sys.executable)
        elif __file__:
            script_dir = os.path.dirname(__file__)

        ftypes = [("Comma Seperated Values", "*.csv")]
        csvs = tk.filedialog.askopenfilenames(filetypes=ftypes)
        # fl = dlg.show()
        tempA = []
        if csvs != "":
            obj = EN_Attachment.exchange_notice(script_dir)
            for oneFile in csvs:
                tempA.append(obj.getData(oneFile))
            wb = obj.openWorkbook()
            n = 2
            for elem in tempA:
                obj.fillTemplate(wb, elem, n)
                n += 1
            obj.saveWorkbook(wb, Super_Duper)

    def evening_routines(self):

        file = r'\\SE10ORGFPS01\Clearing & Custody Services\1. Product Management\Listing Management\New strikes\Evening Strikes.xlsx'
        eveningO = matchingAlgorithm.matchingAlgorithm(file)

        if eveningO.generatedAmount != eveningO.matchedAmount:
            errorText = ('{0} matched from {1} generated'.
                         format(eveningO.matchedAmount, eveningO.generatedAmount))
            messagebox.showinfo('ERROR', errorText)

    def DLbatchSave(self):

        if self.entrySaveBatch.get() != '':
            recordID = self.entrySaveBatch.get()
            
            batch = Reply_DL.BatchingSTO_Message(recordID)
            batch.getAttachments()

    def DLbatchSend(self):

        # determine if application is a script file or frozen exe
        if getattr(sys, 'frozen', False):
            script_dir = os.path.dirname(sys.executable)
        elif __file__:
            script_dir = os.path.dirname(__file__)


        if self.entrySaveBatch.get() != '':
            recordID = self.entrySaveBatch.get()

            rel_path = '\Messages\Trading_Codes.txt'
            abs_file_path = script_dir + rel_path

            # print (abs_file_path)

            with open(abs_file_path, 'r') as f:
                text = f.read()
            
            batch = Reply_DL.BatchingSTO_Message(recordID)
            batch.getAttachments()
            batch.replyMessage(text, batch.getxlsxLocation())
            batch.createTask()

    def convertXMLFiles(self):

        xmlFilesSave = Reply_DL.BatchingDK_Message()
        for xmlFile in xmlFilesSave.xmlFileLocations:
            file = xmlConverter.NewCsvToOldCsv(xmlFile)
            file.readNewCsv()
            file.csvGenerator()
Exemplo n.º 43
0
    def init_ui(self):
        """ setup the GUI for the app """
        self.master.title("Test")
        self.pack(fill=BOTH, expand=True)

        # Input section
        input_frame = LabelFrame(self, text="Input")
        input_frame.bind("-", self.on_minus_key)
        input_frame.bind("+", self.on_plus_key)
        input_frame.pack(fill=X)
        self.play_button = Button(input_frame,
                                  text="Play",
                                  command=self.on_play_button_click)
        self.play_button.pack(side=RIGHT, padx=4)
        self.rec_button = Button(input_frame,
                                 text="Rec",
                                 command=self.on_rec_button_click)
        self.rec_button.pack(side=RIGHT, padx=4)
        self.wav_filename_entry = Entry(input_frame, width=24)
        self.wav_filename_entry.pack(fill=X)
        self.wav_filename_entry.delete(0, END)
        if self.wav_filename:
            self.wav_filename_entry.insert(0, self.wav_filename)

        # Feature section
        features_frame = LabelFrame(self, text="Features")
        features_frame.pack(fill=X)

        features_control_frame = Frame(features_frame)
        features_control_frame.pack(fill=X)
        load_features_button = Button(features_control_frame,
                                      text="Load",
                                      command=self.on_load_featurizer_model)
        load_features_button.pack(side=RIGHT)
        self.features_entry = Entry(features_control_frame, width=8)
        self.features_entry.pack(fill=X)
        self.features_entry.delete(0, END)
        if self.featurizer_model:
            self.features_entry.insert(0, self.featurizer_model)

        viz_frame = Frame(features_frame)
        viz_frame.pack(fill=X)
        self.features_figure = Figure(figsize=(5, 4), dpi=100)
        self.subplot = self.features_figure.add_subplot(111)

        canvas = FigureCanvasTkAgg(self.features_figure, master=viz_frame)
        canvas.draw()
        canvas.show()
        canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=True)

        # Classifier section
        classifier_frame = LabelFrame(self, text="Classifier")
        classifier_frame.pack(fill=X)
        load_classifier_button = Button(classifier_frame,
                                        text="Load",
                                        command=self.on_load_classifier)
        load_classifier_button.pack(side=RIGHT)
        self.classifier_entry = Entry(classifier_frame, width=8)
        self.classifier_entry.pack(fill=X)
        self.classifier_entry.delete(0, END)
        if self.classifier_model:
            self.classifier_entry.insert(0, self.classifier_model)

        # Output section
        output_frame = LabelFrame(self, text="Output")
        output_frame.pack(fill=BOTH, expand=True)

        self.output_text = Text(output_frame)
        self.output_text.pack(fill=BOTH, padx=4, expand=True)
Exemplo n.º 44
0
class AudioDemo(Frame):
    """ A demo application class that provides simple GUI for testing featurizer+classifier on 
    microphone or wav file input. """
    def __init__(self,
                 featurizer_model=None,
                 classifier_model=None,
                 sample_rate=None,
                 channels=None,
                 input_device=None,
                 categories=None,
                 image_width=80,
                 threshold=None,
                 wav_file=None,
                 clear=5):
        """ Initialize AudioDemo object
        featurizer_model - the path to the compiled ELL featurizer
        classifier_model - the path to the compiled ELL classifier
        sample_rate - sample rate to featurizer is expecting
        channels - number of channels featurizer is expecting
        input_device - optional id of microphone to use
        categories - path to file containing category labels
        image_width - width of the spectrogram image
        threshold - ignore predictions that have confidence below this number (e.g. 0.5)
        wav_file - optional wav_file to process when you click Play
        """
        super().__init__()

        self.CLASSIFIER_MODEL_KEY = "classifier_model"
        self.FEATURIZER_MODEL_KEY = "featurizer_model"
        self.WAV_FILE_KEY = "wav_file"
        self.CATEGORY_FILE_KEY = "categories"

        self.get_settings_file_name()
        self.load_settings()
        self.reading_input = False
        self.featurizer_model = None
        if featurizer_model:
            self.featurizer_model = featurizer_model
            self.settings[self.FEATURIZER_MODEL_KEY] = featurizer_model
        elif self.FEATURIZER_MODEL_KEY in self.settings:
            self.featurizer_model = self.settings[self.FEATURIZER_MODEL_KEY]

        self.classifier_model = None
        if classifier_model:
            self.classifier_model = classifier_model
            self.settings[self.CLASSIFIER_MODEL_KEY] = classifier_model
        elif self.CLASSIFIER_MODEL_KEY in self.settings:
            self.classifier_model = self.settings[self.CLASSIFIER_MODEL_KEY]

        self.wav_filename = wav_file
        if self.wav_filename is None and self.WAV_FILE_KEY in self.settings:
            self.wav_filename = self.settings[self.WAV_FILE_KEY]

        self.wav_file_list = None

        self.sample_rate = sample_rate if sample_rate is not None else 16000
        self.channels = channels if channels is not None else 1
        self.input_device = input_device
        self.num_classifier_features = None

        if not categories and self.CATEGORY_FILE_KEY in self.settings:
            categories = self.settings[self.CATEGORY_FILE_KEY]

        self.categories = categories
        if categories:
            self.settings[self.CATEGORY_FILE_KEY] = categories

        self.save_settings()  # in case we just changed it.
        self.min_value = 0.0
        self.max_value = 1.0
        self.update_minmax = True

        self.threshold = threshold

        self.output_clear_time = int(clear * 1000) if clear else 5000

        self.featurizer = None
        self.classifier = None
        self.wav_file = None
        self.speaker = None
        self.microphone = None
        self.animation = None
        self.show_spectrogram = True
        self.colormap_name = "inferno"
        self.show_classifier_output = True
        self.last_prediction = None
        self.probability = 0

        # Threads
        self.read_input_thread = None
        self.lock = Lock()
        self.main_thread = get_ident()
        self.message_queue = []

        # UI components
        self.max_spectrogram_width = image_width
        self.features_entry = None
        self.spectrogram_image = None
        self.classifier_feature_data = None
        self.spectrogram_image_data = None

        self.init_ui()

        if self.featurizer_model:
            self.load_featurizer_model(os.path.abspath(self.featurizer_model))
        else:
            self.show_output("Please specify and load a feature model")

        if self.classifier_model:
            self.load_classifier(self.classifier_model)
            self.setup_spectrogram_image()
        else:
            self.show_output("Please specify and load a classifier model")

    def get_settings_file_name(self):
        """ this app stores the various UI field values in a settings file in your temp folder 
        so you don't always have to specify the full command line options """
        import tempfile
        temp = tempfile.gettempdir()
        self.settings_file_name = os.path.join(temp, "ELL", "Audio",
                                               "viewaudio.json")

    def load_settings(self):
        """ load the previously saved settings from disk, if any """
        self.settings = {}
        if os.path.isfile(self.settings_file_name):
            with open(self.settings_file_name, "r") as f:
                self.settings = json.load(f)

    def save_settings(self):
        """ save the current settings to disk """
        settings_dir = os.path.dirname(self.settings_file_name)
        if not os.path.isdir(settings_dir):
            os.makedirs(settings_dir)
        with open(self.settings_file_name, "w") as f:
            f.write(json.dumps(self.settings))

    def load_featurizer_model(self, featurizer_model):
        """ load the given compiled ELL featurizer for use in processing subsequent audio input """
        if featurizer_model:
            self.featurizer = featurizer.AudioTransform(featurizer_model, 40)
            self.setup_spectrogram_image()

            self.show_output("Feature input size: {}, output size: {}".format(
                self.featurizer.input_size, self.featurizer.output_size))
            if self.features_entry.get() != featurizer_model:
                self.features_entry.delete(0, END)
                self.features_entry.insert(0, featurizer_model)

        self.init_data()

    def load_classifier(self, classifier_path):
        """ load the given compiled ELL classifier for use in processing subsequent audio input """
        if classifier_path:
            self.classifier = classifier.AudioClassifier(
                classifier_path, self.categories, self.threshold)
            self.show_output(
                "Classifier input size: {}, output size: {}".format(
                    self.classifier.input_size, self.classifier.output_size))
            if self.classifier_entry.get() != classifier_path:
                self.classifier_entry.delete(0, END)
                self.classifier_entry.insert(0, classifier_path)
        self.init_data()

    def init_data(self):
        """ initialize the spectrogram_image_data and classifier_feature_data based on the newly loaded model info """
        if self.featurizer:
            dim = (self.featurizer.output_size, self.max_spectrogram_width)
            self.spectrogram_image_data = np.zeros(dim, dtype=float)
            if self.spectrogram_image is not None:
                self.spectrogram_image.set_data(self.spectrogram_image_data)

            if self.classifier:
                self.num_classifier_features = self.classifier.input_size // self.featurizer.output_size
                dim = (self.num_classifier_features,
                       self.featurizer.output_size)
                self.classifier_feature_data = np.zeros(dim, dtype=float)

    def accumulate_feature(self, feature_data):
        """ accumulate the feature data and pass feature data to classifier """
        if self.classifier and self.show_classifier_output:
            self.classifier_feature_data = np.vstack(
                (self.classifier_feature_data,
                 feature_data))[-self.num_classifier_features:, :]
            self.evaluate_classifier()

    def accumulate_spectrogram_image(self, feature_data):
        """ accumulate the feature data into the spectrogram image """
        image_data = self.spectrogram_image_data
        feature_data = np.reshape(feature_data, [-1, 1])
        new_image = np.hstack(
            (image_data, feature_data))[:, -image_data.shape[1]:]
        image_data[:, :] = new_image

    def set_spectrogram_image(self):
        """ update the spectrogram image and the min/max values """
        self.lock.acquire()  # protect access to the shared state
        if self.update_minmax and self.show_spectrogram:
            min_value = np.min(self.spectrogram_image_data)
            max_value = np.max(self.spectrogram_image_data)
            if np.isfinite(min_value) and np.isfinite(max_value):
                self.min_value = min_value
                self.max_value = max_value
                eps = 0.1
                if self.max_value - self.min_value < eps:
                    self.max_value = self.min_value + eps

            self.spectrogram_image.set_clim(self.min_value, self.max_value)
        self.spectrogram_image.set_data(self.spectrogram_image_data)
        self.lock.release()

    def get_correct_shape(self, shape):
        """ for some reason keras stores input shape as (None,80,40), and numpy hates that
        so we have to change this to (1,80,40) """
        shape = list(shape)
        fix = [x if x else 1 for x in shape]
        return tuple(fix)

    def clear_output(self):
        """ remove some of the Output based a the timeout callback  """
        self.output_text.delete(1.0, 2.0)

    def process_output(self):
        """ show output that was queued by background thread """
        self.lock.acquire()
        messages = self.message_queue
        self.message_queue = []
        self.lock.release()
        for msg in messages:
            self.show_output(msg)

    def show_output(self, message):
        """ show output message, or queue it if we are on a background thread """
        if self.main_thread != get_ident():
            self.message_queue += [message]
            return

        for line in str(message).split('\n'):
            self.output_text.insert(END, "{}\n".format(line))

        self.output_text.see("end")  # scroll to end
        self.after(self.output_clear_time, self.clear_output)

    def evaluate_classifier(self):
        """ run the classifier model on the current feature data and show the prediction, if any """
        if self.evaluate_classifier and self.classifier and self.classifier_feature_data is not None:
            prediction, probability, label = self.classifier.predict(
                self.classifier_feature_data.ravel())
            if prediction is not None:
                percent = int(100 * probability)
                if self.last_prediction != prediction or self.probability < probability:
                    self.last_prediction = prediction
                    self.probability = probability
                    self.show_output("<<< DETECTED ({}) {}% {} >>>".format(
                        prediction, percent, label))

    def start_playing(self, filename):
        """ Play a wav file, and classify the audio. Note we use a background thread to read the
        wav file and we setup a UI animation function to draw the sliding spectrogram image, this way
        the UI update doesn't interfere with the smoothness of the audio playback """
        if self.speaker is None:
            self.speaker = speaker.Speaker()

        self.stop()
        self.reading_input = False
        self.wav_file = wav_reader.WavReader(self.sample_rate, self.channels)
        self.wav_file.open(filename, self.featurizer.input_size, self.speaker)

        def update_func(frame_index):
            self.process_output()
            if not self.reading_input:
                self.after(1, self.on_stopped)
            self.set_spectrogram_image()
            return (self.spectrogram_image, )

        if self.animation:
            self.animation.event_source.stop()
        self.reading_input = True

        # Start animation timer for updating the UI (e.g. spectrogram image) (30 fps is usually fine)
        self.animation = animation.FuncAnimation(self.features_figure,
                                                 update_func,
                                                 interval=33,
                                                 blit=True)

        # start background thread to read and classify the audio.
        self.featurizer.open(self.wav_file)
        self.read_input_thread = Thread(target=self.on_read_features, args=())
        self.read_input_thread.daemon = True
        self.read_input_thread.start()

    def start_recording(self):
        """ Start recording audio from the microphone nd classify the audio. Note we use a background thread to 
        process the audio and we setup a UI animation function to draw the sliding spectrogram image, this way
        the UI update doesn't interfere with the smoothness of the microphone readings """
        if self.microphone is None:
            self.microphone = microphone.Microphone(False)

        self.stop()
        num_channels = 1
        self.microphone.open(self.featurizer.input_size, self.sample_rate,
                             num_channels, self.input_device)

        def update_func(frame_index):
            # this is an animation callback to update the UI every 33 milliseconds.
            self.process_output()
            self.set_spectrogram_image()
            if not self.reading_input:
                self.after(1, self.on_stopped)
            return (self.spectrogram_image, )

        if self.animation:
            self.animation.event_source.stop()

        self.reading_input = True
        # Start animation timer for updating the UI (e.g. spectrogram image) (30 fps is usually fine)
        self.animation = animation.FuncAnimation(self.features_figure,
                                                 update_func,
                                                 interval=33,
                                                 blit=True)

        # start background thread to read and classify the recorded audio.
        self.featurizer.open(self.microphone)
        self.read_input_thread = Thread(target=self.on_read_features, args=())
        self.read_input_thread.daemon = True
        self.read_input_thread.start()

    def on_read_features(self):
        """ this is the background thread entry point.  So we read the feature data in a loop
        and pass it to the classifier """
        try:
            while self.reading_input and self.featurizer:
                feature_data = self.featurizer.read()
                if feature_data is None:
                    break  # eof
                else:
                    self.lock.acquire()
                    self.accumulate_feature(feature_data)
                    if self.show_spectrogram:
                        self.accumulate_spectrogram_image(feature_data)
                    self.lock.release()
        except:
            errorType, value, traceback = sys.exc_info()
            print("### Exception reading input: " + str(errorType) + ": " +
                  str(value) + " " + str(traceback))
            while traceback:
                print(traceback.tb_frame.f_code)
                traceback = traceback.tb_next

        self.reading_input = False
        if self.classifier:
            self.classifier.reset()  # good time to reset.

    def stop(self):
        """ called when user clicks the stop button, or we reach the end of a wav file input """
        # close streams
        if self.animation:
            self.animation.event_source.stop()
            self.animation = None
        if self.microphone:
            self.microphone.close()
        if self.speaker:
            self.speaker.close()
        if self.wav_file:
            self.wav_file.close()
            self.wav_file = None
        self.reading_input = False
        self.last_prediction = None
        self.probability = 0
        if self.classifier:
            self.classifier.reset()  # good time to reset.

    def on_rec_button_click(self):
        """ called when user clicks the record button, same button is used to "stop" recording. """
        if self.rec_button["text"] == "Rec":
            self.rec_button["text"] = "Stop"
            self.play_button["text"] = "Play"
            self.start_recording()
        else:
            self.rec_button["text"] = "Rec"
            self.on_stop()

    def on_play_button_click(self):
        """ called when user clicks the record button, same button is used to "stop" playback """
        if self.play_button["text"] == "Play":
            self.play_button["text"] = "Stop"
            self.rec_button["text"] = "Rec"
            self.on_play()
        else:
            self.play_button["text"] = "Play"
            self.on_stop()

    def on_play(self):
        """ called when user clicks the Play button """
        filename = self.wav_filename_entry.get()
        filename = filename.strip('"')
        self.wav_filename = filename
        self.settings[self.WAV_FILE_KEY] = filename
        self.save_settings()
        self.start_playing(filename)

    def on_stop(self):
        """ called when user clicks the Stop button """
        self.reading_input = False
        if self.wav_file:
            self.wav_file.close()
            self.wav_file = None
        if self.read_input_thread:
            self.read_input_thread.join()
            self.read_input_thread = None
        self.stop()

    def on_stopped(self):
        """ called when we reach the end of the wav file playback """
        self.play_button["text"] = "Play"
        self.stop()

    def get_wav_list(self):
        if self.wav_filename and os.path.isfile(self.wav_filename):
            dir_name = os.path.dirname(self.wav_filename)
            if not self.wav_file_list:
                self.wav_file_list = [
                    x for x in os.listdir(dir_name)
                    if os.path.splitext(x)[1] == ".wav"
                ]
                self.wav_file_list.sort()
        return self.wav_file_list

    def select_wav_file(self, filename):
        self.wav_filename = filename
        # show the file in the UI
        self.wav_filename_entry.delete(0, END)
        if self.wav_filename:
            self.wav_filename_entry.insert(0, self.wav_filename)
        # and automatically play the file.
        self.on_play()

    def on_minus_key(self, event):
        """ When user presses the plus button we reverse to the previous wav file in the current folder.
        This way you can easily step through all the training wav files """
        if self.get_wav_list():
            i = self.wav_file_list.index(os.path.basename(self.wav_filename))
            if i - 1 >= 0:
                next_wav_file = self.wav_file_list[i - 1]
                dir_name = os.path.dirname(self.wav_filename)
                self.select_wav_file(os.path.join(dir_name, next_wav_file))

    def on_plus_key(self, event):
        """ When user presses the plus button we advance to the next wav file in the current folder.
        This way you can easily step through all the training wav files """
        if self.get_wav_list():
            i = self.wav_file_list.index(os.path.basename(self.wav_filename))
            if i + 1 < len(self.wav_file_list):
                next_wav_file = self.wav_file_list[i + 1]
                dir_name = os.path.dirname(self.wav_filename)
                self.select_wav_file(os.path.join(dir_name, next_wav_file))

    def init_ui(self):
        """ setup the GUI for the app """
        self.master.title("Test")
        self.pack(fill=BOTH, expand=True)

        # Input section
        input_frame = LabelFrame(self, text="Input")
        input_frame.bind("-", self.on_minus_key)
        input_frame.bind("+", self.on_plus_key)
        input_frame.pack(fill=X)
        self.play_button = Button(input_frame,
                                  text="Play",
                                  command=self.on_play_button_click)
        self.play_button.pack(side=RIGHT, padx=4)
        self.rec_button = Button(input_frame,
                                 text="Rec",
                                 command=self.on_rec_button_click)
        self.rec_button.pack(side=RIGHT, padx=4)
        self.wav_filename_entry = Entry(input_frame, width=24)
        self.wav_filename_entry.pack(fill=X)
        self.wav_filename_entry.delete(0, END)
        if self.wav_filename:
            self.wav_filename_entry.insert(0, self.wav_filename)

        # Feature section
        features_frame = LabelFrame(self, text="Features")
        features_frame.pack(fill=X)

        features_control_frame = Frame(features_frame)
        features_control_frame.pack(fill=X)
        load_features_button = Button(features_control_frame,
                                      text="Load",
                                      command=self.on_load_featurizer_model)
        load_features_button.pack(side=RIGHT)
        self.features_entry = Entry(features_control_frame, width=8)
        self.features_entry.pack(fill=X)
        self.features_entry.delete(0, END)
        if self.featurizer_model:
            self.features_entry.insert(0, self.featurizer_model)

        viz_frame = Frame(features_frame)
        viz_frame.pack(fill=X)
        self.features_figure = Figure(figsize=(5, 4), dpi=100)
        self.subplot = self.features_figure.add_subplot(111)

        canvas = FigureCanvasTkAgg(self.features_figure, master=viz_frame)
        canvas.draw()
        canvas.show()
        canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=True)

        # Classifier section
        classifier_frame = LabelFrame(self, text="Classifier")
        classifier_frame.pack(fill=X)
        load_classifier_button = Button(classifier_frame,
                                        text="Load",
                                        command=self.on_load_classifier)
        load_classifier_button.pack(side=RIGHT)
        self.classifier_entry = Entry(classifier_frame, width=8)
        self.classifier_entry.pack(fill=X)
        self.classifier_entry.delete(0, END)
        if self.classifier_model:
            self.classifier_entry.insert(0, self.classifier_model)

        # Output section
        output_frame = LabelFrame(self, text="Output")
        output_frame.pack(fill=BOTH, expand=True)

        self.output_text = Text(output_frame)
        self.output_text.pack(fill=BOTH, padx=4, expand=True)

    def setup_spectrogram_image(self):
        """ this need to be called if you load a new feature model, because the featurizer output size might have 
        changed. """
        if self.featurizer:
            dim = (self.featurizer.output_size, self.max_spectrogram_width)
            self.spectrogram_image_data = np.zeros(dim, dtype=float)
            self.subplot.clear()
            self.spectrogram_image = self.subplot.imshow(
                self.spectrogram_image_data,
                vmin=self.min_value,
                vmax=self.max_value,
                origin="lower",
                animated=True,
                cmap=pyplot.get_cmap(self.colormap_name))

    def on_load_featurizer_model(self):
        """ called when user clicks the Load button for the feature model """
        filename = self.features_entry.get()
        filename = filename.strip('"')
        self.settings[self.FEATURIZER_MODEL_KEY] = filename
        self.save_settings()
        self.stop()
        self.load_featurizer_model(filename)

    def on_load_classifier(self):
        """ called when user clicks the Load button for the feature model """
        self.classifier_model = self.classifier_entry.get()
        self.settings[self.CLASSIFIER_MODEL_KEY] = self.classifier_model
        self.save_settings()
        self.stop()
        self.load_classifier(self.classifier_model)
Exemplo n.º 45
0
class UI(Frame):
    def __init__(self):
        self.tk = Tk()
        super().__init__()
        self.initUI()

    def initUI(self):
        self.window = self.master
        self.window.title('Random Password Generator')
        self.window.geometry("325x350")
        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)
        self.rowconfigure(5, pad=3)
        self.rowconfigure(6, pad=3)
        self.rowconfigure(7, pad=3)
        self.Label1 = Label(self.window, text="Password length").grid(row=0,
                                                                      column=0,
                                                                      pady=5)
        self.Label2 = Label(self.window,
                            text="How many password would you like?").grid(
                                row=1, column=0, padx=10, pady=5)
        self.length = Entry(self.window, width=5)
        self.length.grid(row=0, column=1, sticky=W, padx=5)
        self.much = Entry(self.window, width=5)
        self.much.grid(row=1, column=1, sticky=W, padx=5)
        self.numbers = IntVar(self.window)
        self.numbers.set(0)
        self.Label3 = Label(self.window, text="Include numbers").grid(row=2,
                                                                      column=0,
                                                                      pady=5)
        self.b1 = Checkbutton(self.window,
                              variable=self.numbers,
                              offvalue=0,
                              onvalue=1).grid(row=2, column=1)
        self.spechar = IntVar()
        self.spechar.set(0)
        self.Label4 = Label(self.window,
                            text="Include special characters").grid(row=3,
                                                                    column=0,
                                                                    pady=5)
        self.ckb1 = Checkbutton(self.window,
                                variable=self.spechar).grid(row=3, column=1)
        self.bt1 = Button(self.window, text='Generate',
                          command=self.generate).grid(row=4,
                                                      columnspan=2,
                                                      padx=10,
                                                      sticky=W + E)
        self.text = Text(self.window, height=10, width=38)
        self.text.grid(row=5, columnspan=2, padx=10, pady=5)
        self.scroll = Scrollbar(self.window,
                                orient="vertical",
                                width=20,
                                command=self.text.yview)
        self.scroll.grid(row=5, column=1, padx=5, pady=5, sticky='nse')
        self.text['yscrollcommand'] = self.scroll.set

    def generate(self):
        try:
            length = int(self.length.get())
            much = int(self.much.get())
        except:
            messagebox.showerror("ERROR", message="Please, give a number!!!")

        if length > 36:
            messagebox.showerror("ERROR",
                                 message="Please, give a smaller than 36!!!")
            return
        if length < 0 or much < 0:
            messagebox.showerror("ERROR",
                                 message="Please, give a positive number!!!")
            return
        if much > 20:
            messagebox.showerror("ERROR",
                                 message="Please, give a smaller then 20!!!")
            return

        password = []
        if self.numbers.get() == 0 and self.spechar.get() == 0:
            for s in range(0, much):
                password1 = ""
                for i in range(0, length):
                    password1 = (password1 +
                                 random.choice(string.ascii_letters))
                password.append(password1)

        elif self.numbers.get() == 1 and self.spechar.get() == 0:
            for s in range(0, much):
                password1 = ""
                for i in range(0, length):
                    password1 = (
                        password1 +
                        random.choice(string.ascii_letters + string.digits))
                password.append(password1)
        elif self.numbers.get() == 1 and self.spechar.get() == 1:
            for s in range(0, much):
                password1 = ""
                for i in range(0, length):
                    password1 = (
                        password1 +
                        random.choice(string.ascii_letters + string.digits +
                                      string.punctuation))
                password.append(password1)
        elif self.numbers.get() == 0 and self.spechar.get() == 1:
            for s in range(0, much):
                password1 = ""
                for i in range(0, length):
                    password1 = (password1 +
                                 random.choice(string.ascii_letters +
                                               string.punctuation))
                password.append(password1)
        self.text.delete(1.0, END)
        for i in password:
            self.text.insert('2.0', i + '\n')
        return

    def runUI(self):
        self.mainloop()
Exemplo n.º 46
0
    def render_ui(self):
        '''Render the parameter UI elements and attach bindings'''

        row = self.parent.get_row()
        win = self.label_frame

        # The parameter name
        lab = Label(win, text=self.sherpa_par.name, width=12, anchor="e")
        lab.grid(row=row, column=0, padx=(5, 5), pady=2)

        # The current parameter value
        self.val_str = StringVar()
        self.val = Entry(win,
                         textvariable=self.val_str,
                         foreground="black",
                         width=12,
                         justify="right")
        self.val.grid(row=row, column=1, padx=(5, 5), pady=2)
        self.val.delete(0, END)
        self.val.insert(0, self.__format_val(self.sherpa_par.val))
        self.val.last_value = self.val.get()
        self.val.bind("<KeyRelease>",
                      lambda x: self.entry_callback(x, field='val'))

        # Frozen|Thawed checkbox.  Checked if frozen.
        self.fz_box = IntVar()
        if self.sherpa_par.frozen is True:
            self.fz_box.set(1)
        else:
            self.fz_box.set(0)
        fzbtn = Checkbutton(win,
                            text="",
                            variable=self.fz_box,
                            command=self._freeze_thaw)
        fzbtn.grid(row=row, column=2, padx=(5, 5), pady=2)

        # The min value
        self.min_str = StringVar()
        self.min = Entry(win,
                         textvariable=self.min_str,
                         foreground="black",
                         width=12,
                         justify="right")
        self.min.grid(row=row, column=3, padx=(5, 5), pady=2)
        self.min.delete(0, END)
        self.min.insert(0, self.__format_val(self.sherpa_par.min))
        self.min.last_value = self.min.get()
        self.min.bind("<KeyRelease>",
                      lambda x: self.entry_callback(x, field='min'))

        # The max value
        self.max_str = StringVar()
        self.max = Entry(win,
                         textvariable=self.max_str,
                         foreground="black",
                         width=12,
                         justify="right")
        self.max.grid(row=row, column=4, padx=(5, 5), pady=2)
        self.max.delete(0, END)
        self.max.insert(0, self.__format_val(self.sherpa_par.max))
        self.max.last_value = self.max.get()
        self.max.bind("<KeyRelease>",
                      lambda x: self.entry_callback(x, field='max'))

        # The units of the parameter
        par_units = Label(win,
                          text="{}".format(self.sherpa_par.units),
                          width=20,
                          anchor="e")
        par_units.grid(row=row, column=5, padx=(5, 5), pady=2)
Exemplo n.º 47
0
    def run(self):
        
    # 1/2 Configure the Individual GUI Tabs    
        print("Start GUI Setup!")
        
        self.root = tk.Tk() # The GUI
        self.root.title("Unreal Vehicle GUI")
        self.nb = Notebook(self.root)
        
        # Add Main Tab
        self.StateFrame = Frame(self.nb, width = self.WIDTH, height = self.HEIGHT) # Top of Gui 
        self.nb.add(self.StateFrame, text = "Vehicle State")
        
        # Get Notebook Gridded
        self.nb.grid(row = 0, column = 0)
        
        # Configure Video Tab
        self.VideoFrame = Frame(self.nb, width = self.WIDTH, height = self.HEIGHT)
        self.nb.add(self.VideoFrame, text = "Video Feed")
        
        # Configure Plotting Tab
        self.PlottingFrame = Frame(self.nb, width = self.WIDTH, height = self.HEIGHT)
        self.nb.add(self.PlottingFrame, text = "Track n' Map")
        self.fig = plt.figure(1, figsize= (4,4))
        self.ax = Axes3D(self.fig)
        self.last_3d_viz_x_pos = 0
        self.last_3d_viz_y_pos = 0
        self.last_3d_viz_z_pos = 0
        self.ax.scatter(self.last_3d_viz_x_pos,self.last_3d_viz_y_pos,self.last_3d_viz_z_pos)
        self.canvas = FigureCanvasTkAgg(self.fig, self.PlottingFrame)
        self.canvas.get_tk_widget().grid(row = 1, column = 0)
        
        # Configure Virtual IMU Tab:
        self.embed = tk.Frame(self.root, width = self.WIDTH, height = self.HEIGHT)
        self.nb.add(self.embed, text="Virtual IMU")
        os.environ['SDL_WINDOWID'] = str(self.embed.winfo_id())  #Tell pygame's SDL window which window ID to use
        
        # Start PYGAME for IMU Visualization
        pygame.init()
        self.screen = Screen(500,500, scale=1.5)
        self.cube = Cube(40,40,40)
        # END Initialization
        self.root.update()
        
    # 2/2 Configure the Labels and Entries on the GUI    
        # For Switch Vehicle Feeds
        self.current_vehicle_feed = tk.StringVar(self.StateFrame) # Linked to current vehicle choice
        self.switch_vehicle_feed = Combobox(self.StateFrame, textvariable = self.current_vehicle_feed)
        self.switch_vehicle_feed['values'] = self.vehicle_names
        self.switch_vehicle_feed.grid(row = 0, column = 3)
        self.switch_vehicle_feed.current(0)
        
        # Labels for state variables
        self.label_posx = Label(self.StateFrame, text = "PosX:")
        self.label_posy = Label(self.StateFrame, text = "PosY:")
        self.label_posz = Label(self.StateFrame, text = "PosZ:")
        self.label_velx = Label(self.StateFrame, text = "Vel X:")
        self.label_vely = Label(self.StateFrame, text = "Vel Y:")
        self.label_velz = Label(self.StateFrame, text = "Vel Z:")
        self.label_accx = Label(self.StateFrame, text = "Acc X:")
        self.label_accy = Label(self.StateFrame, text = "Acc Y:")
        self.label_accz = Label(self.StateFrame, text = "Acc Z:")
        self.label_rollrate = Label(self.StateFrame, text = "Roll Rate:")
        self.label_pitchrate = Label(self.StateFrame, text = "Pitch Rate:")
        self.label_yawrate = Label(self.StateFrame, text = "Yaw Rate:")
        self.label_angaccx = Label(self.StateFrame, text = "AngAcc X:")
        self.label_angaccy = Label(self.StateFrame, text = "AngAcc Y:")
        self.label_angaccz = Label(self.StateFrame, text = "AngAcc Z:")
        self.label_roll = Label(self.StateFrame, text = "Roll:")
        self.label_pitch = Label(self.StateFrame, text = "Pitch:")
        self.label_yaw = Label(self.StateFrame, text = "Yaw:")        
        
        # Assemble into grid -- No need to pack if you are using grid
        self.label_posx.grid(row = 0, column = 0)
        self.label_posy.grid(row = 1, column = 0)
        self.label_posz.grid(row = 2, column = 0)
        self.label_velx.grid(row = 3, column = 0)
        self.label_vely.grid(row = 4, column = 0)
        self.label_velz.grid(row = 5, column = 0)
        self.label_accx.grid(row = 6, column = 0)
        self.label_accy.grid(row = 7, column = 0)
        self.label_accz.grid(row = 8, column = 0)
        self.label_rollrate.grid(row = 9, column = 0)
        self.label_pitchrate.grid(row = 10, column = 0)
        self.label_yawrate.grid(row = 11, column = 0)
        self.label_angaccx.grid(row = 12, column = 0)
        self.label_angaccy.grid(row = 13, column = 0)
        self.label_angaccz.grid(row = 14, column = 0)
        self.label_roll.grid(row = 15, column = 0)
        self.label_pitch.grid(row = 16, column = 0)
        self.label_yaw.grid(row = 17, column = 0)
        
        # Entries for State Updates:
        self.entry_posx = Entry(self.StateFrame, text = "PosX:")
        self.entry_posy = Entry(self.StateFrame, text = "PosY:")
        self.entry_posz = Entry(self.StateFrame, text = "PosZ:")
        self.entry_velx = Entry(self.StateFrame, text = "Vel X:")
        self.entry_vely = Entry(self.StateFrame, text = "Vel Y:")
        self.entry_velz = Entry(self.StateFrame, text = "Vel Z:")
        self.entry_accx = Entry(self.StateFrame, text = "Acc X:")
        self.entry_accy = Entry(self.StateFrame, text = "Acc Y:")
        self.entry_accz = Entry(self.StateFrame, text = "Acc Z:")
        self.entry_roll = Entry(self.StateFrame, text = "Roll:")
        self.entry_pitch = Entry(self.StateFrame, text = "Pitch:")
        self.entry_yaw = Entry(self.StateFrame, text = "Yaw:")
        self.entry_rollrate = Entry(self.StateFrame, text = "Roll Rate:")
        self.entry_pitchrate = Entry(self.StateFrame, text = "Pitch Rate:")
        self.entry_yawrate = Entry(self.StateFrame, text = "Yaw Rate:")
        self.entry_angaccx = Entry(self.StateFrame, text = "AngAcc X:")
        self.entry_angaccy = Entry(self.StateFrame, text = "AngAcc Y:")
        self.entry_angaccz = Entry(self.StateFrame, text = "AngAcc Z:")

        # Entries Gridded
        self.entry_posx.grid(row = 0, column = 1)
        self.entry_posy.grid(row = 1, column = 1)
        self.entry_posz.grid(row = 2, column = 1)
        self.entry_velx.grid(row = 3, column = 1)
        self.entry_vely.grid(row = 4, column = 1)
        self.entry_velz.grid(row = 5, column = 1)
        self.entry_accx.grid(row = 6, column = 1)
        self.entry_accy.grid(row = 7, column = 1)
        self.entry_accz.grid(row = 8, column = 1)
        self.entry_roll.grid(row = 15, column = 1)
        self.entry_pitch.grid(row = 16, column = 1)
        self.entry_yaw.grid(row = 17, column = 1)
        self.entry_rollrate.grid(row = 9, column = 1)
        self.entry_pitchrate.grid(row = 10, column = 1)
        self.entry_yawrate.grid(row = 11, column = 1)
        self.entry_angaccx.grid(row = 12, column = 1)
        self.entry_angaccy.grid(row = 13, column = 1)
        self.entry_angaccz.grid(row = 14, column = 1)
        
        # Meta Data For the State Page
        self.entry_action = Entry(self.StateFrame, text = "Action")
        self.entry_action_name = Entry(self.StateFrame, text = "Action Name")
        self.entry_env_state = Entry(self.StateFrame, text = "Env State")
        self.entry_mode = Entry(self.StateFrame, text = "GUI Mode")
        self.entry_act_time = Entry(self.StateFrame, text = "Action Time")
        self.entry_sim_image_time = Entry(self.StateFrame, text = "Sim Image Get Time")
        self.entry_sim_state_time = Entry(self.StateFrame, text = "Sim State Get Time")
        self.entry_reward_time = Entry(self.StateFrame, text = "Sim Calc Reward Time")
        self.entry_step_time = Entry(self.StateFrame, text = "Step Time")
        self.entry_reward = Entry(self.StateFrame, text = "Reward")
        self.entry_done = Entry(self.StateFrame, text = "Done Flag")
        
        
        self.label_action = Label(self.StateFrame, text = "Action:")
        self.label_action_name = Label(self.StateFrame, text = "Action Name:")
        self.label_env_state = Label(self.StateFrame, text = "Env State:")
        self.label_mode = Label(self.StateFrame, text = "GUI Mode:")
        self.label_act_time = Label(self.StateFrame, text = "Action Time:")
        self.label_sim_image_time = Label(self.StateFrame, text = "Sim Image Get Time:")
        self.label_sim_state_time = Label(self.StateFrame, text = "Sim State Get Time:")
        self.label_reward_time = Label(self.StateFrame, text = "Calc Reward Time:")
        self.label_step_time = Label(self.StateFrame, text = "Env Step Time:")
        self.label_reward = Label(self.StateFrame, text = "Reward:")
        self.label_done = Label(self.StateFrame, text = "Done:")
        
        # Grid Meta Data Display
        self.label_action.grid(row = 5, column = 2)
        self.label_action_name.grid(row = 6, column = 2)
        self.label_env_state.grid(row = 7, column = 2)
        self.label_mode.grid(row = 8, column = 2)
        self.label_act_time.grid(row = 9, column = 2)
        self.label_sim_image_time.grid(row = 10, column = 2)
        self.label_sim_state_time.grid(row = 11, column = 2)
        self.label_reward_time.grid(row = 12, column = 2)
        self.label_step_time.grid(row = 13, column = 2)
        self.label_reward.grid(row = 14, column = 2)
        self.label_done.grid(row = 15, column = 2)
        
        self.entry_action.grid(row = 5, column = 3)
        self.entry_action_name.grid(row = 6, column = 3)
        self.entry_env_state.grid(row = 7, column = 3)
        self.entry_mode.grid(row = 8, column = 3)
        self.entry_act_time.grid(row = 9, column = 3)
        self.entry_sim_image_time.grid(row = 10, column = 3)
        self.entry_sim_state_time.grid(row = 11, column = 3)
        self.entry_reward_time.grid(row = 12, column = 3)
        self.entry_step_time.grid(row = 13, column = 3)
        self.entry_reward.grid(row = 14, column = 3)
        self.entry_done.grid(row = 15, column = 3)
        
        # Initialize the Vehicle's Virtual IMU Visualization
        self.label_yaw = Label(self.embed, text = "Yaw:")
        self.label_pitch = Label(self.embed, text = "Pitch:")
        self.label_roll = Label(self.embed, text = "Roll:")
        self.label_yaw.place(x=500,y = 0) # Place the Labels on the far right of the frame
        self.label_pitch.place(x=500, y = 50)
        self.label_roll.place(x=500, y = 100)
        
        self.entry_imu_yaw = Entry(self.embed, text = "Yaw:")
        self.entry_imu_pitch = Entry(self.embed, text = "Pitch:")
        self.entry_imu_roll = Entry(self.embed, text = "Roll:")
        self.entry_yaw.place(x = 500, y = 25)
        self.entry_pitch.place(x = 500, y = 75)
        self.entry_roll.place(x = 500, y = 125)
        
        print("GUI Setup DONE!")
        t_upd = threading.Thread(target = self.updates)
        t_upd.start()
        self.root.mainloop()
Exemplo n.º 48
0
    def initUI(self):

        self.master.title("Calculator", )

        Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10')

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)

        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)

        global expression
        expression = ""
        global label_text
        label_text = StringVar()
        label_text.set("Enter Here...")
        entry = Entry(self, textvariable=label_text)
        entry.grid(row=0, columnspan=4, sticky=W + E)
        entry.bind("<Button-1>", self.cycle_label_text)
        #entry.pack()
        cls = Button(self, text="Cls", command=self.clear)
        cls.grid(row=1, column=0)
        bck = Button(self, text="Back")
        bck.grid(row=1, column=1)
        lbl = Button(self)
        lbl.grid(row=1, column=2)
        clo = Button(self, text="Close", command=self.quit)
        clo.grid(row=1, column=3)
        sev = Button(self, text="7", command=lambda: self.press(7))
        sev.grid(row=2, column=0)
        eig = Button(self, text="8", command=lambda: self.press(8))
        eig.grid(row=2, column=1)
        nin = Button(self, text="9", command=lambda: self.press(9))
        nin.grid(row=2, column=2)
        div = Button(self, text="/", command=lambda: self.press('/'))
        div.grid(row=2, column=3)

        fou = Button(self, text="4", command=lambda: self.press(4))
        fou.grid(row=3, column=0)
        fiv = Button(self, text="5", command=lambda: self.press(5))
        fiv.grid(row=3, column=1)
        six = Button(self, text="6", command=lambda: self.press(6))
        six.grid(row=3, column=2)
        mul = Button(self, text="*", command=lambda: self.press("*"))
        mul.grid(row=3, column=3)

        one = Button(self, text="1", command=lambda: self.press(1))
        one.grid(row=4, column=0)
        two = Button(self, text="2", command=lambda: self.press(2))
        two.grid(row=4, column=1)
        thr = Button(self, text="3", command=lambda: self.press(3))
        thr.grid(row=4, column=2)
        mns = Button(self, text="-", command=lambda: self.press("-"))
        mns.grid(row=4, column=3)

        zer = Button(self, text="0", command=lambda: self.press(0))
        zer.grid(row=5, column=0)
        dot = Button(self, text=".", command=lambda: self.press("."))
        dot.grid(row=5, column=1)
        equ = Button(self, text="=", command=lambda: self.press_equal("="))
        equ.grid(row=5, column=2)
        pls = Button(self, text="+", command=lambda: self.press("+"))
        pls.grid(row=5, column=3)

        self.pack()
Exemplo n.º 49
0
    def __init__(self):
        super().__init__()

        self.master.title("Income calculator app")
        self.pack(fill=BOTH, expand=True)

        # label
        frame0 = Frame(self)
        frame0.pack(fill=X)
        title = Label(frame0,
                      text='Welcome to the app',
                      font=("Times New Roman", 20))
        title.pack()

        # frame 1
        frame1a = Frame(self)
        frame1a.pack(fill=X, padx=10, pady=10)
        name_label = Label(frame1a, text="Employee name :", width=15)
        name_label.pack(side=LEFT, padx=5, pady=5)
        name = Entry(frame1a)
        name.pack(fill=X, padx=5, expand=True)
        frame1b = Frame(self)
        frame1b.pack(fill=X, padx=10, pady=10)
        destination_label = Label(frame1b, text="Destination :", width=15)
        destination_label.pack(side=LEFT, padx=5, pady=5)
        # destination = Entry(frame1b)
        # destination.pack(fill=X, padx=5, expand=True)
        data = pd.read_csv("country_currency.csv")
        data.dropna(subset=['Country'], inplace=True)
        destination_select = StringVar(frame1b)
        destination = AutocompleteCombobox(
            frame1b,
            textvariable=destination_select,
            width=20,
            completevalues=data['Country'].to_list())
        destination.pack()

        # frame 2
        frame2 = Frame(self)
        frame2.pack(fill=X)
        netIncome_label = Label(frame2, text='Net income (per year)', width=20)
        netIncome_label.pack(side=LEFT, padx=5, pady=5)
        netIncome = Entry(frame2)
        netIncome.pack(fill=X, padx=5, expand=True)

        #frame 3
        frame3 = Frame(self)
        frame3.pack(pady=10)
        maritalStatus_label = Label(frame3, text='Marital status ', width=15)
        maritalStatus_label.pack(side=LEFT, padx=5, pady=5)
        maritalStatus_select = StringVar(frame3)
        maritalStatus_select.set(maritalStatusList[0])
        maritalStatus = OptionMenu(frame3, maritalStatus_select,
                                   *maritalStatusList)
        maritalStatus.pack(side=LEFT, padx=10)

        nKids_label = Label(frame3, text='Number of kids :', width=20)
        nKids_select = IntVar(frame3)
        nKids_select.set(nKids_list[0])
        nKids_entry = OptionMenu(frame3, nKids_select, *nKids_list)
        nKids_label.pack(side=LEFT)
        nKids_entry.pack(side=LEFT)

        def get_info():
            try:
                df_row = data[data['Country'] == destination_select.get()]
                currency_code = str(df_row['Currency code'].values[0])
                currency_name = str(df_row['Currency'].values[0])
            except:
                messagebox.showwarning('Warning',
                                       'Please select a destination')
                currency_code = 'EUR'
                currecy_name = 'Euros'
            country2_select.set(currency_code)
            currency.set(currency_name)

        #frame 3
        frame3a = Frame(self)
        frame3a.pack(pady=5)

        info_button = Button(frame3a, text='Get info', command=get_info)
        info_button.pack(side=TOP)

        forex_label = Label(frame3a,
                            text='Currency conversion    From ',
                            width=15)
        forex_label.pack(side=LEFT, padx=5, pady=5)
        country1_select = StringVar(frame3a)
        country1_select.set(currecy_list[0])
        country1 = OptionMenu(frame3a, country1_select, *currecy_list)
        country1.pack(side=LEFT, padx=10)

        forex_label2 = Label(frame3a, text='  To  ', width=5)
        country2_select = StringVar(frame3a)
        currency = StringVar(frame3a)
        country2_select.set('EUR')
        currency.set('Euros')
        country2 = Text(frame3a, height=1, width=10)
        country2.insert(END, country2_select.get())
        forex_label2.pack(side=LEFT)
        country2.pack(side=LEFT)

        forex_display = Text(frame3a, height=1, width=10)
        c = CurrencyRates()
        forex_display.insert(
            END, c.get_rate(country1_select.get(), country2_select.get()))
        forex_display.pack(side=RIGHT, padx=10)
        forex_conversion = StringVar()
        forex_conversion.set('1.0')

        def callback(*args):
            forex_display.delete(1.0, "end")
            country2.delete(1.0, "end")
            try:
                forex_conversion.set(
                    c.get_rate(country1_select.get(), country2_select.get()))
                forex_display.insert(END, forex_conversion.get())
                country2.insert(END, country2_select.get())
            except Exception as exception_error:
                messagebox.showwarning('Warning', exception_error)
                forex_conversion.set('1.0')
                forex_display.insert(END, '0')

        country2_select.trace("w", callback)
        country1_select.trace("w", callback)

        #frame 4
        frame4 = Frame(self)
        frame4.pack(pady=10)
        radioInput = IntVar(self)
        radioInput.set(1)
        R1 = Radiobutton(frame4, text="Yearly", variable=radioInput, value=1)
        R2 = Radiobutton(frame4, text="Montly", variable=radioInput, value=2)
        R3 = Radiobutton(frame4, text="Daily", variable=radioInput, value=3)
        period_label = Label(frame4, text='Calculating for period :')
        period_label.pack(side=LEFT)
        R1.pack(side=LEFT, pady=10)
        R2.pack(side=LEFT, pady=10)
        R3.pack(side=RIGHT, pady=10)

        now = datetime.now()  # current date and time

        def get_string():
            income = float('0' + netIncome.get())
            status = str(maritalStatus_select.get())
            output_string = "Income calculation        \t {}  \n\n".format(
                now.strftime("%d/%m/%Y, %H:%M:%S"))
            output_string += "Employee name :{} \n\n".format(name.get())
            output_string += "Destination   :{} \n".format(
                destination_select.get())
            output_string += "Currency      :{} - {} \n".format(
                country2_select.get(), currency.get())
            output_string += "\nNet yearly income = {} {}  ".format(
                income, country1_select.get())
            output_string += "\n\nCalcualting for " + str(
                period[radioInput.get() - 1])
            if radioInput.get() == 2:
                income = round(income / 12, 2)
            elif radioInput.get() == 3:
                income = round(income / 365, 2)
            output_string += "\nNet income = {} {} \nMarital status = {} ".format(
                income, country1_select.get(), status)
            output_string += "\nNumber of kids = " + str(nKids_select.get())

            try:
                tax_rate = get_tax(country=destination_select.get())
                social_sec_em, social_sec_com = get_social_security(
                    country=destination_select.get())
            except:
                messagebox.showwarning(
                    'Warning', 'Tax / social security information NOT found')
                tax_rate = 0
                social_sec_em, social_sec_com = 0, 0
            output_string += "\n\nTax rate : {} %".format(tax_rate)
            output_string += "\nSocial security rates:"
            output_string += "\n   employee : {} %".format(social_sec_em)
            output_string += "\n   company  : {} %".format(social_sec_com)
            output_string += "\n\n Tax amount  : {}".format(
                round(income * tax_rate / 100, 2))
            output_string += "\n Employee social security amount : {}".format(
                round(income * social_sec_em / 100, 2))
            output_string += "\n Company social security amount  : {}".format(
                round(income * social_sec_com / 100, 2))
            total = float(
                get_total(income=income,
                          rate1=tax_rate,
                          rate2=social_sec_em,
                          rate3=social_sec_com))
            output_string += "\n\nTotal  : {} {}".format(
                total, country1_select.get())
            output_string += '\n conversion = {}'.format(
                forex_conversion.get())
            total *= float(forex_conversion.get())
            output_string += "\n after conversion {} {} ".format(
                round(total, 2), country2_select.get())

            return output_string

        def write_pdf():
            pdf = FPDF()
            pdf.add_page()
            pdf.set_margins(30, 50, 25)
            pdf.set_font("Arial", size=15)
            output_string = get_string().split('\n')
            for s in output_string:
                pdf.cell(200, 10, txt=s, ln=1)
            pdf.output(name.get() + ' ' + str(now.strftime("%d_%m_%Y")) +
                       '_info.pdf')

        def write_txt():
            with open(
                    name.get() + ' ' + str(now.strftime("%d_%m_%Y")) +
                    '_info.txt', 'w') as sfile:
                sfile.write(get_string())

        def string_display():
            output_display.delete(1.0, END)
            output_display.insert(END, get_string())

        frame5 = Frame(self, borderwidth=1)
        frame5.pack(fill=BOTH, expand=True, padx=5, pady=5)
        output_display = Text(frame5, height=15)
        scroll_y = Scrollbar(frame5,
                             orient="vertical",
                             command=output_display.yview)
        scroll_y.pack(side="right", expand=True, fill="y", padx=2, pady=2)
        output_display.pack(side='left', fill=X, padx=2, pady=2)
        output_display.configure(yscrollcommand=scroll_y.set)

        frame_final = Frame(self, relief=RAISED, borderwidth=1)
        frame_final.pack(fill=X, padx=10, pady=5)
        submit_button = Button(frame_final,
                               text='Submit',
                               command=string_display)
        submit_button.pack(side=LEFT)
        file_type_label = Label(frame_final, text='Choose file type:')
        file_type_label.pack()
        file_save_type = StringVar()
        file_save_type.set(save_list[0])
        file_save = OptionMenu(frame_final, file_save_type, *save_list)

        def save_to_file():
            if file_save_type.get() == 'txt':
                write_txt()
                messagebox.showinfo('Saved!', 'Saved as text file')
            elif file_save_type.get() == 'pdf':
                write_pdf()
                messagebox.showinfo('Saved!', 'Saved as pdf file')
            else:
                messagebox.showwarning('Warning',
                                       'Please select text file or pdf')

        save_button = Button(frame_final,
                             text='Save to file',
                             command=save_to_file)
        save_button.pack(side=RIGHT)
        file_save.pack(side=RIGHT)
Exemplo n.º 50
0
class Control(Frame):
    def __init__(self):
        # initialize RED and BLUE fighters
        self.RED = 0
        self.BLUE = 1

        # initialize score and kyonggo variables
        self.redPoints = 0
        self.bluePoints = 0
        self.redKyonggo = 0
        self.blueKyonggo = 0
        self.currentRound = 0
        self.display = None
        self.miniDisplay = None
        self.numRounds = 0
        self.timer = None
        self.isSuddenDeath = False
        self.callNextRound = True
        try:
            # for Python3
            super().__init__()
        except:
            # for Python2
            Frame.__init__(self)

        # set title and default style
        self.master.title("TKD Scoring System")
        # create style
        self.s = Style()
        self.s.configure("TButton", padding=10, font=(None, 20))
        self.s.configure("TCheckbutton", padding=10, font=(None, 20))
        self.s.configure("TOptionMenu", padding=10, font=(None, 20))
        self.pack(fill=BOTH, expand=True)
        # create setup frames, labels, and entries
        # time entry frame
        self.setTimeFrame = Frame(self)
        self.timerLabel = Label(self.setTimeFrame,
                                text="Time:",
                                font=(None, 20))
        self.secondsEntry = Entry(self.setTimeFrame, width=3, font=(None, 20))
        self.colonLabel = Label(self.setTimeFrame, text=":", font=(None, 20))
        self.minuteEntry = Entry(self.setTimeFrame, width=3, font=(None, 20))
        # round entry frame
        self.roundsFrame = Frame(self)
        self.roundsLabel = Label(self.roundsFrame,
                                 text="Number of Rounds:",
                                 font=(None, 20))
        self.roundsEntry = Entry(self.roundsFrame, width=3, font=(None, 20))
        # serial entry frame
        self.serialFrame = Frame(self)
        try:
            self.arduino_ports = ["None"] + [
                p.device for p in serial.tools.list_ports.comports()
            ]
        except:
            # if serial is not installed
            self.arduino_ports = ["None"]
        self.serialEntry = StringVar()
        self.serialEntry.set("None")
        self.serialLabel = Label(self.serialFrame,
                                 text="Serial Input:",
                                 font=(None, 20))
        self.serialCheck = OptionMenu(self.serialFrame, self.serialEntry,
                                      "None", *self.arduino_ports)
        self.createMatchButton = Button(self,
                                        text="Create Match",
                                        style="TButton",
                                        command=self.hideSetup)

        # initialize frames for UI
        # red frame and buttons
        self.redFrame = Frame(self)
        self.redScoreButton = Button(
            self.redFrame,
            text="Red +",
            style="TButton",
            command=lambda: self.incrementPoints(self.RED))
        self.redDeletePoint = Button(
            self.redFrame,
            text="Red -",
            style="TButton",
            command=lambda: self.deductPoints(self.RED))
        self.redKyonggoButton = Button(
            self.redFrame,
            text="Kyonggo +",
            style="TButton",
            command=lambda: self.callKyonggo(self.RED))
        self.redKyonggoDelete = Button(
            self.redFrame,
            text="Kyonggo -",
            style="TButton",
            command=lambda: self.deductKyonggo(self.RED))
        # blue frame and buttons
        self.blueFrame = Frame(self)
        self.blueScoreButton = Button(
            self.blueFrame,
            text="Blue +",
            style="TButton",
            command=lambda: self.incrementPoints(self.BLUE))
        self.blueDeletePoint = Button(
            self.blueFrame,
            text="Blue -",
            style="TButton",
            command=lambda: self.deductPoints(self.BLUE))
        self.blueKyonggoButton = Button(
            self.blueFrame,
            text="Kyonggo +",
            style="TButton",
            command=lambda: self.callKyonggo(self.BLUE))
        self.blueKyonggoDelete = Button(
            self.blueFrame,
            text="Kyonggo -",
            style="TButton",
            command=lambda: self.deductKyonggo(self.BLUE))
        # reset and new match frame and buttons
        self.resetFrame = Frame(self)
        self.startStop = StringVar()
        self.timerStartStop = Button(self.resetFrame,
                                     textvariable=self.startStop,
                                     style="TButton",
                                     command=self.timerPush)
        self.startStop.set("Start Round 1")
        self.newMatch = Button(self.resetFrame,
                               text="New Match",
                               style="TButton",
                               command=self.newMatch)
        self.resetMatch = Button(self.resetFrame,
                                 text="Reset Match",
                                 style="TButton",
                                 command=self.resetMatch)

        self.setup()

    # displays setup frames
    def setup(self):
        # timer frame
        self.setTimeFrame.pack(fill=X)
        # timer label and entry
        self.timerLabel.pack(side=LEFT, padx=5, pady=5)
        self.secondsEntry.pack(side=RIGHT)
        self.colonLabel.pack(side=RIGHT)
        self.minuteEntry.pack(side=RIGHT)

        # frame for number of rounds
        self.roundsFrame.pack(fill=X)
        # number of rounds label and entry
        self.roundsLabel.pack(side=LEFT, padx=5, pady=5)
        self.roundsEntry.pack(side=RIGHT)

        # frame for serial entry
        self.serialFrame.pack(fill=X, expand=True)
        # serial entry label and checkbox
        self.serialLabel.pack(side=LEFT, padx=5, pady=5)
        self.serialCheck.pack(side=RIGHT)

        # create match button
        self.createMatchButton.pack(side=BOTTOM)

    # hides setup widgets and initalizes timer and number of rounds
    def hideSetup(self):
        # check if minutes, seconds, and round entries are valid
        if len(self.minuteEntry.get()) < 1:
            minutes = 0
        else:
            try:
                minutes = int(self.minuteEntry.get())
            except:
                minutes = 0
        if len(self.secondsEntry.get()) < 1:
            seconds = 0
        else:
            try:
                seconds = int(self.secondsEntry.get()) % 60
                minutes += int(self.secondsEntry.get()) // 60
            except:
                seconds = 0
        if len(self.roundsEntry.get()) < 1:
            numRounds = 0
        else:
            try:
                numRounds = int(self.roundsEntry.get())
            except:
                numRounds = 0
        # set up serial input if checked
        if self.serialEntry.get() != "None":
            self.serialSetup()
        else:
            self.arduino = False
        # only moves on if entries are valid
        if ((minutes != 0) or (seconds != 0)) and (numRounds != 0):
            self.roundLength = [minutes, seconds]
            self.timer = Timer(self.roundLength)
            self.numRounds = numRounds
            self.currentRound = 1
            self.isSuddenDeath = False
            self.roundsFrame.pack_forget()
            self.setTimeFrame.pack_forget()
            self.createMatchButton.pack_forget()
            self.serialFrame.pack_forget()
            self.initUI()

    # set up serial input
    def serialSetup(self):
        try:
            self.arduino = True
            self.serialPort = self.serialEntry.get()
            self.baudRate = 9600
            self.ser = serial.Serial(self.serialPort,
                                     self.baudRate,
                                     timeout=0,
                                     writeTimeout=0)
            self.ser.flushInput()
        except:
            self.arduino = False
            print("Could Not Complete Serial Port Set Up")

    # creates user interface
    def initUI(self):
        # create display
        if self.display == None:
            self.display = Display(self.timer)
            self.display.attributes('-fullscreen', True)
        else:
            self.display.newTimer(self.timer)
            self.display.updateCurrentRound("R1")
        if self.miniDisplay == None:
            self.miniDisplay = miniDisplay(self.timer)
        else:
            self.miniDisplay.newTimer(self.timer)
            self.miniDisplay.updateCurrentRound("R1")

        # red point and kyonggo buttons
        self.redFrame.pack(fill=BOTH, side=LEFT)
        self.redScoreButton.pack(padx=5, pady=5, fill=X)
        self.redDeletePoint.pack(padx=5, pady=5, fill=X)
        self.redKyonggoButton.pack(padx=5, pady=5, fill=X)
        self.redKyonggoDelete.pack(padx=5, pady=5, fill=X)

        # blue point and kyonggo buttons
        self.blueFrame.pack(fill=BOTH, side=RIGHT)
        self.blueScoreButton.pack(padx=5, pady=5, fill=X)
        self.blueDeletePoint.pack(padx=5, pady=5, fill=X)
        self.blueKyonggoButton.pack(padx=5, pady=5, fill=X)
        self.blueKyonggoDelete.pack(padx=5, pady=5, fill=X)

        # timer start/stop button, reset button, and quit button
        self.resetFrame.pack(side=BOTTOM)
        self.startStop.set("Start Round " + str(self.currentRound))
        self.timerStartStop.pack(side=TOP, pady=5)
        self.newMatch.pack(side=LEFT, padx=5)
        self.resetMatch.pack(side=RIGHT, padx=5)

    def timerPush(self):
        # if round is over, reset time give option to start next round
        if self.timer.timeLeft[0] == self.timer.timeLeft[1] == 0:
            self.timer.reset()
            self.startStop.set("Start Round " + str(self.currentRound))
            self.display.updateCurrentRound("R" + str(self.currentRound))
            self.miniDisplay.updateCurrentRound("R" + str(self.currentRound))
            self.updateDisplayTimer()
        # pause timer, give option to unpause
        elif self.timer.isRunning():
            self.timer.stop()
            self.startStop.set("Start")
        # unpause timer, give option to pause
        else:
            if self.arduino:
                self.ser.flushInput()
            self.timer.start()
            if self.arduino:
                self.readSerialInput()
            self.startStop.set("Pause")
            if not self.callNextRound:
                self.callNextRound = True
            self.updateDisplayTimer()

    def resetMatch(self):
        if not self.timer.isRunning():
            self.timer.reset()
            self.redPoints = 0
            self.bluePoints = 0
            self.redKyonggo = 0
            self.blueKyonggo = 0
            self.currentRound = 1
            if self.isSuddenDeath:
                self.isSuddenDeath = False
            self.newMatch.pack_forget()
            self.resetMatch.pack_forget()
            self.timerStartStop.pack(side=TOP, pady=5)
            self.newMatch.pack(side=LEFT, padx=5)
            self.resetMatch.pack(side=RIGHT, padx=5)
            self.startStop.set("Start Round 1")
            self.display.reset(self.timer.getTimeString())
            self.miniDisplay.reset(self.timer.getTimeString())

    def updateDisplayTimer(self):
        if self.timer.isElapsed():
            self.timer.stop()
            if self.callNextRound:
                self.nextRound()
            if self.currentRound < self.numRounds or self.redPoints == self.bluePoints:
                self.display.updateTimer(self.timer.getTimeString())
            self.miniDisplay.updateTimer(self.timer.getTimeString())
        elif self.currentRound > self.numRounds:
            self.suddenDeath()
        else:
            self.display.updateTimer(self.timer.getTimeString())
            self.miniDisplay.updateTimer(self.timer.getTimeString())
            self.after(1000, self.updateDisplayTimer)

    def nextRound(self):
        self.callNextRound = False
        self.currentRound += 1
        if self.currentRound <= self.numRounds:
            self.startStop.set("Reset Timer")
        elif self.redPoints == self.bluePoints:
            self.startStop.set("Sudden Death")
        else:
            self.declareWinner()
            self.timerStartStop.pack_forget()

    def declareWinner(self):
        if self.redPoints > self.bluePoints:
            winner = "RED"
        else:
            winner = "BLUE"
        self.display.updateTimer(winner + " WINS")
        self.display.updateCurrentRound("")

    def suddenDeath(self):
        self.redPoints = 0
        self.display.updateRedPoints(0)
        self.miniDisplay.updateRedPoints(0)
        self.bluePoints = 0
        self.display.updateBluePoints(0)
        self.miniDisplay.updateBluePoints(0)
        self.display.updateTimer("SUDDEN DEATH")
        self.miniDisplay.updateTimer("SUDDEN DEATH")
        self.display.updateCurrentRound("")
        self.miniDisplay.updateCurrentRound("")
        self.isSuddenDeath = True
        if self.arduino:
            self.readSerialInput()
        self.timerStartStop.pack_forget()

    def readSerialInput(self):
        if self.timer.isRunning() or self.isSuddenDeath:
            output = self.ser.readline()
            if len(output) != 0:
                try:
                    fighter = int(output)
                    self.incrementPoints(fighter)
                except:
                    print("Invalid Serial Input")
                self.after(250, self.readSerialInput)
            else:
                self.after(50, self.readSerialInput)

    def incrementPoints(self, fighter):
        if fighter == self.RED:
            self.redPoints += 1
            self.display.updateRedPoints(self.redPoints)
            self.miniDisplay.updateRedPoints(self.redPoints)
        elif fighter == self.BLUE:
            self.bluePoints += 1
            self.display.updateBluePoints(self.bluePoints)
            self.miniDisplay.updateBluePoints(self.bluePoints)
        if self.isSuddenDeath:
            self.declareWinner()

    def deductPoints(self, fighter):
        if fighter == self.RED and self.redPoints > 0:
            self.redPoints -= 1
            self.display.updateRedPoints(self.redPoints)
            self.miniDisplay.updateRedPoints(self.redPoints)
        elif fighter == self.BLUE and self.bluePoints > 0:
            self.bluePoints -= 1
            self.display.updateBluePoints(self.bluePoints)
            self.miniDisplay.updateBluePoints(self.bluePoints)

    def callKyonggo(self, fighter):
        if fighter == self.RED:
            self.redKyonggo += 1
            self.display.updateRedKyonggo("Kyonggo: " + str(self.redKyonggo))
            self.miniDisplay.updateRedKyonggo("Kyonggo: " +
                                              str(self.redKyonggo))
            if self.redKyonggo % 2 == 0:
                self.bluePoints += 1
                self.display.updateBluePoints(self.bluePoints)
                self.miniDisplay.updateBluePoints(self.bluePoints)
        elif fighter == self.BLUE:
            self.blueKyonggo += 1
            self.display.updateBlueKyonggo("Kyonggo: " + str(self.blueKyonggo))
            self.miniDisplay.updateBlueKyonggo("Kyonggo: " +
                                               str(self.blueKyonggo))
            if self.blueKyonggo % 2 == 0:
                self.redPoints -= 1
                self.display.updateRedPoints(self.redPoints)
                self.miniDisplay.updateRedPoints(self.redPoints)

    def deductKyonggo(self, fighter):
        if fighter == self.RED and self.redKyonggo > 0:
            self.redKyonggo -= 1
            self.display.updateRedKyonggo("Kyonggo: " + str(self.redKyonggo))
            self.miniDisplay.updateRedKyonggo("Kyonggo: " +
                                              str(self.redKyonggo))
            if self.redKyonggo % 2 == 1:
                self.redPoints += 1
                self.display.updateRedPoints(self.redPoints)
                self.miniDisplay.updateRedPoints(self.redPoints)
        elif fighter == self.BLUE and self.blueKyonggo > 0:
            self.blueKyonggo -= 1
            self.display.updateBlueKyonggo("Kyonggo: " + str(self.blueKyonggo))
            self.miniDisplay.updateBlueKyonggo("Kyonggo: " +
                                               str(self.blueKyonggo))
            if self.blueKyonggo % 2 == 1:
                self.bluePoints += 1
                self.display.updateBluePoints(self.bluePoints)
                self.miniDisplay.updateBluePoints(self.bluePoints)

    def newMatch(self):
        if not self.timer.isRunning():
            self.redPoints = 0
            self.redKyonggo = 0
            self.bluePoints = 0
            self.blueKyonggo = 0
            self.display.reset("0:00")
            self.miniDisplay.reset("0:00")
            self.hideUI()
            self.setup()

    def hideUI(self):
        self.redFrame.pack_forget()
        self.blueFrame.pack_forget()
        self.resetFrame.pack_forget()
Exemplo n.º 51
0
    def init_ui(self):

        self.master.title("Louis")

        Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10')

        self.NUM_TRANSFORMS = 5

        layer_options = [
            "None",
            "FC1",
            "GRU",
            "FC2",
        ]

        transform_options = [
            "None",
            "ablate",
            "oscillate",
            "threshold",
            "invert",
        ]

        self.gui_elements = []

        button = Button(self, text="Update", command=self.run)
        button.grid(column=0, row=self.NUM_TRANSFORMS)

        Label(self, text="layer").grid(row=0, column=1)
        Label(self, text="transform").grid(row=0, column=2)
        Label(self, text="units/value").grid(row=0, column=3)
        Label(self, text="midi").grid(row=0, column=4)
        Label(self, text="lfo_freq").grid(row=0, column=5)
        Label(self, text="min").grid(row=0, column=6)
        Label(self, text="max").grid(row=0, column=7)

        for i in range(self.NUM_TRANSFORMS):
            var_dict = {}
            var_dict["layer"] = StringVar()
            var_dict["transform"] = StringVar()
            var_dict["unit_value"] = StringVar()
            var_dict["unit_value"].set("0.5")
            var_dict["unit_midi"] = StringVar()
            var_dict["param"] = []
            for j in range(2):
                param_dict = {}
                param_dict["param_value"] = StringVar()
                param_dict["param_value"].set("0.5")
                param_dict["param_midi"] = StringVar()
                param_dict["param_min"] = StringVar()
                param_dict["param_max"] = StringVar()
                param_dict["param_lfo"] = StringVar()
                param_dict["param_label"] = Label(self, text="NA")
                var_dict["param"].append(param_dict)
            self.gui_elements.append(var_dict)

            r = (i * 3) + 1
            layer_menu = OptionMenu(self,
                                    var_dict["layer"],
                                    *layer_options,
                                    command=self.option_changed)
            layer_menu.config(width=10)
            layer_menu.grid(row=r, column=1)
            transform_menu = OptionMenu(self,
                                        var_dict["transform"],
                                        *transform_options,
                                        command=self.option_changed)
            transform_menu.config(width=10)
            transform_menu.grid(row=r, column=2)

            ENTRY_WIDTH = 8

            unit_value = Entry(self,
                               textvariable=var_dict["unit_value"],
                               width=ENTRY_WIDTH)
            unit_value.grid(row=r, column=3)
            unit_midi = Entry(self,
                              textvariable=var_dict["unit_midi"],
                              width=ENTRY_WIDTH)
            unit_midi.grid(row=r, column=4)

            for j in range(2):
                label = var_dict["param"][j]["param_label"]
                label.grid(row=r + (j + 1), columnspan=2, column=1)
                param_value = Entry(
                    self,
                    textvariable=var_dict["param"][j]["param_value"],
                    width=ENTRY_WIDTH)
                param_value.grid(row=r + (j + 1), column=3)
                param_midi = Entry(
                    self,
                    textvariable=var_dict["param"][j]["param_midi"],
                    width=ENTRY_WIDTH)
                param_midi.grid(row=r + (j + 1), column=4)
                param_lfo = Entry(
                    self,
                    textvariable=var_dict["param"][j]["param_lfo"],
                    width=ENTRY_WIDTH)
                param_lfo.grid(row=r + (j + 1), column=5)
                param_min = Entry(
                    self,
                    textvariable=var_dict["param"][j]["param_min"],
                    width=ENTRY_WIDTH)
                param_min.grid(row=r + (j + 1), column=6)
                param_max = Entry(
                    self,
                    textvariable=var_dict["param"][j]["param_max"],
                    width=ENTRY_WIDTH)
                param_max.grid(row=r + (j + 1), column=7)

        self.pack()
Exemplo n.º 52
0
    def __init__(self):
        # initialize RED and BLUE fighters
        self.RED = 0
        self.BLUE = 1

        # initialize score and kyonggo variables
        self.redPoints = 0
        self.bluePoints = 0
        self.redKyonggo = 0
        self.blueKyonggo = 0
        self.currentRound = 0
        self.display = None
        self.miniDisplay = None
        self.numRounds = 0
        self.timer = None
        self.isSuddenDeath = False
        self.callNextRound = True
        try:
            # for Python3
            super().__init__()
        except:
            # for Python2
            Frame.__init__(self)

        # set title and default style
        self.master.title("TKD Scoring System")
        # create style
        self.s = Style()
        self.s.configure("TButton", padding=10, font=(None, 20))
        self.s.configure("TCheckbutton", padding=10, font=(None, 20))
        self.s.configure("TOptionMenu", padding=10, font=(None, 20))
        self.pack(fill=BOTH, expand=True)
        # create setup frames, labels, and entries
        # time entry frame
        self.setTimeFrame = Frame(self)
        self.timerLabel = Label(self.setTimeFrame,
                                text="Time:",
                                font=(None, 20))
        self.secondsEntry = Entry(self.setTimeFrame, width=3, font=(None, 20))
        self.colonLabel = Label(self.setTimeFrame, text=":", font=(None, 20))
        self.minuteEntry = Entry(self.setTimeFrame, width=3, font=(None, 20))
        # round entry frame
        self.roundsFrame = Frame(self)
        self.roundsLabel = Label(self.roundsFrame,
                                 text="Number of Rounds:",
                                 font=(None, 20))
        self.roundsEntry = Entry(self.roundsFrame, width=3, font=(None, 20))
        # serial entry frame
        self.serialFrame = Frame(self)
        try:
            self.arduino_ports = ["None"] + [
                p.device for p in serial.tools.list_ports.comports()
            ]
        except:
            # if serial is not installed
            self.arduino_ports = ["None"]
        self.serialEntry = StringVar()
        self.serialEntry.set("None")
        self.serialLabel = Label(self.serialFrame,
                                 text="Serial Input:",
                                 font=(None, 20))
        self.serialCheck = OptionMenu(self.serialFrame, self.serialEntry,
                                      "None", *self.arduino_ports)
        self.createMatchButton = Button(self,
                                        text="Create Match",
                                        style="TButton",
                                        command=self.hideSetup)

        # initialize frames for UI
        # red frame and buttons
        self.redFrame = Frame(self)
        self.redScoreButton = Button(
            self.redFrame,
            text="Red +",
            style="TButton",
            command=lambda: self.incrementPoints(self.RED))
        self.redDeletePoint = Button(
            self.redFrame,
            text="Red -",
            style="TButton",
            command=lambda: self.deductPoints(self.RED))
        self.redKyonggoButton = Button(
            self.redFrame,
            text="Kyonggo +",
            style="TButton",
            command=lambda: self.callKyonggo(self.RED))
        self.redKyonggoDelete = Button(
            self.redFrame,
            text="Kyonggo -",
            style="TButton",
            command=lambda: self.deductKyonggo(self.RED))
        # blue frame and buttons
        self.blueFrame = Frame(self)
        self.blueScoreButton = Button(
            self.blueFrame,
            text="Blue +",
            style="TButton",
            command=lambda: self.incrementPoints(self.BLUE))
        self.blueDeletePoint = Button(
            self.blueFrame,
            text="Blue -",
            style="TButton",
            command=lambda: self.deductPoints(self.BLUE))
        self.blueKyonggoButton = Button(
            self.blueFrame,
            text="Kyonggo +",
            style="TButton",
            command=lambda: self.callKyonggo(self.BLUE))
        self.blueKyonggoDelete = Button(
            self.blueFrame,
            text="Kyonggo -",
            style="TButton",
            command=lambda: self.deductKyonggo(self.BLUE))
        # reset and new match frame and buttons
        self.resetFrame = Frame(self)
        self.startStop = StringVar()
        self.timerStartStop = Button(self.resetFrame,
                                     textvariable=self.startStop,
                                     style="TButton",
                                     command=self.timerPush)
        self.startStop.set("Start Round 1")
        self.newMatch = Button(self.resetFrame,
                               text="New Match",
                               style="TButton",
                               command=self.newMatch)
        self.resetMatch = Button(self.resetFrame,
                                 text="Reset Match",
                                 style="TButton",
                                 command=self.resetMatch)

        self.setup()
Exemplo n.º 53
0
    def addChan(self):
        self.center = Frame(root,
                            bg=config.bgcolor,
                            width=50,
                            height=40,
                            padx=3,
                            pady=3)

        # layout all of the main containers
        root.grid_rowconfigure(1, weight=1)
        root.grid_columnconfigure(0, weight=1)
        self.center.grid(row=1, sticky="nsew")
        #set center frame

        chanlbl = Label(self.center,
                        bg=config.bgcolor,
                        text="Enter Channel URL",
                        font=("Arial", config.fontSize))
        chanlbl.grid(column=0, row=1, sticky=left)

        channelString = Entry(self.center, width=config.textBoxWidthLG)
        #for testing
        channelString.insert(0, testURL)
        channelString.grid(column=1, columnspan=4, row=1)

        chanNameLbl = Label(self.center,
                            bg=config.bgcolor,
                            text="Channel Name",
                            font=("Arial", config.fontSize))
        chanNameLbl.grid(column=0, row=2, sticky=left)
        channelName = Entry(self.center, width=config.textBoxWidthLG)

        channelName.grid(column=1, columnspan=4, row=2)

        channelDirLbl = Label(self.center,
                              bg=config.bgcolor,
                              text="Channel Directory",
                              font=("Arial", config.fontSize))
        channelDirLbl.grid(column=0, row=3, sticky=left)
        channelDirTxt = Entry(self.center, width=config.textBoxWidthLG)

        channelDirTxt.grid(column=1, columnspan=4, row=3)

        channelName.bind("<KeyRelease>",
                         lambda e: self.writeTo(channelName, channelDirTxt))

        pgrsbar = Progressbar(self.center,
                              orient=HORIZONTAL,
                              length=400,
                              mode="determinate",
                              takefocus=True,
                              maximum=100)
        pgrsbar.place(anchor="e")
        checkCmd = IntVar()
        checkCmd.set(0)
        updatechan = Checkbutton(self.center,
                                 text="Download all videos",
                                 variable=checkCmd,
                                 onvalue=1,
                                 offvalue=0)
        updatechan.grid(column=1, row=4)
        markallCmd = IntVar()
        markallCmd.set(0)
        markall = Checkbutton(self.center,
                              text="Mark all downloaded",
                              variable=markallCmd,
                              onvalue=1,
                              offvalue=0)
        markall.grid(column=2, row=4)
        btnadd = Button(self.center,
                        text="Add",
                        font=("Arial", config.fontSize),
                        command=lambda: self.
                        add_chan(channelString, channelName, channelDirTxt,
                                 pgrsbar, markallCmd, checkCmd))
        btnadd.grid(column=3, row=4, sticky=right)
        btn = Button(self.center,
                     text="Cancel",
                     font=("Arial", config.fontSize),
                     command=lambda: self.menudo("home"))
        btn.grid(column=4, row=4, sticky=right)

        pgrsbar.grid(columnspan=4, row=6)
Exemplo n.º 54
0
def startSignup():
    global root
    root = Toplevel()
    root.attributes('-topmost', True)
    root.title("  Signup")
    root.geometry("330x620")
    # root.resizable(0,0)
    root.configure(bg="white")
    root.iconphoto(True, PhotoImage(file=assetpath + 'login.png'))
    root.tk.call('tk', 'scaling', 1.6)

    style = Style()
    style.configure("TLabel", background="white")

    Label(root,
          text="CREATE AN ACCOUNT",
          font=("ARIAL", 15, 'bold', 'italic'),
          bg="dodger blue",
          fg="white").pack(pady=(20, 20), ipadx=10, ipady=10)
    mainf = Frame(root, bg="white")
    mainf.pack(padx=30, pady=(20, 5), ipadx=30, ipady=20)

    #making the form
    Label(mainf, text="Username :"******"Arial", 8, 'bold'),
          bg="white").pack(anchor=W)
    userb = Frame(mainf, bg="dodger blue", bd=2)
    userb.pack(anchor=W)
    usere = Entry(userb, width=30)
    usere.pack(anchor=W, ipadx=5, ipady=5)

    Label(mainf, text="Email :", font=("Arial", 8, 'bold'),
          bg="white").pack(anchor=W)
    mailb = Frame(mainf, bg="dodger blue", bd=2)
    mailb.pack(anchor=W)
    maile = Entry(mailb, width=30)
    maile.pack(anchor=W, ipadx=5, ipady=5)

    Label(mainf,
          text="Choose Password :"******"Arial", 8, 'bold'),
          bg="white").pack(anchor=W)
    passb = Frame(mainf, bg="dodger blue", bd=2)
    passb.pack(anchor=W)
    passe = Entry(passb, width=30, show="*")
    passe.pack(anchor=W, ipadx=5, ipady=5)

    Label(mainf,
          text="Confirm Password :"******"Arial", 8, 'bold'),
          bg="white").pack(anchor=W)
    passcb = Frame(mainf, bg="dodger blue", bd=2)
    passcb.pack(anchor=W)
    passce = Entry(passcb, width=30, show="*")
    passce.pack(anchor=W, ipadx=5, ipady=5)

    #a curated set of security questions
    sec_ques = [
        "What is your pet name?",
        "What was the first company that you worked for?",
        "Where did you meet your spouse?",
        "Where did you go to high school/college?",
        "What city were you born in?"
    ]

    Label(mainf,
          text="Security Question :",
          font=("Arial", 8, 'bold'),
          bg="white").pack(anchor=W)
    combo = Combobox(mainf, values=sec_ques, width=29, state='readonly')
    combo.pack(anchor=W, pady=(10, 10))
    combo.current(0)
    quesb = Frame(mainf, bg="dodger blue", bd=2)
    quesb.pack(anchor=W)
    quese = Entry(quesb, width=30)
    quese.pack(anchor=W, ipadx=5, ipady=5)

    Label(
        mainf,
        text=
        "The security question will help you\n login if you forget your password",
        bg="white").pack(pady=(20, 10))
    createb = Button(mainf,
                     width=30,
                     text="Create Account",
                     font=('ARIAL', 10, 'bold'),
                     bd=0,
                     fg="white",
                     bg="dodger blue",
                     activebackground="dodger blue",
                     activeforeground="white")
    createb.pack(ipadx=5, ipady=5, padx=10, pady=20)

    root.mainloop()
Exemplo n.º 55
0
        remove(full_target_path)
        progress_value.set(progress_value.get() + step)

    progress_value.set(100)


# ------------- GUI ------------- #
# Configure window
window.title("Folder syncer")
window.geometry("560x250")

# Source folder label
Label(window, text="Source folder:").grid(row=0, column=0)

# Source folder entry
Entry(window, textvariable=source_path).grid(row=1, column=0)

# Source folder button
Button(window, command=chose_source_folder,
       text="Get source folder").grid(row=1, column=1)

# Target folder label
Label(window, text="Target folder:").grid(row=0, column=3)

# Target folder entry
Entry(window, textvariable=target_path).grid(row=1, column=3)

# Target folder button
Button(window, command=chose_target_folder,
       text="Get target folder").grid(row=1, column=4)
Exemplo n.º 56
0
class Palette(Toplevel):
    def __init__(self, master, font, symbols, **kwargs):
        Toplevel.__init__(self, master, **kwargs)
        self.title("Symbols")
        self.grab_set()
        self.resizable(False, False)
        self.columnconfigure(0, weight=1)

        style = Style(self)
        self.activebg = style.lookup("TEntry", "selectbackground", ("focus", ))

        self.text_to_insert = ""

        l = len(symbols)
        self.canvas = Canvas(self,
                             background="white",
                             width=240,
                             height=(l // 12 + 1) * 20)
        self.canvas.grid(row=0, column=0, columnspan=2, sticky="eswn")

        for i, s in enumerate(symbols):
            x = i % 12
            y = i // 12
            self.canvas.create_rectangle(x * 20,
                                         y * 20, (x + 1) * 20, (y + 1) * 20,
                                         activefill=self.activebg,
                                         fill="white",
                                         width=0,
                                         tags="square")
            self.canvas.create_text(x * 20 + 10,
                                    y * 20 + 10,
                                    text=s,
                                    activefill="white",
                                    font="%s 11" % font,
                                    tags="char")

        self.canvas.tag_bind("square", "<Button-1>", self.add_square)
        self.canvas.tag_bind("square", "<Enter>", self.enter_square)
        self.canvas.tag_bind("square", "<Leave>", self.leave_square)
        self.canvas.tag_bind("char", "<Button-1>", self.add_char)
        self.canvas.tag_bind("char", "<Enter>", self.enter_char)
        self.canvas.tag_bind("char", "<Leave>", self.leave_char)

        self.entry = Entry(self)
        self.entry.grid(row=1, column=0, sticky="ew")
        self.entry.focus_set()
        self.entry.bind("<Return>", self.ok)

        Button(self,
               text=_("Insert"),
               width=len(_("Insert")) + 1,
               command=self.ok).grid(row=1, column=1)

    def enter_square(self, event):
        c = self.canvas.find_withtag("current")
        char = self.canvas.find_above(c)
        self.canvas.itemconfigure(char, fill="white")

    def leave_square(self, event):
        c = self.canvas.find_withtag("current")
        char = self.canvas.find_above(c)
        self.canvas.itemconfigure(char, fill="black")

    def enter_char(self, event):
        c = self.canvas.find_withtag("current")
        square = self.canvas.find_below(c)
        self.canvas.itemconfigure(square, fill=self.activebg)

    def leave_char(self, event):
        c = self.canvas.find_withtag("current")
        square = self.canvas.find_below(c)
        self.canvas.itemconfigure(square, fill="white")

    def add_square(self, event):
        c = self.canvas.find_withtag("current")
        char = self.canvas.find_above(c)
        self.entry.insert("end", self.canvas.itemcget(char, "text"))

    def add_char(self, event):
        char = self.canvas.find_withtag("current")
        self.entry.insert("end", self.canvas.itemcget(char, "text"))

    def ok(self, event=None):
        self.text_to_insert = self.entry.get()
        self.destroy()

    def get_text(self):
        return self.text_to_insert
Exemplo n.º 57
0
    def edit_config(self):
        self.center = Frame(root,
                            bg=config.bgcolor,
                            width=50,
                            height=40,
                            padx=3,
                            pady=3)

        # layout all of the main containers
        root.grid_rowconfigure(1, weight=1)
        root.grid_columnconfigure(0, weight=1)
        self.center.grid(row=1, sticky="nsew")

        dbpathLBL = Label(self.center, text="Database Path")
        dbpathLBL.grid(column=0, row=0)
        dbpath = Entry(self.center, width=config.textBoxWidthLG)
        dbpath.insert(END, config.db_path)
        dbpath.grid(column=1, row=0)

        dwnloadLBL = Label(self.center, text="Download DIR")
        dwnloadLBL.grid(column=0, row=1)
        downloaddir = Entry(self.center, width=config.textBoxWidthLG)
        downloaddir.insert(END, config.download_dir)
        downloaddir.grid(column=1, row=1)

        watcherdirLBL = Label(self.center, text="Watcher DIR")
        watcherdirLBL.grid(column=0, row=2)
        watcherdir = Entry(self.center, width=config.textBoxWidthLG)
        watcherdir.insert(END, config.watcherdir)
        watcherdir.grid(column=1, row=2)
Exemplo n.º 58
0
class App_test(object):
    def __init__(self, master, fuc, query, next, pre, query_all_chapters,
                 query_text):
        self.win = master
        self.win.title('shuyaya阅读_v2.0   by: 孤月')
        # self.win.iconbitmap('./ico/gui_text_proce.ico')  # 指定界面图标
        curWidth = self.win.winfo_width()
        curHeight = self.win.winfo_height()
        scnWidth, scnHeight = self.win.maxsize()
        tmpcnf = '1340x640+500+300'  # % ((scnWidth - curWidth) / 2, (scnHeight - curHeight) / 2)
        self.win.geometry(tmpcnf)
        self.creat_res()
        self.set_position()
        self.list_box(query_all_chapters, query_text)
        # self.add_train_info()
        self.res_config(fuc, query, next, pre)
        self.train_message = {}
        self.gettime()  # 系统时间

    def creat_res(self):
        # self.v = IntVar()  # 书籍查询
        # self.v.set(True)
        self.temp = StringVar()  # 书名/作者 录入
        self.temp2 = StringVar()  # 章节名录入
        self.sys_time = StringVar()  # 系统时间

        self.E_startstation = Entry(self.win, textvariable=self.temp)
        # self.E_endstation = Entry(self.win, textvariable=self.temp2)

        self.La_startstation = Label(self.win, text="根据书名/作者搜索:")
        self.La_endstation = Label(self.win, text="书籍目录:")
        self.La_directory = Label(self.win, text="目录")
        self.La_text = Label(self.win, text="正文")
        self.La_sys_time = Label(self.win,
                                 textvariable=self.sys_time,
                                 fg='blue',
                                 font=("黑体", 20))  # 设置字体大小颜色
        self.La_pic = Label(self.win, bg="#E6E6FA")
        self.La_anthor = Label(self.win, bg="#E6E6FA")
        self.La_type = Label(self.win, bg="#E6E6FA")
        self.La_update_time = Label(self.win, bg="#E6E6FA")
        self.La_latest_chapter = Label(self.win, bg="#E6E6FA")

        self.B_search = Button(self.win, text="搜索")
        self.B_buy_tick = Button(self.win, text="阅读")
        self.B_pre_chapter = Button(self.win, text="上一章")
        self.B_next_chapter = Button(self.win, text="下一章")

        # self.R_site = Radiobutton(self.win, text="书名查询", variable=self.v, value=True)
        # self.R_price = Radiobutton(self.win, text="章节查询", variable=self.v, value=False)

        self.init_data_Text = Text(self.win)  # 原始数据录入框
        self.S_move = Scrollbar(self.win)  # 目录滚动条
        self.S_text_move = Scrollbar(self.win)  # 创建文本框滚动条

    # 设置位置
    def set_position(self):
        self.init_data_Text.place(x=430, y=40, width=870, height=550)
        self.E_startstation.place(x=10, y=50, width=145, height=30)
        self.E_startstation.insert(10, "星辰变")
        # self.E_endstation.place(x=10, y=140, width=145, height=30)
        # self.E_endstation.insert(10, "第一章 秦羽")
        self.La_startstation.place(x=10, y=10, width=130, height=30)
        self.La_endstation.place(x=10, y=100, width=60, height=30)
        self.La_sys_time.place(x=1150, y=600, width=160, height=30)
        self.La_pic.place(x=10, y=350, width=170, height=180)  # 图片
        self.La_anthor.place(x=10, y=545, width=170, height=30)
        self.La_type.place(x=10, y=575, width=170, height=30)
        self.La_update_time.place(x=10, y=605, width=170, height=30)
        self.La_latest_chapter.place(x=10, y=635, width=170, height=30)

        self.B_search.place(x=10, y=300, width=80, height=40)
        self.B_buy_tick.place(x=90, y=300, width=80, height=40)
        self.B_pre_chapter.place(x=950, y=600, width=80, height=40)
        self.B_next_chapter.place(x=1050, y=600, width=80, height=40)
        self.S_move.place(x=380, y=40, width=30, height=550)
        self.S_text_move.place(x=1300, y=40, width=30, height=550)
        # self.R_site.place(x=10, y=180, width=90, height=30)
        # self.R_price.place(x=100, y=180, width=90, height=30)
        self.La_directory.place(x=180, y=7, width=90, height=30)
        self.La_text.place(x=420, y=7, width=70, height=30)

    # 为按钮绑定事件
    def res_config(self, fuc, query, next_, pre):
        self.B_search.config(command=fuc)  # 搜索
        self.B_buy_tick.config(command=query)  # 阅读
        self.B_pre_chapter.config(command=pre)  # 上一章
        self.B_next_chapter.config(command=next_)  # 下一章
        self.S_move.config(command=self.Ls_box_ct.yview)  # 目录滚动条
        self.Ls_box_ct.config(yscrollcommand=self.S_move.set)
        self.S_text_move.config(command=self.init_data_Text.yview)  # 文本框滚动条
        self.init_data_Text.config(yscrollcommand=self.S_text_move.set)

    # def printlist(self,event):
    #     print(self.Ls_box.get(self.Ls_box.curselection()))

    def list_box(self, query_all_chapters, query_text):
        self.Ls_box = Listbox(self.win, selectmode=EXTENDED, fg='blue')
        self.Ls_box.place(x=10, y=140, width=170, height=150)
        self.Ls_box.bind(
            '<Double-Button-1>', query_all_chapters
        )  # 鼠标双击  更多事件请看http://www.cnblogs.com/hackpig/p/8195678.html
        self.Ls_box.insert(END, "获取排行榜")  # 请输入书名&作者进行查询

        self.Ls_box_ct = Listbox(self.win, selectmode=EXTENDED, fg='blue')
        self.Ls_box_ct.place(x=200, y=40, width=180, height=550)
        self.Ls_box_ct.bind('<Double-Button-1>', query_text)

    def add_train_info(self):
        lis_train = ["C" + str(x) for x in range(0, 2)]
        tuple_train = tuple(lis_train)
        self.tree = Treeview(self.win,
                             columns=tuple_train,
                             height=30,
                             show="headings")
        self.tree.place(x=200, y=40, width=180, height=550)
        train_info = [' 书名 ', ' 作者 ']
        for i in range(0, len(lis_train)):
            self.tree.column(
                lis_train[i], width=len(train_info[i]) * 11,
                anchor='w')  # must be n, ne, e, se, s, sw, w, nw, or center
            self.tree.heading(lis_train[i], text=train_info[i])

    # 实时显示时钟
    def gettime(self):
        # 获取当前时间
        self.sys_time.set(time.strftime("%H:%M:%S"))
        # 每隔一秒调用函数自身获取时间
        self.win.after(1000, self.gettime)
    def initUI(self):
        """
        Function defines basic layout of whole program.
        """

        # Start instances atributes
        self.master.title("Image Compare")
        self.pack(fill=BOTH, expand=1)
        self.listOfPaths = []
        self.lenght = 0
        self.i = 0
        self.directory1 = "C:\\Plots1"
        self.directory2 = "C:\\Plots2"

        Style().configure("TFrame", background="#333")

        # Defining entrys, lables and text fields
        self.path1 = Entry(self, width=50)
        self.path1.place(x=10, y=10)

        self.path2 = Entry(self, width=50)
        self.path2.place(x=10, y=35)

        self.startFromEntry = Entry(self, width=5)
        self.startFromEntry.place(x=550, y=10)

        self.plot1PathText = Text(self, height=3, width=75)
        self.plot1PathText.place(x=620, y=670)

        self.plot2PathText = Text(self, height=3, width=75)
        self.plot2PathText.place(x=1230, y=670)

        self.lb = Listbox(self, height=15, width=100)
        self.lb.place(x=620, y=740)

        self.numberOfPlotsText = Text(self, height=1, width=5)
        self.numberOfPlotsText.place(x=790, y=10)

        self.currentPlotsText = Text(self, height=1, width=5)
        self.currentPlotsText.place(x=930, y=10)

        numberOfPlotsLabel = Label(self, text="Nuber of plots:")
        numberOfPlotsLabel.place(x=700, y=10)

        currentPlotsLabel = Label(self, text="Current plot:")
        currentPlotsLabel.place(x=850, y=10)

        # Defining buttons
        previousButton = Button(self,
                                text="Previous",
                                command=self.previousButtonFunction)
        previousButton.place(x=10, y=670)

        nextButton = Button(self, text="Next", command=self.nextButtonFunction)
        nextButton.place(x=100, y=670)

        differentButton = Button(self,
                                 text="Different",
                                 command=self.differentButtonFunction)
        differentButton.place(x=300, y=670)

        deleteButton = Button(self,
                              text="Delete",
                              command=self.deleteButtonFunction)
        deleteButton.place(x=380, y=670)

        getPathButton = Button(self,
                               text="Get Path",
                               command=self.get_filepaths)
        getPathButton.place(x=350, y=8)

        startFromButton = Button(self,
                                 text="Start From",
                                 command=self.startFromButtonFunction)
        startFromButton.place(x=600, y=8)
Exemplo n.º 60
0
    def listchans(self,
                  index=None,
                  tagsearch="",
                  archived=0,
                  ob=Channel.displayname,
                  so=asc):
        self.center = Frame(root,
                            bg=config.bgcolor,
                            width=50,
                            height=40,
                            padx=3,
                            pady=3)

        # layout all of the main containers
        root.grid_rowconfigure(1, weight=1)
        root.grid_columnconfigure(0, weight=1)
        self.center.grid(row=1, sticky="nsew")

        channels = database.get_channels(archived, ob, so)
        if so == desc:
            so = asc
        else:
            so = desc

        tree = Treeview(self.center)

        sstring = Entry(self.center, width=config.textBoxWidth)
        sstring.bind(
            "<KeyRelease-Return>",
            lambda e: self.listchans(None, sstring.get(), archived, ob, so))
        sstring.grid(column=0, row=0)
        if len(tagsearch) >= 1:
            sstring.focus()
            sstring.insert(0, tagsearch)
        searchbutton = Button(self.center,
                              text="Search",
                              command=lambda: self.listchans(
                                  None, sstring.get(), archived, ob, so))
        searchbutton.grid(column=1, row=0)

        clearbutton = Button(self.center, text="Clear Search")
        clearbutton.configure(command=lambda: self.listchans(archived))
        clearbutton.grid(column=3, row=0)

        tree["columns"] = ("one", "two")

        tree.column("#0", width=210, minwidth=10, stretch=YES)
        tree.column("one", width=350, minwidth=250, stretch=YES)
        tree.column("two", width=210, minwidth=10, stretch=YES)

        tree.heading("#0",
                     text="Last Check",
                     anchor=W,
                     command=lambda: self.listchans(None, sstring.get(
                     ), archived, Channel.lastcheck, so))

        tree.heading("one",
                     text="Channel Name",
                     anchor=E,
                     command=lambda: self.listchans(None, sstring.get(
                     ), archived, Channel.displayname, so))
        tree.heading("two",
                     text="Last Published",
                     command=lambda: self.listchans(None, sstring.get(
                     ), archived, Channel.lastpub, so))
        i = 0
        tree.tag_configure('oddrow', background='#88DD88')
        tree.tag_configure('evenrow', background='#FFFFFF')
        tree.tag_configure('archivedodd',
                           background="#88DD88",
                           foreground="#aaaaaa")
        tree.tag_configure('archivedeven',
                           background='#FFFFFF',
                           foreground="#cccccc")

        for item in channels:
            foldername = "folder" + str(i)

            if i % 2 == 0:
                color = "evenrow"
            else:
                color = "oddrow"

            if item.archive == True:
                if i % 2 == 0:
                    color = "archivedeven"
                else:
                    color = "archivedodd"

            if tagsearch.lower() in str(
                    item.displayname).lower() or tagsearch.lower() in str(
                        item.dldir).lower() or tagsearch.lower() in str(
                            item.yt_channelid).lower():
                if item.lastpub == None:
                    lastpub = "N/A"
                else:
                    lastpub = time.ctime(item.lastpub)

                foldername = tree.insert("",
                                         "end",
                                         text=time.ctime(item.lastcheck),
                                         values=(item.displayname, lastpub),
                                         tags=(color, item.displayname,
                                               item.dldir, item.yt_channelid))

                tree.insert(foldername,
                            "end",
                            text="Directory",
                            values=(item.dldir, ),
                            tags=(color))

                tree.insert(foldername,
                            "end",
                            text="Last Published",
                            values=(lastpub, ),
                            tags=(color))

                i = i + 1

        vertscroll = Scrollbar(self.center)
        vertscroll.config(command=tree.yview)
        tree.config(yscrollcommand=vertscroll.set, height=20)
        vertscroll.grid(column=4, row=1, sticky='NSE')
        tree.bind("<Double-1>", self.item_selected)

        tree.grid(row=1, columnspan=4, sticky="NSEW")
        tree.focus(index)
        tree.selection_set(index)
        tree.see(index)