Пример #1
0
    def initUI(self):
      
        self.parent.title("Listbox") 
        
        self.pack(fill=BOTH, expand=1)

        IP_list = ['IP Address 1', 'IP Address 2', 'IP Address 3', 'IP Address 4', 'IP Address 5', 'IP Address 6', 'IP Address 7', 'IP Address 8', 'IP Address 9', 'IP Address 10', 'IP Address 11', 'IP Address 12', 'IP Address 13', 'IP Address 14', 'IP Address 15', 'IP Address 16']
        IP_numbers = ['150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1', '150.0.0.1']

        lb = Listbox(self)
        for i in IP_list:
            lb.insert(END, i)
            
        lb.bind("<<ListboxSelect>>", self.onSelect)    
            
        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)        
        self.label.place(x=20, y=270)

        #
        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)
        
        #lbl = Label(self, text="Windows")
        lb.grid(sticky=W, pady=40, padx=50)
        
        #lb = Text(self)
        lb.grid(row=1, column=0, columnspan=2, rowspan=4, 
            padx=50, sticky=E+W+S+N)
        
        abtn = Button(self, text="Activate")
        abtn.grid(row=1, column=3)

        cbtn = Button(self, text="Close")
        cbtn.grid(row=2, column=3, pady=4)
        
        hbtn = Button(self, text="Help")
        hbtn.grid(row=5, column=0, padx=5)

        obtn = Button(self, text="OK")
        obtn.grid(row=5, column=3)
Пример #2
0
    def initUI(self):
        self.parent.title("Listbox")
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss',
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)

        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.place(x=20, y=210)
def A_t_a_mode(event=0):
    def add_user(work_mode, timeout=1):
        global user_list
        sock.settimeout(timeout)
        try:
            conn, addr = sock.accept()
        except:
            return
        name = pickle.loads(conn.recv(1024))
        conn.send(pickle.dumps(work_mode))
        user_list[name] = (conn, addr)
        lbox.insert(0, name)

    def all_to_all_send_recv():
        global clip, clip_ch_flag, user_list, request, request_ch_flag, clip_user, request_user
        if request_ch_flag:
            request_ch_flag = False
            if request != "user_list_get":
                if request == "server":
                    user_list[request_user][0].send(
                        pickle.dumps([pyperclip.paste(), "clip"]))
                    return

                user_list[request][0].send(
                    pickle.dumps(["get_clip", "request"]))
                while True:
                    if clip_ch_flag:
                        clip_ch_flag = False
                        user_list[request_user][0].send(
                            pickle.dumps([clip, "clip"]))
                        break
            else:
                user_list[request_user][0].send(
                    pickle.dumps([[i for i in user_list] + ["server"],
                                  "user_list"]))
                print("user list send")

    def server_get_clip(event):
        global clip, clip_ch_flag, user_list, request, request_ch_flag, clip_user, request_user
        try:
            name = lbox.get(lbox.curselection())
        except:
            return
        print(user_list)
        user_list[name][0].send(pickle.dumps(["get_clip", "request"]))
        while True:
            if clip_ch_flag:
                clip_ch_flag = False
                pyperclip.copy(clip)
                print("clip pasted to clip", name)
                break
            sleep(0.1)

    def entry_bind(event):
        port = entry_port.get()
        if not port.isdigit() or int(port) in range(0, 1024):
            entry_port.delete(0, END)
            entry_port.insert(0, "Incorrect port")
            entry_port.after(1000, lambda: entry_port.delete(0, END))
            return
        entry_port.destroy()
        port_label_value = Label(text=port, bg="#33FFFF", fg="white")
        port_label_value.place(x=55, y=40)
        start_button["text"] = "Exit"
        start_button.bind("<Button-1>", func=lambda x: exit())
        status_label["text"] = "Starting server"
        status_label["bg"] = "orange"
        sock.bind(('', int(port)))
        sock.listen(10)
        work_thread.start()
        status_label["text"] = "Server started"
        status_label["bg"] = "green"

    def thread_cycle(event=0):
        global work_mode
        while True:
            add_user(work_mode)
            recive_server_controller()
            all_to_all_send_recv()
            sleep(1)

    work_thread = Thread(target=thread_cycle)
    work_thread.daemon = True
    root.destroy()
    window = Tk()
    window.resizable(False, False)
    window.geometry("400x220")
    window.title("A-t-A mode | server")

    get_clip_button = Button(window, text="Get Clipboard")
    lbox = Listbox(width=20, height=10)
    entry_port = Entry(width=15)
    port_label = Label(text="Port")
    start_button = Button(window, text="Start", width=17)
    status_label = Label(text="Server stopped", bg="red", height=1, width=20)
    nick_name_label = Label(text="Your nickname is Server",
                            bg="#00CCFF",
                            fg="white",
                            height=1,
                            width=20)
    ip_label = Label(text=("Your IP is {}".format(
        socket.gethostbyname(socket.gethostname()))),
                     bg="#00CCFF",
                     fg="white",
                     height=1,
                     width=20)

    ip_label.place(x=25, y=160)
    nick_name_label.place(x=25, y=10)
    status_label.place(x=25, y=180)
    port_label.place(x=25, y=40)
    entry_port.place(x=55, y=40)
    start_button.place(x=25, y=70)
    lbox.place(x=250, y=10)
    get_clip_button.place(x=270, y=180)

    start_button.bind("<Button-1>", func=entry_bind)
    get_clip_button.bind("<Button-1>", func=server_get_clip)

    window.mainloop()
Пример #4
0
class CadastroVeiculo(Toplevel):
    '''Classe interface cadastrar veiculo'''
    def __init__(self, master=None):
        Toplevel.__init__(self, master=master)
        self.veiculo = Veiculo()
        self.dao = VeiculoDAO()

        self.geometry('1500x850+0+0')
        self.title('Cadastro de veiculos')
        self.resizable(0, 0)  # impede de maximizar
        self.configure(background='#c9c9ff')

        self.heading = Label(self,
                             text="Cadastrar veiculos",
                             bg='#c9c9ff',
                             fg='white',
                             font=('Verdana 20 bold'))
        self.heading.place(x=650, y=0)

        # marca =========================================================================
        self.marca = Label(self,
                           text="Marca do veículo :",
                           bg='#c9c9ff',
                           fg='white',
                           font=('Verdana 15 bold'))
        self.marca.place(x=10, y=70)
        self.marca_entry = Entry(self, width=20, font=('Verdana 15 bold'))
        self.marca_entry.place(x=300, y=70)

        # modelo =========================================================================
        self.modelo = Label(self,
                            text="Modelo:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.modelo.place(x=10, y=120)
        self.modelo_entry = Entry(self, width=20, font=('Verdana 15 bold'))
        self.modelo_entry.place(x=300, y=120)

        # ano =========================================================================
        self.ano = Label(self,
                         text="Ano:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.ano.place(x=10, y=170)
        self.ano_entry = Entry(self, width=20, font=('Verdana 15 bold'))
        self.ano_entry.place(x=300, y=170)

        # cor =========================================================================
        self.cor = Label(self,
                         text="Cor:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.cor.place(x=10, y=220)
        self.cor_entry = Entry(self, width=20, font=('Verdana 15 bold'))
        self.cor_entry.place(x=300, y=220)
        # self.cor_entry.insert(END, datetime.date.today())

        # tanque =========================================================================
        self.tanque = Label(self,
                            text="Capacidade do tanque:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.tanque.place(x=10, y=270)
        self.tanque_entry = Entry(self, width=20, font=('Verdana 15 bold'))
        self.tanque_entry.place(x=300, y=270)
        self.tanque_entry.insert(END, "litros")

        # combustivel =========================================================================
        self.combustivel = Label(self,
                                 text="Tipo de Combustível:",
                                 bg='#c9c9ff',
                                 fg='white',
                                 font=('Verdana 15 bold'))
        self.combustivel.place(x=10, y=320)
        self.combustivel_entry = Entry(self,
                                       width=20,
                                       font=('Verdana 15 bold'))
        self.combustivel_entry.place(x=300, y=320)

        # consumo cidade =========================================================================
        self.consumo_cidade = Label(self,
                                    text="Consumo na cidade:",
                                    bg='#c9c9ff',
                                    fg='white',
                                    font=('Verdana 15 bold'))
        self.consumo_cidade.place(x=10, y=370)
        self.consumo_cidade_entry = Entry(self,
                                          width=20,
                                          font=('Verdana 15 bold'))
        self.consumo_cidade_entry.place(x=300, y=370)

        self.consumo_cidade_entry.insert(END, "l/km")

        self.consumo_estrada = Label(self,
                                     text="Consumo na estrada:",
                                     bg='#c9c9ff',
                                     fg='white',
                                     font=('Verdana 15 bold'))
        self.consumo_estrada.place(x=10, y=420)
        self.consumo_estrada_entry = Entry(self,
                                           width=20,
                                           font=('Verdana 15 bold'))
        self.consumo_estrada_entry.place(x=300, y=420)
        self.consumo_estrada_entry.insert(END, "l/km")

        self.tempo_0_100 = Label(self,
                                 text="Tempo de 0km/h a 100km/h:",
                                 bg='#c9c9ff',
                                 fg='white',
                                 font=('Verdana 15 bold'))
        self.tempo_0_100.place(x=10, y=470)
        self.tempo_0_100_entry = Entry(self,
                                       width=20,
                                       font=('Verdana 15 bold'))
        self.tempo_0_100_entry.place(x=300, y=470)

        self.chassi = Label(self,
                            text="Chassi:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.chassi.place(x=10, y=520)
        self.chassi_entry = Entry(self, width=20, font=('Verdana 15 bold'))
        self.chassi_entry.place(x=300, y=520)

        self.placa = Label(self,
                           text="Placa:",
                           bg='#c9c9ff',
                           fg='white',
                           font=('Verdana 15 bold'))
        self.placa.place(x=10, y=570)
        self.placa_entry = Entry(self, width=20, font=('Verdana 15 bold'))
        self.placa_entry.place(x=300, y=570)

        self.tamanho_pneu = Label(self,
                                  text="Tamanho do pneu:",
                                  bg='#c9c9ff',
                                  fg='white',
                                  font=('Verdana 15 bold'))
        self.tamanho_pneu.place(x=10, y=620)
        self.tamanho_pneu_entry = Entry(self,
                                        width=20,
                                        font=('Verdana 15 bold'))
        self.tamanho_pneu_entry.place(x=300, y=620)

        self.som = Label(self,
                         text="Som:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.som.place(x=10, y=670)
        self.som_entry = Entry(self, width=20, font=('Verdana 15 bold'))
        self.som_entry.place(x=300, y=670)

        self.valor_diaria = Label(self,
                                  text="valor da diária:",
                                  bg='#c9c9ff',
                                  fg='white',
                                  font=('Verdana 15 bold'))
        self.valor_diaria.place(x=10, y=720)
        self.valor_diaria_entry = Entry(self,
                                        width=20,
                                        font=('Verdana 15 bold'))
        self.valor_diaria_entry.place(x=300, y=720)
        self.valor_diaria_entry.insert(END, 'R$ ')

        # BOTAO LIMPAR  =========================================================================
        self.botao_limpar = Button(self,
                                   text="Limpar",
                                   width=31,
                                   height=1,
                                   bg='#ffdfba',
                                   fg='black',
                                   font=('Verdana 15 bold'),
                                   command=self.clear_all)
        self.botao_limpar.place(x=600, y=700)

        self.botao_cadastrar = Button(self,
                                      text="Cadastrar",
                                      width=62,
                                      height=1,
                                      bg='#baffc9',
                                      fg='black',
                                      font=('Verdana 15 bold'),
                                      command=self.get_items)
        self.botao_cadastrar.place(x=600, y=650)

        self.botao_sair = Button(self,
                                 text="Sair",
                                 width=30,
                                 height=1,
                                 bg='#ffb3ba',
                                 fg='black',
                                 font=('Verdana 15 bold'),
                                 command=self.close)
        self.botao_sair.place(x=1048, y=700)

        self.veiculo_box = Listbox(self,
                                   width=63,
                                   height=20,
                                   font=('Verdana 15 bold'))
        self.veiculo_box.place(x=600, y=120)

        self.scrollbar_veiculo = Scrollbar(self)
        self.veiculo_box.configure(yscrollcommand=self.scrollbar_veiculo.set)
        self.scrollbar_veiculo.configure(command=self.veiculo_box.yview)
        self.scrollbar_veiculo.place(x=1485,
                                     y=120,
                                     relheight=0.62,
                                     anchor='ne')

        self.pesquisar_veiculo = Label(self,
                                       text="Lista de veiculos Cadastrados:",
                                       bg='#c9c9ff',
                                       font=('Verdana 15 bold'))
        self.pesquisar_veiculo.place(x=900, y=65)

        self.view_command()

    def view_command(self):
        "método para visualização dos resultados"
        try:
            rows = self.dao.view()
            self.veiculo_box.delete(0, END)
            for r in rows:
                self.veiculo_box.insert(END, r)
        except Exception as e:
            print(e)

    def get_items(self):
        self.veiculo.marca = self.marca_entry.get()
        self.veiculo.modelo = self.modelo_entry.get()
        self.veiculo.ano = self.ano_entry.get()
        self.veiculo.cor = self.cor_entry.get()
        self.veiculo.tanque = self.tanque_entry.get()
        self.veiculo.combustivel = self.combustivel_entry.get()
        self.veiculo.consumo_cidade = self.consumo_cidade_entry.get()
        self.veiculo.consumo_estrada = self.consumo_estrada_entry.get()
        self.veiculo.tempo_0_100 = self.tempo_0_100_entry.get()
        self.veiculo.chassi = self.chassi_entry.get()
        self.veiculo.placa = self.placa_entry.get()
        self.veiculo.tamanho_pneu = self.tamanho_pneu_entry.get()
        self.veiculo.som = self.som_entry.get()
        self.veiculo.valor_diaria = self.valor_diaria_entry.get()

        if (self.veiculo.marca == '' or self.veiculo.modelo == ''
                or self.veiculo.ano == '' or self.veiculo.cor == ''
                or self.veiculo.tanque == '' or self.veiculo.combustivel == ''
                or self.veiculo.consumo_cidade == ''
                or self.veiculo.consumo_estrada == ''
                or self.veiculo.tempo_0_100 == '' or self.veiculo.chassi == ''
                or self.veiculo.placa == '' or self.veiculo.tamanho_pneu == ''
                or self.veiculo.som == '' or self.veiculo.valor_diaria == ''):
            tkinter.messagebox.showinfo(
                "Aviso:", "POR FAVOR PREENCHER TODOS OS CAMPOS!")
        else:
            try:
                self.veiculo.tanque = float(self.veiculo.tanque)
                self.veiculo.consumo_cidade = float(
                    self.veiculo.consumo_cidade)
                self.veiculo.consumo_estrada = float(
                    self.veiculo.consumo_estrada)
                self.veiculo.tempo_0_100 = float(self.veiculo.tempo_0_100)
                self.veiculo.valor_diaria = float(self.veiculo.valor_diaria)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'Os campos tamanho do tanque, Consumo na cidade, consumo ma estrada, tempo_0_100 e valor da diária devem ser preenchidos com números!'
                )
            else:
                try:
                    self.dao.insert(self.veiculo)
                except Exception as e:
                    print(e)
                else:
                    tkinter.messagebox.showinfo(
                        'Aviso!', 'Cadastro Realizado com Sucesso!')
                    self.clear_all()
                    self.view_command()

    def clear_all(self):
        self.marca_entry.delete(0, END)
        self.modelo_entry.delete(0, END)
        self.ano_entry.delete(0, END)
        self.cor_entry.delete(0, END)
        self.tanque_entry.delete(0, END)
        self.tanque_entry.insert(END, "litros")

        self.combustivel_entry.delete(0, END)

        self.consumo_cidade_entry.delete(0, END)
        self.consumo_cidade_entry.insert(END, "l/km")

        self.consumo_estrada_entry.delete(0, END)
        self.consumo_estrada_entry.insert(END, "l/km")

        self.tempo_0_100_entry.delete(0, END)
        self.tempo_0_100_entry.insert(END, "segundos")

        self.chassi_entry.delete(0, END)
        self.placa_entry.delete(0, END)
        self.tamanho_pneu_entry.delete(0, END)
        self.som_entry.delete(0, END)
        self.valor_diaria_entry.delete(0, END)
        self.valor_diaria_entry.insert(END, 'R$ ')

    def close(self):
        self.dao.close()
        self.destroy()

    def run(self):
        self.mainloop()
class User_Interface:
    def __init__(self, master):
        
        self.df = pd.read_csv ('diabetes.csv')
        #intialising empty arrays to store data results 
        #testing/training
        self.x_train = []
        self.x_test = []
        self.y_test = []
        self.y_train = []
        
        self.master = master
        self.master.title('Diabetes Classification')
        self.master.config(background = 'light grey')
        self.master.geometry("800x650+30+30")
        self.create_window(master)
        
    def create_window(self, master):
             #===============Data Analysis Danvas==========
        self.canvas = Canvas(self.master, height= 180, width=380, background = 'light grey',borderwidth=1, relief=GROOVE)
        self.canvas.place(x=10, y=20)
        self.listbox = Listbox(self.master, height = 9, width = 15)
        self.listbox.place(x=40, y=40)
        self.title= Label(self.master, text='Data Analysis', background='light grey')
        self.title.place(x=40,y=20)
        self.title.config(font=('System', 10))
        #split data button     
        self.load_button= Button(self.master, text='Split Data')
        self.load_button.place(x=230, y=160)
        self.load_button.config(background= 'light grey', activebackground= 'grey', command= self.preprocessing)
        #Data Ananysis text boxese
        self.class_type = Entry(self.master, width= 10)
        self.class_type.place(x=280, y=40)
        self.class_typel = Label(self.master, text='DataSet Class Labels', background= 'light grey')
        self.class_typel.place(x=160, y=40)
        self.class_typel.config(font=('Times', 9))
        self.class_typel2 = Label(self.master, text='Count of Data Items', background= 'light grey')
        self.class_typel2.place(x=160, y=60)
        self.class_typel2.config(font=('Times', 9))
        self.class_type2 = Entry(self.master, width= 10)
        self.class_type2.place(x=280, y=60)
        self.test_datat= Entry(self.master, width=10)
        self.test_datat.place(x=280, y=80)
        self.test_data= Label(self.master, text='Testing Data Items', background='light grey')
        self.test_data.place(x=160, y=80)
        self.test_data.config(font=('Times', 9))
        self.train_datat= Entry(self.master, width=10)
        self.train_datat.place(x=280, y=100)
        self.train_data= Label(self.master, text='Training Data Items', background='light grey')
        self.train_data.place(x=160, y=100)
        self.train_data.configure(font=('Times', 9))
            #==============KNN Canas=====================
        self.canvas_1 = Canvas(self.master, height= 180, width=380, background = 'light grey',borderwidth=1, relief=GROOVE)
        self.canvas_1.place(x=405, y=20)
        self.title= Label(self.master, text='K Nearest Neighbor', background='light grey')
        self.title.place(x=440,y=20)
        self.title.config(font=('System', 10))
        #knn checkboxes and labels    
        self.train_l = Label(self.master, text= 'Enter K', background='light grey')
        self.train_l.place(x=440, y=40)
        self.train_l.config(font=('Times', 9))
        self.train_l = Entry(self.master, width= 10)
        self.train_l.place(x=500, y=40)
        self.train2 = Label(self.master, text='Train knn without Analysis', background='light grey')
        self.train2.place(x=440, y=60)
        self.train2.config(font=('Times', 9))
        self.var = IntVar()
        self.train2 = Checkbutton(self.master, background='light grey', variable = self.var)
        self.train2.place(x=660, y=60)
        self.train_l2 = Label(self.master, text='Train with Principal Component Analysis', background='light grey')
        self.train_l2.place(x=440, y=80)
        self.train_l2.config(font=('Times', 9))
        self.var1 = IntVar()
        self.train_l2 = Checkbutton(self.master, background='light grey', variable = self.var1)
        self.train_l2.place(x=660, y=80)
        self.train_l3 = Label(self.master, text='Train with Linear Discriminant Analysis', background='light grey')
        self.train_l3.place(x=440, y=100)
        self.train_l3.config(font=('Times', 9))
        self.var2 = IntVar()
        self.train_l3 = Checkbutton(self.master, background='light grey', variable = self.var2)
        self.train_l3.place(x=660, y=100)
        #knn button
        self.kb= Button(self.master, text='Train')
        self.kb.place(x=560, y=160)
        self.kb.config(background= 'light grey', activebackground= 'grey', command= self.knn_checked)
            #==============Naive Bayes===================
        self.canvas_2 = Canvas(self.master, height= 180, width=380, background = 'light grey',borderwidth=1, relief=GROOVE)
        self.canvas_2.place(x=10, y=220)
        self.ntitle= Label(self.master, text='Naive Bayes', background='light grey')
        self.ntitle.place(x=40,y=220)
        self.ntitle.config(font=('System', 10))
        #naive bayes checkboxes and labels
        self.ntrain_l = Label(self.master, text='Train without Analysis', background='light grey')
        self.ntrain_l.place(x=40, y=260)
        self.ntrain_l.config(font=('Times', 9))
        self.var3 = IntVar()
        self.ntrain_l = Checkbutton(self.master, background='light grey', variable = self.var3)
        self.ntrain_l.place(x=260, y=260)
        self.ntrain_l2 = Label(self.master, text='Train with Principal Component Analysis', background='light grey')
        self.ntrain_l2.place(x=40, y=280)
        self.ntrain_l2.config(font=('Times', 9))
        self.var4 = IntVar()
        self.ntrain_l2 = Checkbutton(self.master, background='light grey', variable = self.var4)
        self.ntrain_l2.place(x=260, y=280)
        self.ntrain_l3 = Label(self.master, text='Train with Linear Discriminant Analysis', background='light grey')
        self.ntrain_l3.place(x=40, y=300)
        self.ntrain_l3.config(font=('Times', 9))
        self.var5 = IntVar()
        self.ntrain_l3 = Checkbutton(self.master, background='light grey', variable = self.var5)
        self.ntrain_l3.place(x=260, y=300)
        #Niave Bayes train button
        self.nb= Button(self.master, text='Train')
        self.nb.place(x=160, y=360)
        self.nb.config(background= 'light grey', activebackground= 'grey', command= self.nb_checked)
            #=============Neaural Network Canvas============
        self.canvas_3 = Canvas(self.master, height= 180, width=380, background = 'light grey',borderwidth=1, relief=GROOVE)
        self.canvas_3.place(x=405, y=220)
        self.nntitle= Label(self.master, text='Neural Network', background='light grey')
        self.nntitle.place(x=440,y=220)
        self.nntitle.config(font=('System', 10))
        #neaural network checkboxes and labels
        self.nntrain_l = Label(self.master, text='Train without Analysis', background='light grey')
        self.nntrain_l.place(x=440, y=260)
        self.nntrain_l.config(font=('Times', 9))
        self.var6 = IntVar()
        self.nntrain_l = Checkbutton(self.master, background='light grey', variable= self.var6)
        self.nntrain_l.place(x=660, y=260)
        self.nntrain_l2 = Label(self.master, text='Train with Principal Component Analysis', background='light grey')
        self.nntrain_l2.place(x=440, y=280)
        self.nntrain_l2.config(font=('Times', 9))
        self.var7 = IntVar()
        self.nntrain_l2 = Checkbutton(self.master, background='light grey', variable=self.var7)
        self.nntrain_l2.place(x=660, y=280)
        self.nntrain_l3 = Label(self.master, text='Train with Linear Discriminant Analysis', background='light grey')
        self.nntrain_l3.place(x=440, y=300)
        self.nntrain_l3.config(font=('Times', 9))
        self.var8 = IntVar()
        self.nntrain_l3 = Checkbutton(self.master, background='light grey', variable=self.var8)
        self.nntrain_l3.place(x=660, y=300)
        #neaural network button 
        self.nn= Button(self.master, text='Train', command = self.mlp_checked)
        self.nn.place(x=570, y=360)
        self.nn.config(background= 'light grey', activebackground= 'grey', )
            #=============Classification Results Canvas======================
        self.canvas_4 = Canvas(self.master, height= 230, width=780, background = 'gray68',borderwidth=1, relief=SUNKEN)
        self.canvas_4.place(x=10, y=410)
        self.rtitle= Label(self.master, text='Classification Report', background='gray68')
        self.rtitle.place(x=20, y=420)
        self.rtitle.config(font=('System', 10))
        #classification results text boxes
        self.class_accl= Label(self.master, text='Accuracy', background='gray68')
        self.class_accl.place(x=20, y=470)
        self.class_accl.configure(font=('Times', 9))
        self.class_acc = Entry(self.master, width= 10)
        self.class_acc.place(x=180, y=470)
        self.class_sens= Label(self.master, text= 'Sensitivity', background='gray68')
        self.class_sens.configure(font=('Times', 9))
        self.class_sens.place(x=20, y=500)
        self.class_sense= Entry(self.master, width=10)
        self.class_sense.place(x=180, y=500)
        self.class_spec= Label(self.master, text= 'Specificity', background='gray68')
        self.class_spec.configure(font=('Times', 9))
        self.class_spec.place(x=20, y=530)
        self.class_spece= Entry(self.master, width=10)
        self.class_spece.place(x=180, y=530)
        self.rocl = Label(self.master, text= 'ROC/AUC Score', background='gray68')
        self.rocl.configure(font=('Times', 9))
        self.rocl.place(x=20, y=560)
        self.rocscore = Entry(self.master, width=10)
        self.rocscore.place(x=180, y=560)
        #auc-roc curve canvas
        self.canvas_im = Canvas(self.master, height= 210, width=260, background = 'gray68',borderwidth=1, relief=SUNKEN)
        self.canvas_im.pack()
        self.canvas_im.place(x=250, y=420) 
        self.canvas_iml= Label(self.master, text='AUC-ROC Curve', background='white',borderwidth=1, relief=SUNKEN)
        self.canvas_iml.place(x=340, y=612)
        self.canvas_iml.configure(font=('Times', 8))
        #scatter graph canvas
        self.canvas_im2 = Canvas(self.master, height= 210, width=260, background = 'gray68',borderwidth=1, relief=SUNKEN)
        self.canvas_im2.pack()
        self.canvas_im2.place(x=520, y=420)
        self.canvas_im2l= Label(self.master, text='X=PCA=1 Y=PCA=2', background='white',borderwidth=1, relief=SUNKEN)
        self.canvas_im2l.place(x=600, y=612)
        self.canvas_im2l.configure(font=('Times', 9))

    #listbox and textboxes for data analysis when split data is clicked   
    def clear_dataset(self):
        self.listbox.delete(0,"end")
        self.class_type.delete(0,"end")
        self.class_type2.delete(0,"end")
    #load diabetes dataset into listbox and data feilds when split data has been clicked  
    def open_file(self):
        self.clear_dataset()
        data_class = self.df.iloc[:,-1]
        d_class = data_class.unique()
        d_count = data_class.count()
        #insert target feature into entry box
        self.class_type.insert("end", d_class)
        #insert count of data items into entry box
        self.class_type2.insert("end", d_count)
        data_list = list(self.df)
        #for everyitem/column in datalist
        for items in data_list:
            #insert colomns into listbox
            self.listbox.insert("end", items)
            
    #preparing the data before classification
    def preprocessing(self):
        self.clear_results()
        #outcome colomn with all rows
        x = self.df.drop('Outcome', 1)
        #just outcome column
        y = self.df['Outcome']
        #split training set 75% test set 25%
        self.x_train,self.x_test,self.y_train,self.y_test = train_test_split(x, y, test_size=0.25, random_state=0)
        train_set = len(self.x_train + self.y_train)
        test_set = len(self.x_test + self.y_test)
        #add testing and traing data into text boxs
        self.test_datat.insert("end", test_set)
        self.train_datat.insert("end", train_set)
        scaler = MinMaxScaler()
        self.x_train = scaler.fit_transform(self.x_train)
        self.x_test = scaler.transform(self.x_test)
        #add two components scatter graph
        self.img2=img2 =ImageTk.PhotoImage(Image.open("pca_scatter.png"))
        self.canvas_im2.create_image(0,0,anchor = "nw", image=img2)
#--------------CheckBoxes-------------------------------------------------
    #show all classifier roc-auc results in canvas   
    def knn_checked(self):
        #get if checked
        var = self.var.get()
        var1 = self.var1.get()
        var2 = self.var2.get()
        self.clear_checked()
        self.canvas_im.delete("all")
        #if knn without analysis is checked then show knn roc curve
        if var ==1:
            self.knn_own()
            self.img=img =ImageTk.PhotoImage(Image.open("knn_img.png"))
            self.canvas_im.create_image(0,0,anchor = "nw", image=img)
        #if pca knn is checked then show knn with pca roc curve    
        if var1 == 1:
            self.knn_pca()
            self.img=img =ImageTk.PhotoImage(Image.open("pk_img.png"))
            self.canvas_im.create_image(0,0,anchor = "nw", image=img)
        #if lda knn is checked then show knn with lda roc curve
        if var2 == 1:
            self.knn_lda()
            self.img=img =ImageTk.PhotoImage(Image.open("ldak_img.png"))
            self.canvas_im.create_image(0,0,anchor = "nw", image=img) 
            
    def nb_checked(self):
        var3 = self.var3.get()
        var4 = self.var4.get()
        var5 = self.var5.get()
        self.clear_checked()
        self.canvas_im.delete("all")
        #if naive bayes without analysis is checked then show naive bayes roc curve
        if var3 == 1:
            self.naive_bayes()
            self.img=img =ImageTk.PhotoImage(Image.open("nb_img.png"))
            self.canvas_im.create_image(0,0,anchor = "nw", image=img)
        #if naive bayes with pca is cheked then show naive bayes with pca roc curve
        if var4 == 1:
            self.naiveb_pca()
            self.img=img =ImageTk.PhotoImage(Image.open("pcanb_img.png"))
            self.canvas_im.create_image(0,0,anchor = "nw", image=img)
        #if naive bayes with lda is checked then show naive bayes with lda roc curve
        if var5 == 1:
            self.naiveb_lda()
            self.img=img =ImageTk.PhotoImage(Image.open("ldanb_img.png"))
            self.canvas_im.create_image(0,0,anchor = "nw", image=img)
            
    def mlp_checked(self):
        var6 = self.var6.get()
        var7 = self.var7.get()
        var8 = self.var8.get()
        self.clear_checked()
        self.canvas_im.delete("all")
        
        if var6 ==1:
            self.mlp()
            #''change image to knn without pca
            self.img=img =ImageTk.PhotoImage(Image.open("mlp_img.png"))
            self.canvas_im.create_image(0,0,anchor = "nw", image=img) 
        if var7 == 1:
            self.mlp_pca()
            self.img=img =ImageTk.PhotoImage(Image.open("pcamlp_img.png"))
            self.canvas_im.create_image(0,0,anchor = "nw", image=img)    
        if var8 == 1:
            self.mlp_lda()
            self.img=img =ImageTk.PhotoImage(Image.open("ldamlp_img.png"))
            self.canvas_im.create_image(0,0,anchor = "nw", image=img)          
    #clear all checked button once clicked        
    def clear_checked(self):
        self.var.set(0)
        self.var1.set(0)
        self.var2.set(0)
        self.var3.set(0)
        self.var4.set(0)
        self.var5.set(0)
        self.var6.set(0)
        self.var7.set(0)
        self.var8.set(0)
#------------------end of checkboxes-----------------------------------------
        
    #linear discriminent analysis with one component on training data    
    def lda(self):
        lda = LDA(n_components=1)
        self.xlda_train = lda.fit_transform(self.x_train,  self.y_train)
        self.xlda_test = lda.transform(self.x_test)
        return self.xlda_test, self.xlda_train

    #principle component anaysis with seven components tested to give best results
    def pca(self):
         pca = PCA(n_components=7)
         self.xpca_train = pca.fit_transform(self.x_train)
         self.xpca_test = pca.transform(self.x_test)
         return self.xpca_test, self.xpca_train
        
    #retrive all results for classification report     
    def get_results(self, x, y):
         self.acc =accuracy_score(self.y_test, x)
         #seperate confusion matrix to get true negative, flase positive, false negative and true 
         #true positive for specificity result
         tn, fp, fn, tp = confusion_matrix(self.y_test, x).ravel()
         self.spec = tn / (tn+fp)
         self.roc_score =roc_auc_score(self.y_test, y)
         self.sens = recall_score(self.y_test, x)
#===========================Classifiers=============================================
   #three different classifiers for each model one train without ananysis then pca and lda
    #call methods for training/ splitting and standardisation of data 
    #fit all classifiers with training data 
    #clear all classification results once a classifier has been trained 
     # insert the new classifier resutls into classification report text boxes 
    #-------------------------KNN--------------------------------------------       
    def k_n_n(self, x, y):
        #get input value
         r = int(self.train_l.get())
         #classify knn with input valaue for n_neighbors testing 
         #differnt k values correct k = 11 
         knn = KNeighborsClassifier(n_neighbors=r)
         knn.fit(x,self.y_train)
         self.y_pred = knn.predict(y)
         self.y_score = knn.predict_proba(y)[:,1]
         return self.y_pred, self.y_score
        
    #knn withou anaylisis  
    def knn_own(self):
        self.clear_results()
        self.preprocessing()
        self.k_n_n(self.x_train, self.x_test)
        self.get_results(self.y_pred, self.y_score)
        self.get_results(self.y_pred, self.y_score)
        self.insert_results()
    #knn with linear discriminent analysis    
    def knn_lda(self):
        self.clear_results()
        self.preprocessing()
        self.lda()
        self.k_n_n(self.xlda_train, self.xlda_test)
        self.get_results(self.y_pred, self.y_score)
        self.insert_results()
        
    #knn with principle component analysis                           
    def knn_pca(self):
        self.clear_results()
        self.preprocessing()
        self.pca()
        self.k_n_n(self.xpca_train, self.xpca_test)
        self.get_results(self.y_pred, self.y_score)
        self.insert_results()
#-------------------------Naive Bayes----------------------------------------    
    #train naive bayes
    def n_b(self, x, y):
        clf = GaussianNB()
        clf.fit(x, self.y_train)
        self.yn_pred = clf.predict(y)
        self.yn_scores = clf.predict_proba(y)[:,1]
        return self.yn_pred, self.yn_scores
    #naive bayes without anaylis 
    def naive_bayes(self):
        self.clear_results()
        self.preprocessing()
        self.n_b(self.x_train, self.x_test)
        self.get_results(self.yn_pred, self.yn_scores)
        self.insert_results()
     
    #naive bayes with linear discriminent anaylsis  
    def naiveb_lda(self):
        self.clear_results()
        self.preprocessing()
        self.lda()
        self.n_b(self.xlda_train, self.xlda_test)
        self.get_results(self.yn_pred, self.yn_scores)
        self.insert_results()
    #naive bayes with principle component anaylsis    
    def naiveb_pca(self):
        self.clear_results()
        self.preprocessing()
        self.pca()
        self.n_b(self.xpca_train, self.xpca_test)
        self.get_results(self.yn_pred, self.yn_scores)
        self.insert_results()
#---------------------MultiLayer Perceptron------------------------------------        
         
    #MultiLayer Perceptron method with 100 iterations and ten hidden layers for three nodes    
    def m_l_p(self, x, y):
        mlp = MLPClassifier(hidden_layer_sizes=(10,10,10), max_iter=1000, random_state=1)
        mlp.fit(x, self.y_train)
        self.ym_pred = mlp.predict(y)
        self.ym_scores = mlp.predict_proba(y)[:,1]
        return self.ym_pred, self.ym_scores
    
    #empty contents train multilayer perceptron with Principle component Analysis
    #intilize methods
    def mlp(self):
        self.clear_results()
        self.preprocessing()
        self.m_l_p(self.x_train, self.x_test)
        self.get_results(self.ym_pred, self.ym_scores)
        self.insert_results()
        
    def mlp_lda(self):
        self.clear_results()
        self.preprocessing()
        self.lda()
        self.m_l_p(self.xlda_train, self.xlda_test)
        self.get_results(self.ym_pred, self.ym_scores)
        self.insert_results()
       
    def mlp_pca(self):
        self.clear_results()
        self.preprocessing()
        self.pca()
        self.m_l_p(self.xpca_train, self.xpca_test)
        self.get_results(self.ym_pred, self.ym_scores)
        self.insert_results()
    
    def insert_results(self):
        #insert all results into text boxes in class report
        #round results to two decimal places
        self.class_acc.insert("end",self.acc.round(2))
        self.class_sense.insert("end", self.sens.round(2))
        self.class_spece.insert("end", self.spec.round(2))
        self.rocscore.insert("end", self.roc_score.round(2))   
    #clear all results in classification report once another
    #classifier has been selected      
    def clear_results(self):
        self.test_datat.delete(0,"end")
        self.class_acc.delete(0,"end")
        self.train_datat.delete(0,"end")
        self.class_sense.delete(0, "end")
        self.class_spece.delete(0, "end")
        self.rocscore.delete(0,"end")
Пример #6
0
class GUI:
    def __init__(self, master):
        self.master = master

        master.title("Zoom Poll Analyzer")
        master.geometry("1200x800")
        master.configure(bg="red3")
        self.listee = Listbox(master, width=80, height=35)
        self.listee.place(x=50, y=140)
        self.header = Label(master,
                            text="ZOOM POLL ANALYZER",
                            width=30,
                            height=2,
                            font=30).place(x=500, y=50)
        self.buton4 = Button(master,
                             text="Start",
                             width=35,
                             height=2,
                             command=self.start).place(x=850, y=475)
        self.buton5 = Button(master,
                             text="Show Result",
                             width=35,
                             height=2,
                             command=self.newwindow).place(x=850, y=550)
        self.buton6 = Button(master,
                             text="Show Histograms",
                             width=35,
                             height=2,
                             command=self.imagewindow).place(x=850, y=625)

    def start(self):
        driver = ZoomPollAnalyzer("answer-keys-directory",
                                  "students-list-directory", "polls-directory",
                                  "output")
        driver.start()
        if os.name == 'posix':
            self.names = glob.glob(os.getcwd() + "/output/**/*.xlsx",
                                   recursive=True)

            for i in self.names:
                if "Poll" in i.split("/")[-1]:
                    self.listee.insert(0, i.split("/")[-1])
                elif "attendance" in i.split("/")[-1]:
                    self.listee.insert(0, i.split("/")[-1])
        else:

            self.names = glob.glob(os.getcwd() + "\output/*.xlsx",
                                   recursive=True)
            for i in self.names:
                if "Poll" in i.split("\\")[-1]:
                    self.listee.insert(0, i.split("\\")[-1])
                elif "attendance" in i.split("\\")[-1]:
                    self.listee.insert(0, i.split("\\")[-1])

    def newwindow(self):
        self.window = Tk()
        self.window.title("Student List")
        self.window.geometry("1000x600")
        xls = pd.ExcelFile(os.getcwd() + "/output/" +
                           self.listee.get(self.listee.curselection()))
        sheetData = pd.read_excel(xls, 'Sheet1')
        headings = sheetData.columns
        data = list(headings.values.tolist())
        rows = len(sheetData)
        tree = ttk.Treeview(self.window,
                            columns=data,
                            show=["headings"],
                            selectmode='browse')
        tree.place(x=0, y=100)
        for heading in headings:
            heading = str(heading)
            tree.column(heading, width=120, anchor='center')
            tree.heading(heading, text=heading)
        for rownumber in range(rows):
            rowvalue = sheetData.values[rownumber]
            rowdata = tuple(rowvalue)
            tree.insert('', 'end', values=rowdata)

    def imagewindow(self):
        self.imagewindoww = Toplevel(bg='yellow')
        self.imagewindoww.title("Histograms With Reports")
        self.imagewindoww.geometry("1000x600")
        self.combo = ttk.Combobox(self.imagewindoww)
        self.combo.place(x=50, y=50)
        path = (os.getcwd() + "/output/Histograms " +
                self.listee.get(self.listee.curselection())).split(".xlsx")[0]
        self.png_dict = {}
        combo_values = []
        self.name = glob.glob(path[:-1] + str(int(path[-1]) - 1) + "/*.png",
                              recursive=True)
        for qe in self.name:
            png = qe.split("/")[-1]
            combo_values.append(png.split(".")[0])
            self.png_dict[png.split(".")[0]] = qe
        combo_values.sort()
        self.combo["values"] = combo_values
        self.combo.bind("<<ComboboxSelected>>",
                        lambda event: self.imageshow1(event))

    def imageshow1(self, event):
        png_file = self.combo.get()
        self.image = Image.open(self.png_dict[png_file])
        self.resized = self.image.resize((500, 500), Image.ANTIALIAS)
        self.photo = ImageTk.PhotoImage(self.resized)
        self.showimage = Label(self.imagewindoww, image=self.photo)
        self.showimage.resized = self.photo
        self.showimage.place(x=50, y=100)
        excel = self.png_dict[png_file].split(".png")[0] + ".xlsx"
        xls = pd.ExcelFile(excel)
        sheetData = pd.read_excel(xls, 'Sheet1')
        headings = sheetData.columns
        data = list(headings.values.tolist())
        rows = len(sheetData)
        tree = ttk.Treeview(self.imagewindoww,
                            columns=data,
                            show=["headings"],
                            selectmode='browse')
        tree.place(x=600, y=100)
        for heading in headings:
            heading = str(heading)
            tree.column(heading, width=200, anchor='center')
            tree.heading(heading, text=heading)
        for rownumber in range(rows):
            rowvalue = sheetData.values[rownumber]
            rowdata = tuple(rowvalue)
            tree.insert('', 'end', values=rowdata)
Пример #7
0
# listbox schuifbalken
yscrollbar = Scrollbar(overzicht_frame)
yscrollbar.pack(side='right', fill='y')

xscrollbar = Scrollbar(overzicht_frame, orient='horizontal')
xscrollbar.pack(side='bottom', fill='x')

# overzicht voor resultaten van de zoekopdracht en controles
overzicht = Listbox(overzicht_frame,
                    font=("Courier", 12),
                    width=124,
                    height=29,
                    bg="white",
                    yscrollcommand=yscrollbar.set,
                    xscrollcommand=xscrollbar.set)
overzicht.place(x=210, y=12)
overzicht.pack(side='left', fill='both')
overzicht.bind('<Double-Button-1>', foto_of_pdf_tonen)

yscrollbar.config(command=overzicht.yview)
xscrollbar.config(command=overzicht.xview)

VERSIE_NUMMER = lees_versienummer()
master.title("HKN - zoeken in archief - versie {0}  -  database: {1} ".format(
    VERSIE, VERSIE_NUMMER))

# GUI voltooid ----------------------------------------------------------------

info_programma_weergeven()

master.mainloop()
Пример #8
0
class OrderManagerGui:
    def __init__(self, master):
        self.bg = "#35323b"
        self.black = "#201e24"
        self.light_green = "#00b986"
        self.black_green = "#008562"
        self.title_text = "#dddddd"
        self.button_text = "#eeeeee"

        self.incomplete_orders = []
        self.orders_to_display = []

        self.margin_default_text = "Margin: "
        self.invested_default_text = "Invested: "
        self.profit_default_text = "Profit: "
        self.roi_default_text = "ROI: "
        self.last_bought_at_default_text = "Last Buy Order: "

        self.master = master
        self.master.geometry("900x400")
        self.master.configure(bg=self.bg)
        self.master.resizable(False, False)
        master.title("TT v" + constants.VERSION)

        self.lbl_blank_header = Label(
            master,
            text="                                                ",
            font=("Arial", 24),
            bg=self.black)
        self.lbl_blank_header.place(x=0, y=0)

        #Title
        self.lbl_title = Label(master,
                               text="TT",
                               font=("Fixedsys", 24, "bold"),
                               bg=self.black,
                               fg=self.title_text)
        self.lbl_title.place(x=5, y=5)

        #Version Num
        self.lbl_version = Label(master,
                                 text="v" + constants.VERSION,
                                 font=("Fixedsys", 16),
                                 bg=self.black,
                                 fg=self.title_text)
        self.lbl_version.place(x=90, y=17)

        #Generator
        self.lbl_generator = Label(master,
                                   text="MANAGER",
                                   font=("Fixedsys", 18, "bold"),
                                   bg=self.black,
                                   fg=self.light_green)
        self.lbl_generator.place(x=185, y=5)

        ###ORDERS###
        self.orders_var = StringVar(master)
        self.orders_var.set(
            ["#99999 - Shark (1115:1129)[14] x 10k units", "15"])
        self.lb_orders = Listbox(master,
                                 listvariable=self.orders_var,
                                 width=146,
                                 height=11)
        self.lb_orders.place(x=10, y=50)
        self.lb_orders.after(500, self.show_stats)

        #Can be deleted, commented out for now in case manual testing on show_stats() needs to be done
        #self.btn_test = Button(master, text="Update Stats", command=self.show_stats)
        #self.btn_test.place(x=600, y=350)

        #Can be deleted, commented out for now in case manual testing on import_orders() needs to be done
        #self.btn_update = Button(master, text="Pull Orders", command=self.import_orders)
        #self.btn_update.place(x=700, y=350)

        ###STATS###
        column_spacer = 240
        unit_spacer = 20
        self.lbl_last_bought_at = Label(master,
                                        text=self.last_bought_at_default_text,
                                        fg=self.title_text,
                                        bg=self.bg,
                                        font=("Arial", 9))
        self.lbl_last_bought_at.place(x=10, y=column_spacer)

        self.lbl_margin = Label(master,
                                text=self.margin_default_text,
                                fg=self.title_text,
                                bg=self.bg,
                                font=("Arial", 9))
        self.lbl_margin.place(x=10, y=column_spacer + unit_spacer)

        self.lbl_invested = Label(master,
                                  text=self.invested_default_text,
                                  fg=self.title_text,
                                  bg=self.bg,
                                  font=("Arial", 9))
        self.lbl_invested.place(x=10, y=column_spacer + unit_spacer * 2)

        self.lbl_profit = Label(master,
                                text=self.profit_default_text,
                                fg=self.title_text,
                                bg=self.bg,
                                font=("Arial", 9))
        self.lbl_profit.place(x=10, y=column_spacer + unit_spacer * 3)

        self.lbl_roi = Label(master,
                             text=self.roi_default_text,
                             fg=self.title_text,
                             bg=self.bg,
                             font=("Arial", 9))
        self.lbl_roi.place(x=10, y=column_spacer + unit_spacer * 4)

        ###NOTES###
        self.txt_notes = Text(master,
                              height=7,
                              width=41,
                              bg=self.black,
                              fg=self.button_text,
                              relief="flat")
        self.txt_notes.place(x=250, y=column_spacer)

        ###Speed Buttons###
        self.lbl_speed = Label(master,
                               text="Speed of Completion",
                               fg=self.title_text,
                               bg=self.bg,
                               font=("Arial", 9))
        self.lbl_speed.place(x=700, y=column_spacer)

        self.btn_speed_1 = Button(master,
                                  text="  1  ",
                                  command=self.complete_order_1)
        self.btn_speed_1.place(x=690, y=270)

        self.btn_speed_2 = Button(master,
                                  text="  2  ",
                                  command=self.complete_order_2)
        self.btn_speed_2.place(x=752, y=270)

        self.btn_speed_3 = Button(master,
                                  text="  3  ",
                                  command=self.complete_order_3)
        self.btn_speed_3.place(x=810, y=270)

        self.btn_speed_overnight = Button(
            master, text="Overnight", command=self.complete_order_overnight)
        self.btn_speed_overnight.place(x=695, y=300)

        self.btn_speed_aborted = Button(master,
                                        text=" Aborted ",
                                        command=self.complete_order_aborted)
        self.btn_speed_aborted.place(x=775, y=300)

        self.import_orders()

    def show_stats(self):
        if len(self.incomplete_orders) != 0:
            curr_trans = self.incomplete_orders[self.lb_orders.curselection()
                                                [0]]
            self.lbl_last_bought_at['text'] = self.last_bought_at_default_text
            self.lbl_margin['text'] = self.margin_default_text + str(
                calc.margin(curr_trans.unit_price,
                            curr_trans.unit_intended_sell_price))
            self.lbl_invested['text'] = self.invested_default_text + str(
                calc.invested(curr_trans.unit_price, curr_trans.quantity) /
                1000) + "k"
            self.lbl_profit['text'] = self.profit_default_text + str(
                calc.profit(curr_trans.unit_price,
                            curr_trans.unit_intended_sell_price,
                            curr_trans.quantity) / 1000) + "k"
            self.lbl_roi['text'] = self.roi_default_text + str(
                calc.roi(curr_trans.unit_price,
                         curr_trans.unit_intended_sell_price,
                         curr_trans.quantity)) + "%"

        self.lb_orders.after(500, self.show_stats)

    def import_orders(self):
        all_transactions = read.transaction_database(
            constants.PATH_TO_TRANSACTION_DB)

        #clear Listbox and reset
        self.lb_orders.delete(0, 'end')
        self.incomplete_orders = []
        self.orders_to_display = []

        #Pull incomplete orders and format them for display in the Listbox
        for trans in all_transactions:
            if trans.completed == "None":
                self.incomplete_orders.append(trans)
                self.orders_to_display.append(
                    trans.item_name + " x " + str(trans.quantity) +
                    "k units (" + str(trans.unit_price) + ":" +
                    str(trans.unit_intended_sell_price) + ") [" + str(
                        calc.margin(trans.unit_price,
                                    trans.unit_intended_sell_price)) + "]")

        #Display orders
        if len(self.orders_to_display) == 0:
            self.orders_var.set(["All transactions are complete"])
        else:
            self.orders_var.set(self.orders_to_display)

        #set default selected value in Listbox (first item)
        if len(self.orders_to_display) != 0:
            self.lb_orders.select_set(0)

    def complete_order_1(self):
        self.complete_order(constants.COMPLETION_SPEEDS[0])

    def complete_order_2(self):
        self.complete_order(constants.COMPLETION_SPEEDS[1])

    def complete_order_3(self):
        self.complete_order(constants.COMPLETION_SPEEDS[2])

    def complete_order_overnight(self):
        self.complete_order(constants.COMPLETION_SPEEDS[3])

    def complete_order_aborted(self):
        self.complete_order(constants.COMPLETION_SPEEDS[4])

    def complete_order(self, completion_code):
        completed_id = self.incomplete_orders[self.lb_orders.curselection()
                                              [0]].transaction_id
        all_transactions = read.transaction_database(
            constants.PATH_TO_TRANSACTION_DB)

        for trans in all_transactions:
            if trans.transaction_id == completed_id:
                curr_time = datetime.datetime.now()
                trans.end_year = curr_time.year
                trans.end_month = curr_time.month
                trans.end_day = curr_time.day
                trans.end_hour = curr_time.hour
                trans.end_minute = curr_time.minute
                trans.completed = completion_code
        write.transaction_database(constants.PATH_TO_TRANSACTION_DB,
                                   all_transactions)
        self.import_orders()  #update listbox
Пример #9
0
var3 = StringVar()
var3.set('打开串口')
b1 = Button(init_window, text='串口', width=10, height=1, command=print_selection)
b1.grid(row=1, column=0)
b2 = Button(init_window, textvariable=var3, width=10, height=1, command=open_serial)
b2.grid(row=1, column=2)
b2 = Button(init_window, text="发送", width=10, height=1, command=get_data)
b2.grid(row=1, column=4)
b3 = Button(init_window, text="刷新串口", width=9, height=1, command=freshen)
b3.place(x=15, y=150)
t = Label(init_window, text="波特率")
t.grid(row=0, column=1)
var2 = StringVar()
var2.set(tuple(serial_com))
print("chuangk", serial_com)
#val_com = 'COM3'
val_com = 'COM9'

lis = Listbox(init_window, width=10, height=5, listvariable=var2)  # 显示串口
lis.place(x=15, y=55)
text_send = Text(init_window, width=80, height=1)  # 输入传输字符
text_send.grid(row=1, column=3)
text_recv = Text(init_window, width=90, height=100)  # 接收字符
text_recv.grid(row=2, column=3)
text_baud = Text(init_window, width=10, height=1)  # 波特率设置
text_baud.grid(row=1, column=1)
text_baud.insert(END, '115200')

init_window.mainloop()
Пример #10
0
def create_widget(window):
    '''функция создания кнопок и их активация
    '''
    global ent_rashod_dohod, variable, options, text_result, select_value, frame_2, label_date_vision, combo_category

    options = db.get_articles_category()
    variable = StringVar(window)
    frame_1 = LabelFrame(window, text='Данные', height=300, width=600)
    frame_2 = LabelFrame(window,
                         text='Списки расходов и доходов',
                         height=500,
                         width=700)
    frame_3 = LabelFrame(window, text='Результаты', height=200, width=700)
    combo_category = Combobox(
        frame_2,
        values=options,
        postcommand=sort_article.refresh_sort_category,
        width=12,
        state='readonly',
    )
    combo_type = Combobox(frame_2, width=5, state='readonly')
    combo_type['values'] = ['Все', 'Расходы', 'Доходы']
    combo_category.current(0)
    combo_type.current(0)
    # ширина экрана
    w = window.winfo_screenwidth()
    # высота экрана
    h = window.winfo_screenheight()
    # значение по умолчанию
    variable.set(options[0])
    select_value = OptionMenu(frame_1, variable, *options)
    btn_rashod = Button(frame_1,
                        text='Добавить расходы',
                        command=add_type_rashod,
                        font=('Arial', 12))
    btn_dohod = Button(frame_1,
                       text='Добавить доходы',
                       command=add_type_dohod,
                       font=('Arial', 12))
    btn_append_item = Button(frame_1,
                             text='Добавить свой вариант',
                             command=category.create_window_category_change,
                             font=('Arial', 10))
    btn_result = Button(frame_2,
                        text='Oтсортировать',
                        font=('Arial', 12),
                        command=sort_article.sort_article_list)
    btn_delete = Button(frame_2,
                        text='Удалить',
                        command=del_article,
                        font=('Arial', 12))
    btn_demo = Button(frame_2, text='Демо', command=conftest.request_user)
    btn_calendar = Button(frame_2,
                          text='Сортировка по дате',
                          command=cal.create_window_calendar)
    btn_range_date = Button(frame_2,
                            text='Сортировка по периоду',
                            command=cal.create_window_range_date)
    ent_rashod_dohod = Entry(frame_1, width=40, font=('Arial', 12))
    label_text_select = Label(frame_1,
                              text='Выбирите нужный пункт расходов и доходов:',
                              font=('Arial', 12))
    label_text_select_type = Label(frame_1,
                                   text='Введите сумму расходов или доходов:',
                                   font=('Arial', 12))
    label_text_result = Label(frame_1, text='Результаты:', font=('Arial', 12))
    label_text_dohod = Label(frame_1, text='Сумма доходов', font=('Arial', 12))
    label_text_summ = Label(frame_1, text='ИТОГО')
    label_text_expence = Label(frame_3, text='Расходы', font=('Arial', 12))
    label_text_income = Label(frame_3, text='Доходы', font=('Arial', 12))
    label_text_all = Label(frame_3, text='Итого', font=('Arial', 12))
    label_date_vision = Label(frame_2, text="", font=('Arial', 12))
    text_result = Listbox(frame_2,
                          width=65,
                          height=20,
                          selectmode=EXTENDED,
                          font=('Arial', 12))
    scroll = Scrollbar(frame_2, orient="vertical", command=text_result.yview)
    text_result.config(yscrollcommand=scroll.set)
    text_result_expence = Listbox(frame_3,
                                  width=15,
                                  height=1,
                                  font=('Arial', 13))
    text_result_income = Listbox(frame_3,
                                 width=15,
                                 height=1,
                                 font=('Arial', 13))
    text_result_all = Listbox(frame_3, width=15, height=1, font=('Arial', 13))

    select_value.place(relx=0.03, rely=0.15)
    btn_rashod.place(relx=0.03, rely=0.70)
    btn_dohod.place(relx=0.33, rely=0.70)
    btn_delete.place(relx=0.55, rely=0.90)
    btn_append_item.place(relx=0.30, rely=0.15)
    btn_result.place(relx=0.75, rely=0.90)
    btn_demo.place(relx=0.35, rely=0.90)
    btn_calendar.place(relx=0.36, rely=0.02)
    btn_range_date.place(relx=0.57, rely=0.02)
    text_result.place(relx=0.10, rely=0.09)
    text_result_expence.place(relx=0.33, rely=0.03)
    text_result_income.place(relx=0.33, rely=0.18)
    text_result_all.place(relx=0.33, rely=0.33)
    ent_rashod_dohod.place(relx=0.03, rely=0.55)
    label_text_select.place(relx=0.03, rely=0.03)
    label_text_select_type.place(relx=0.03, rely=0.40)
    label_text_expence.place(relx=0.03, rely=0.03)
    label_text_income.place(relx=0.03, rely=0.18)
    label_text_all.place(relx=0.03, rely=0.33)
    #label_date_vision.place
    scroll.place(relx=0.95, rely=0.09, height=380)
    frame_1.place(relx=0.02, rely=0.02)
    frame_2.place(relx=0.47, rely=0.02)
    frame_3.place(relx=0.47, rely=0.70)
    combo_category.place(relx=0.10, rely=0.02)
    combo_type.place(relx=0.25, rely=0.02)
    result.show_result(text_result_income, text_result_expence,
                       text_result_all)
class GUI(Frame):

    def __init__(self, master=None, val=0):
        super().__init__(master)
        self.master = master
        self.val = val
        self.parametros = []
        self.actions = Enums.actions
        self.controller = Controller()
        self.initComp()

    def initComp(self):
        self.master.title("EDD - TytusDB")
        self.master.iconbitmap('team16/View/img/logo.ico')
        self.master.deiconify()
        self.centrar()
        if self.val == 1:
            self.main()
        elif self.val == 2:
            self.funciones()
        elif self.val == 3:
            self.reportes()

    def centrar(self):
        if self.val == 1:
            ancho = 500
            alto = 500
        elif self.val == 2:
            ancho = 1045
            alto = 660
        else:
            ancho = 1150
            alto = 650
        x_ventana = self.winfo_screenwidth() // 2 - ancho // 2
        y_ventana = self.winfo_screenheight() // 2 - alto // 2
        posicion = str(ancho) + "x" + str(alto) + "+" + str(x_ventana) + "+" + str(y_ventana - 35)
        self.master.resizable(width=False, height=False)
        self.master.geometry(posicion)

    def ventanaFunciones(self):
        v2 = Toplevel()
        self.master.iconify()
        image = Image.open('team16/View/img/function.png')
        background_image = ImageTk.PhotoImage(image.resize((1060, 680)))
        background_label = Label(v2, image=background_image)
        background_label.place(x=0, y=0, relwidth=1, relheight=1)
        v2.protocol("WM_DELETE_WINDOW", lambda: self.on_closing(v2, self.master))
        app2 = GUI(master=v2, val=2)
        app2.mainloop()

    def ventanaReporte(self):
        v3 = Toplevel()
        self.master.iconify()
        v3['bg'] = "#0f1319"
        v3.protocol("WM_DELETE_WINDOW", lambda: self.on_closing(v3, self.master))
        app3 = GUI(master=v3, val=3)
        app3.mainloop()

    @staticmethod
    def on_closing(win, root):
        if messagebox.askokcancel("Salir", "¿Seguro que quieres salir?"):
            win.destroy()
            root.deiconify()

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

    # region Menú principal
    def main(self):
        btnF = Button(text="FUNCIONES", bg="#33868a", bd=0, activebackground="#225b5e",
                      font="Arial 18", pady=12, width=14, command=lambda: self.ventanaFunciones())
        btnF.pack(side=TOP, pady=(150, 25))

        btnR = Button(text="REPORTES", bg="#33868a", bd=0, activebackground="#225b5e",
                      font="Arial 18", pady=12, width=14, command=lambda: self.ventanaReporte())
        btnR.pack(side=TOP, pady=(0, 25))

        btnS = Button(text="SALIR", bg="#bf4040", bd=0, activebackground="#924040",
                      font="Arial 18", pady=0, width=14, command=lambda: exit())
        btnS.pack(side=TOP, pady=(0, 25))

    # endregion

    # region Ventana de funciones
    def funciones(self):
        lbl1 = Label(self.master, text="Bases de datos", font=("Century Gothic", 21), bg="#0f1319", fg="#ffffff")
        lbl1.grid(row=1, column=0, padx=(60, 85), pady=(100, 25))

        lbl2 = Label(self.master, text="Tablas", font=("Century Gothic", 21), bg="#0f1319", fg="#ffffff")
        lbl2.grid(row=1, column=1, padx=(5, 0), columnspan=2, pady=(100, 25))

        lbl3 = Label(self.master, text="Tuplas", font=("Century Gothic", 21), bg="#0f1319", fg="#ffffff")
        lbl3.grid(row=1, column=3, padx=(130, 150), pady=(100, 25))

        # region Bases de datos
        btnCreateDB = Button(self.master,
                             text=self.actions[1],
                             bg="#abb2b9", font=("Courier New", 14),
                             borderwidth=0.5, pady=6, width=16,
                             command=lambda: self.simpleDialog(["database"], self.actions[1]))
        btnCreateDB.grid(row=2, column=0, sticky=W, padx=(70, 0), pady=(0, 25))

        btnshowDBS = Button(self.master,
                            text=self.actions[2],
                            bg="#abb2b9", font=("Courier New", 14),
                            borderwidth=0.5, pady=6, width=16,
                            command=lambda: self.controller.execute(None, self.actions[2]))
        btnshowDBS.grid(row=3, column=0, sticky=W, padx=(70, 0), pady=(0, 25))

        btnAlterDB = Button(self.master,
                            text=self.actions[3],
                            bg="#abb2b9", font=("Courier New", 14),
                            borderwidth=0.5, pady=6, width=16,
                            command=lambda: self.simpleDialog(["databaseOld", "databaseNew"], self.actions[3]))
        btnAlterDB.grid(row=4, column=0, sticky=W, padx=(70, 0), pady=(0, 25))

        btnDropDB = Button(self.master,
                           text=self.actions[4],
                           bg="#abb2b9", font=("Courier New", 14),
                           borderwidth=0.5, pady=6, width=16,
                           command=lambda: self.simpleDialog(["database"], self.actions[4]))
        btnDropDB.grid(row=5, column=0, sticky=W, padx=(70, 0), pady=(0, 25))

        btnFormat = Button(self.master,
                           text=self.actions[23],
                           bg="#abb2b9", font=("Courier New", 14),
                           borderwidth=0.5, pady=6, width=16,
                           command=lambda: self.controller.execute(None, self.actions[23]))
        btnFormat.grid(row=6, column=0, sticky=W, padx=(70, 0), pady=(0, 25))
        # endregion

        # region Tablas
        btnCreateTb = Button(self.master,
                             text=self.actions[5],
                             bg="#abb2b9", font=("Courier New", 14),
                             borderwidth=0.5, pady=6, width=15,
                             command=lambda: self.simpleDialog(["database", "tableName", "numberColumns"],
                                                               self.actions[5]))
        btnCreateTb.grid(row=2, column=1, sticky=W, padx=(10, 0), pady=(0, 25))

        btnDefinePK = Button(self.master,
                             text=self.actions[9],
                             bg="#abb2b9", font=("Courier New", 14),
                             borderwidth=0.5, pady=6, width=15,
                             command=lambda: self.simpleDialog(["database", "table", "columns"], self.actions[9]))
        btnDefinePK.grid(row=3, column=1, sticky=W, padx=(10, 0), pady=(0, 25))

        btnDropPK = Button(self.master,
                           text=self.actions[10],
                           bg="#abb2b9", font=("Courier New", 14),
                           borderwidth=0.5, pady=6, width=15,
                           command=lambda: self.simpleDialog(["database", "table"], self.actions[10]))
        btnDropPK.grid(row=4, column=1, sticky=W, padx=(10, 0), pady=(0, 25))

        btnShowTb = Button(self.master,
                           text=self.actions[6],
                           bg="#abb2b9", font=("Courier New", 14),
                           borderwidth=0.5, pady=6, width=15,
                           command=lambda: self.simpleDialog(["database"], self.actions[6]))
        btnShowTb.grid(row=5, column=1, sticky=W, padx=(10, 0), pady=(0, 25))

        btnAlterTb = Button(self.master,
                            text=self.actions[13],
                            bg="#abb2b9", font=("Courier New", 14),
                            borderwidth=0.5, pady=6, width=15,
                            command=lambda: self.simpleDialog(["database", "tableOld", "tableNew"], self.actions[13]))
        btnAlterTb.grid(row=6, column=1, sticky=W, padx=(10, 0), pady=(0, 25))

        btnDropTb = Button(self.master,
                           text=self.actions[16],
                           bg="#abb2b9", font=("Courier New", 14),
                           borderwidth=0.5, pady=6, width=15,
                           command=lambda: self.simpleDialog(["database", "tableName"], self.actions[16]))
        btnDropTb.grid(row=2, column=2, sticky=W, padx=(5, 0), pady=(0, 25))

        btnAlterAdd = Button(self.master,
                             text=self.actions[14],
                             bg="#abb2b9", font=("Courier New", 14),
                             borderwidth=0.5, pady=6, width=15,
                             command=lambda: self.simpleDialog(["database", "tableName", "default"],
                                                               self.actions[14]))
        btnAlterAdd.grid(row=3, column=2, sticky=W, padx=(5, 0), pady=(0, 25))

        btnAlterDrop = Button(self.master,
                              text=self.actions[15],
                              bg="#abb2b9", font=("Courier New", 14),
                              borderwidth=0.5, pady=6, width=15,
                              command=lambda: self.simpleDialog(["database", "tableName", "columnNumber"],
                                                                self.actions[15]))
        btnAlterDrop.grid(row=4, column=2, sticky=W, padx=(5, 0), pady=(0, 25))

        btnExtractTb = Button(self.master,
                              text=self.actions[7],
                              bg="#abb2b9", font=("Courier New", 14),
                              borderwidth=0.5, pady=6, width=15,
                              command=lambda: self.simpleDialog(["database", "table"], self.actions[7]))
        btnExtractTb.grid(row=5, column=2, sticky=W, padx=(5, 0), pady=(0, 25))

        btnExtractRangeTb = Button(self.master,
                                   text=self.actions[8],
                                   bg="#abb2b9", font=("Courier New", 14),
                                   borderwidth=0.5, pady=6, width=15,
                                   command=lambda: self.simpleDialog(["database", "table", "column", "lower", "upper"],
                                                                     self.actions[8]))
        btnExtractRangeTb.grid(row=6, column=2, sticky=W, padx=(5, 0), pady=(0, 25))
        # endregion

        # region Tuplas:
        btnInsertTp = Button(self.master,
                             text=self.actions[17],
                             bg="#abb2b9", font=("Courier New", 14),
                             borderwidth=0.5, pady=6, width=12,
                             command=lambda: self.simpleDialog(["database", "table", "register"], self.actions[17]))
        btnInsertTp.grid(row=2, column=3, sticky=W, padx=(110, 0), pady=(0, 25))

        btnLoadfile = Button(self.master,
                             text=self.actions[18],
                             bg="#abb2b9", font=("Courier New", 14),
                             borderwidth=0.5, pady=6, width=12,
                             command=lambda: self.simpleDialog(["file", "database", "table"], self.actions[18]))
        btnLoadfile.grid(row=3, column=3, sticky=W, padx=(110, 0), pady=(0, 25))

        btnExtractTp = Button(self.master,
                              text=self.actions[19],
                              bg="#abb2b9", font=("Courier New", 14),
                              borderwidth=0.5, pady=6, width=12,
                              command=lambda: self.simpleDialog(["database", "table", "id"], self.actions[19]))
        btnExtractTp.grid(row=4, column=3, sticky=W, padx=(110, 0), pady=(0, 25))

        btnUpdateTp = Button(self.master,
                             text=self.actions[20],
                             bg="#abb2b9", font=("Courier New", 14),
                             borderwidth=0.5, pady=6, width=12,
                             command=lambda: self.simpleDialog(["database", "table", "register", "columns"],
                                                               self.actions[20]))
        btnUpdateTp.grid(row=5, column=3, sticky=W, padx=(110, 0), pady=(0, 25))

        btnDeleteTp = Button(self.master,
                             text=self.actions[21],
                             bg="#abb2b9", font=("Courier New", 14),
                             borderwidth=0.5, pady=6, width=12,
                             command=lambda: self.simpleDialog(["database", "tableName", "columns"], self.actions[21]))
        btnDeleteTp.grid(row=6, column=3, sticky=W, padx=(110, 0), pady=(0, 25))

        btnTruncateTp = Button(self.master,
                               text=self.actions[22],
                               bg="#abb2b9", font=("Courier New", 14),
                               borderwidth=0.5, pady=6, width=12,
                               command=lambda: self.simpleDialog(["database", "tableName"], self.actions[22]))
        btnTruncateTp.grid(row=7, column=3, sticky=W, padx=(110, 0), pady=(0, 25))
        # endregion

    # endregion

    # region Ventana de reporte
    def reportes(self):
        self.titulo3 = Label(self.master, text="Reporte bases de datos", bg="#0f1319", fg="#45c2c5",
                             font=("Century Gothic", 42), pady=12)
        self.titulo3.pack(fill=X)

        self.scrollbarY = Scrollbar(self.master)
        self.scrollbarY.pack(side=RIGHT, fill=Y)

        self.scrollbarX = Scrollbar(self.master, orient='horizontal')
        self.scrollbarX.pack(side=BOTTOM, fill=X)

        self.listbox = Listbox(self.master, height=21, width=20,
                               bg="#0f1319", bd=0, fg='#ffffff', font=("Century Gothic", 12))
        self.listbox.place(x=65, y=122)

        self.listbox.bind("<<ListboxSelect>>", self.displayDBData)

        self.tableList = Combobox(self.master, state="readonly", width=30, font=("Century Gothic", 12))
        self.tableList.place(x=360, y=120)
        self.tableList.set('Seleccione tabla...')
        self.tableList.bind("<<ComboboxSelected>>", self.displayTableData)

        self.tuplelist = Combobox(self.master, state="readonly", width=30, font=("Century Gothic", 12))
        self.tuplelist.place(x=750, y=120)
        self.tuplelist.set('Seleccione tupla...')
        self.tuplelist.bind("<<ComboboxSelected>>", self.displayTupleData)

        self.canvas = Canvas(self.master, width=740, height=415, bg="#0f1319", highlightthickness=0)
        self.canvas.place(x=320, y=170)
        # self.canvas.config(xscrollcommand=self.scrollbarX.set, yscrollcommand=self.scrollbarY.set)
        self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)

        self.scrollbarY.config(command=self.canvas.yview)
        self.scrollbarX.config(command=self.canvas.xview)

        self.desplegarDB()

    # Mostrar lista de base de datos
    def desplegarDB(self):
        try:
            dblist = self.controller.execute(None, self.actions[2])
            for db in dblist:
                self.listbox.insert(END, str(db))
            png = self.controller.reportDB()
            bg_DB = ImageTk.PhotoImage(Image.open(png))
            self.image_on_canvas = self.canvas.create_image(370, 207, anchor=CENTER, image=bg_DB)
            # self.canvas.config(xscrollcommand=self.scrollbarX.set, yscrollcommand=self.scrollbarY.set)
            # self.canvas.config(scrollregion=self.canvas.bbox(ALL))
            self.master.mainloop()
        except:
            None

    # Mostrar lista de tablas
    def displayDBData(self, event):
        try:
            selection = event.widget.curselection()
            data = ""
            tmp = []
            if selection:
                self.tableList.set('Seleccione tabla...')
                self.tuplelist.set('Seleccione tupla...')
                index = selection[0]
                data = event.widget.get(index)
                self.titulo3.configure(text=data)
                tmp.append(data)
                dbList = self.controller.execute(tmp, self.actions[6])
                self.tableList["values"] = dbList
                png = self.controller.reportTBL(data)
                bg_TBL = ImageTk.PhotoImage(Image.open(png))
                self.canvas.itemconfig(self.image_on_canvas, image=bg_TBL)
                self.canvas.config(xscrollcommand=self.scrollbarX.set, yscrollcommand=self.scrollbarY.set)
                self.canvas.config(scrollregion=self.canvas.bbox(ALL))
                self.master.mainloop()
        except:
            None

    # Mostrar AVL de tabla
    def displayTableData(self, event):
        try:
            self.tuplelist.set('Seleccione tupla...')
            db = str(self.titulo3["text"])
            tb = str(self.tableList.get())
            tp = self.controller.getIndexes(db, tb)
            self.tuplelist["values"] = tp
            png = self.controller.reportAVL(db, tb)
            bg_AVL = ImageTk.PhotoImage(Image.open(png))
            self.canvas.itemconfig(self.image_on_canvas, image=bg_AVL)
            self.canvas.config(xscrollcommand=self.scrollbarX.set, yscrollcommand=self.scrollbarY.set)
            self.canvas.config(scrollregion=self.canvas.bbox(ALL))
            self.master.mainloop()
        except:
            None

    # Mostrar tupla
    def displayTupleData(self, event):
        try:
            db = str(self.titulo3["text"])
            tb = str(self.tableList.get())
            tp = str(self.tuplelist.get())
            png = self.controller.reportTPL(db, tb, tp)  # le envío el índice del árbol (tp)
            bg_TPL = ImageTk.PhotoImage(Image.open(png))
            self.canvas.itemconfig(self.image_on_canvas, image=bg_TPL)
            self.canvas.config(xscrollcommand=self.scrollbarX.set, yscrollcommand=self.scrollbarY.set)
            self.canvas.config(scrollregion=self.canvas.bbox(ALL))
            self.master.mainloop()
        except:
            None

    # endregion

    # region Digitador
    def simpleDialog(self, args, action):
        self.parametros.clear()
        tmp = []
        dialog = Tk()
        dialog['bg'] = "#0f1319"
        dialog.title(action)
        dialog.resizable(False, False)
        dialog.update()
        dialog.deiconify()
        dim = len(args)
        for i in range(dim):
            Label(dialog, text=args[i] + ":", bg="#0f1319", fg="#ffffff", font=("Century Gothic", 12)
                  ).grid(row=i, padx=(12, 1), pady=(2, 2), sticky=SW)

        if args[0] == "file":
            btnFile = Button(dialog, text="Examinar...", command=lambda: self.cargarArchivo(btnFile))
            btnFile.grid(row=0, column=1, pady=(15, 2), padx=(0, 18), sticky="ew")
            for j in range(dim - 1):
                entry = Entry(dialog)
                entry.grid(row=j + 1, column=1, padx=(0, 18))
                tmp.append(entry)
        else:
            for j in range(dim):
                entry = Entry(dialog)
                entry.grid(row=j, column=1, padx=(0, 18))
                tmp.append(entry)
        tmp[0].focus_set()
        dialog.bind('<Return>', lambda event=None: self.ejecutar(dialog, tmp, action))
        dialog.bind('<Escape>', lambda event=None: dialog.destroy())
        submit = Button(dialog, text="OK", bg="#45c2c5", bd=0, pady=6, width=10,
                        command=lambda: self.ejecutar(dialog, tmp, action))
        submit.grid(row=dim + 1, columnspan=2, pady=(8, 10))
        dialog.mainloop()

    # endregion

    def cargarArchivo(self, btn):
        filename = filedialog.askopenfilename(filetypes=[("csv files", "*.csv")])
        if filename:
            self.parametros.append(filename)
            btn.configure(text=filename[filename.rfind('/') + 1:])

    def ejecutar(self, dialog, args, action):
        for arg in args:
            if arg.get():
                self.parametros.append(arg.get())
            else:
                return messagebox.showerror("Oops", "Existen campos vacíos")
        response = self.controller.execute(self.parametros, action)
        if response in range(1, 8):
            self.parametros.clear()
            return messagebox.showerror("Error número: " + str(response),
                                        "Ocurrió un error en la operación.\nAsegúrese de introducir datos correctos")
        dialog.destroy()
Пример #12
0
class App(object):
    def __init__(self):
        self.win = Tk()
        self.win.geometry('400x380')
        self.win.title("网易云mp3播放下载器")
        self.creat_res()
        self.res_config()
        self.win.mainloop()

    def creat_res(self):
        self.mp3_lis = []
        self.temp = StringVar()  # url输入框
        self.temp2 = StringVar()  # id输入框和歌名播放
        self.temp3 = StringVar()  # path 输入框
        self.T_message = Listbox(self.win, background="#EEE9E9")
        self.B_search = Button(self.win, text="搜索")
        self.B_path = Button(self.win, text="选择目录")
        self.E_song = Entry(self.win, textvariable=self.temp)
        self.E_path = Entry(self.win, textvariable=self.temp3)
        self.Play_button = Button(self.win, text="播放")
        self.Pause_button = Button(self.win, text="暂停")
        self.Temp_button = Button(self.win, text="单曲下载")
        self.Info = Button(self.win, text="说明")
        self.More_down = Button(self.win, text="歌单批量下载")
        self.S_bal = Scrollbar(self.win)
        self.L_mp3_name = Label(self.win, text="播放歌曲名")
        self.E_box = Entry(self.win, textvariable=self.temp2)
        self.B_search.place(x=340, y=10, width=50, height=40)
        self.E_song.place(x=10, y=10, width=300, height=35)
        self.T_message.place(x=10, y=165, width=280, height=200)
        self.Play_button.place(x=340, y=190, width=50, height=40)
        self.Pause_button.place(x=340, y=250, width=50, height=40)
        self.E_box.place(x=310, y=95, width=80, height=30)
        self.Temp_button.place(x=310, y=141, width=80, height=30)
        self.S_bal.place(x=286, y=165, width=20, height=200)
        self.E_path.place(x=10, y=70, width=200, height=40)
        self.B_path.place(x=230, y=70, width=60, height=40)
        self.L_mp3_name.place(x=310, y=60, width=80, height=30)
        self.Info.place(x=340, y=300, width=50, height=40)
        self.More_down.place(x=10, y=125, width=100, height=30)

    def res_config(self):
        self.B_search.config(command=self.get_lis)
        self.S_bal.config(command=self.T_message.yview)
        self.T_message["yscrollcommand"] = self.S_bal.set
        self.B_path.config(command=self.choose_path)
        self.More_down.config(command=self.download_music)
        self.Info.config(command=self.show_mesage)
        self.Temp_button.config(command=self.single_music_down)
        self.Play_button.config(command=self.play_music)
        self.Pause_button.config(command=self.pause_music)

    def choose_path(self):
        self.path_ = askdirectory()
        self.temp3.set(self.path_)

    def show_mesage(self):
        msg = "输入框可识别歌单list,或者歌曲名称 '\n'" \
              "输入歌单,请搜索后选择路径和批量下载 '\n'" \
              "搜索单曲后选择id号输入进行下载 '\n'" \
              "播放功能待完善"
        messagebox.showinfo(message=msg, title="使用说明")

    def get_lis(self):  # 搜索按钮,先判断下输入的是url 还是单曲
        flag = music_get.do_something(self.temp.get())
        music_dic = music_get.get_music_id(self.temp.get())
        if self.temp.get() != "":  # 输入框非空
            if flag == True:  # 输入的是链接
                mp3_url = music_get.get_mps_url(self.temp.get())
                for i, j in mp3_url.items():
                    self.T_message.insert(END, "歌曲:" + i + "\n")
                for i in mp3_url.keys():
                    self.mp3_lis.append(i)  # 存储清单歌曲名字,备用
                print(self.mp3_lis)
            else:  # 如果输入的是单曲
                self.T_message.insert(END, "正在查找歌曲:" + self.temp.get() + "\n")
                for id, name in music_dic.items():
                    self.T_message.insert(END,
                                          "找到歌曲:{}-{}".format(id, name) + "\n")
        else:
            self.T_message.insert(END, "清输入歌曲名或者歌单链接:" + "\n")

    def download_music(self):  # 歌单批量下载
        mp3_url = music_get.get_mps_url(self.temp.get())
        music_get.down_mp3(self.temp3.get(), self.temp.get())
        print(self.temp.get(), self.temp3.get())
        for i in mp3_url.keys():
            t = random.randint(100, 300) * 0.01
            self.T_message.insert(END, "正在努力下载歌曲:" + i + "\n")
            time.sleep(t)

    def single_music_down(self):  # 单曲下载
        print("下载单曲")
        flag = music_get.do_something(
            self.temp.get())  # 判断是url 还是歌曲名字 如果是url true 否则f
        mps_dic = music_get.get_music_id(self.temp.get())
        # 首先判断以下 路径存在,输入的是单曲名,输入的是id号
        if os.path.exists(self.temp3.get(
        )) and flag == False and self.temp2.get() in mps_dic.keys():
            music_get.down_music2(self.temp3.get(), self.temp2.get(),
                                  self.temp.get())
            self.T_message.insert(
                END, "正在下载歌曲:" + self.temp.get() + self.temp2.get() + "\n")

    def play_music(self):
        print("播放音乐")
        path = self.temp3.get()  # 路径
        if os.path.exists(path):
            count = 0
            print(os.listdir(self.temp3.get()))
            for mp3 in os.listdir(self.temp3.get()):
                if self.temp2.get() in mp3:  # 如果名字在路径下面
                    song_index = os.listdir(self.temp3.get()).index(mp3)
                    self.T_message.insert(END,
                                          "找到歌曲:" + self.temp2.get() + "\n")
                    path_play = path + "/" + self.temp2.get() + ".mp3"
                    print(path_play)
                    # song=minimu.load(path_play)
                    # song.play()
                    # song.volume(50)
                else:
                    count += 1
            if count == len(os.listdir(self.temp3.get())):
                self.T_message.insert(END, "没找到歌曲:" + self.temp2.get() + "\n")
        else:
            self.T_message.insert(END, "清输入路径:" + "\n")

    def pause_music(self):
        print("暂停播放")
Пример #13
0
def EnrollPage():
    def enroll_ok():
        try:
            profile = {
                "ID": int(id_box.get()),
                "Name": name_box.get(),
                "Class": int(class_box.get()),
                "Section": section_list.curselection()[0],
                "DOB": dob_box.get_date(),
                "ParentContact": int(contact_box.get())
            }
            dir_path = f"./StudentManagementSystem/data/profiles"
            file_path = dir_path + f"/{profile['ID']}.json"
            
            if (not os.path.exists(dir_path)):
                os.makedirs(dir_path)
            with open(file_path, "w") as f:
                f.write(json.dumps(profile, indent=4))

        except (IndexError, ValueError):
            messagebox.showerror(
                title="Invalid Input",
                message="Information provided is incorrect. Please re-check the details.")

        else:
            messagebox.showinfo(
                title="Success",
                message="Successfully enrolled new student.")
            window.destroy()

    window = Toplevel(height=600, width=500)
    window.title("Add New Student")

    id_label = Label(window, text="ID :", fg="#cc3333")
    id_label.place(anchor=NW, x=120, y=20)
    id_box = Entry(window)
    id_box.place(x=150, y=20)

    name_label = Label(window, text="Name :")
    name_label.place(anchor=NW, x=100, y=50)
    name_box = Entry(window)
    name_box.place(x=150, y=50)

    class_label = Label(window, text="Class :")
    class_label.place(anchor=NW, x=105, y=80)
    class_box = Entry(window)
    class_box.place(x=150, y=80)

    section_label = Label(window, text="Section :")
    section_label.place(anchor=NW, x=90, y=110)
    section_list = Listbox(window, selectmode=SINGLE, height=6)
    section_list.insert(0, " A")
    section_list.insert(END, " B")
    section_list.insert(END, " C")
    section_list.insert(END, " D")
    section_list.insert(END, " E")
    section_list.insert(END, " F")
    section_list.place(x=150, y=110)

    dob_label = Label(window, text="DOB :")
    dob_label.place(anchor=NW, x=105, y=220)
    dob_box = Calendar(window, selectmode="day", year=2000, month=3, day=10)
    dob_box.place(x=150, y=220)

    contact_label = Label(window, text="Parent Contact :")
    contact_label.place(anchor=NW, x=50, y=420)
    contact_box = Entry(window)
    contact_box.place(x=150, y=420)

    ok_button = Button(window, text="OK", command=enroll_ok)
    ok_button.place(x=240, y=520, width=90)
    cancel_button = Button(window, text="Cancel", command=window.destroy)
    cancel_button.place(x=340, y=520, width=90)
Пример #14
0
class GUI:
    def __init__(self, driver):
        self.root = Tk()
        self.root.title("VoltaireTaMere")
        self.root.resizable(False, False)
        self.root.geometry('600x350')
        self.root.iconphoto(
            True, PhotoImage(file="asset/VoltaireTaMere_icon[PNG].png"))
        self.root.configure(bg='#23272A')

        self.Auto_off = PhotoImage(file="asset/Boutton_Auto_off.png")
        self.Auto_on = PhotoImage(file="asset/Boutton_Auto_on.png")
        self.Manual = PhotoImage(file="asset/Boutton_Manuel.png")
        self.back = PhotoImage(file="asset/Boutton_Retour.png")
        self.load_file = PhotoImage(file="asset/Boutton_Load.png")
        self.Quitter = PhotoImage(file="asset/boutton_Quitter.png")
        self.BG1 = PhotoImage(file="asset/Menu_1.png")
        self.BG2 = PhotoImage(file="asset/Menu_2.png")
        self.BG3 = PhotoImage(file="asset/Menu_3.png")

        self.driver = driver
        self.module = Module("")
        self.bot_on = False

        self.accuracy = IntVar()
        self.time_next = IntVar()
        self.accuracy.set(found_data("./file/options.txt", "accuracy", "int"))
        self.time_next.set(found_data("./file/options.txt", "accuracy", "int"))

        self.number_q = 0
        self.prgm = StringVar()
        self.niveau = StringVar()

        self.fond = Label(self.root, image=None, bg='#23272A')
        self.btn_pont_sup = Button(
            self.root,
            text="PONT\nSUPÉRIEUR",
            command=lambda: [
                self.prgm.set("pont_Supérieur"),
                self.niveau.
                set("Module\\ 1 Module\\ 2 Module\\ 3 Module\\ 4 Module\\ 5 Module\\ 6 Module\\ 7 Module\\ 8 Test\\ Blanc"
                    ),
                self.Menu_Unpack(),
                self.Menu_2(self.BG2)
            ],
            bg="#a2d417",
            highlightthickness=2,
            bd=0,
            height=6,
            width=12,
            font=('Helvetica', '10', "bold"))
        self.btn_sup = Button(
            self.root,
            text="SUPÉRIEUR",
            command=lambda: [
                self.prgm.set("Supérieur"),
                self.niveau.
                set("Module\\ 1 Module\\ 2 Module\\ 3 Module\\ 4 Module\\ 5 Module\\ 6 Module\\ 7 Module\\ 8 Module\\ 9 Module\\ 10 Test\\ Blanc"
                    ),
                self.Menu_Unpack(),
                self.Menu_2(self.BG2)
            ],
            bg="#a2d417",
            highlightthickness=2,
            bd=0,
            height=6,
            width=12,
            font=('Helvetica', '10', "bold"))
        self.btn_exc = Button(
            self.root,
            text="EXCELLENCE",
            command=lambda: [
                self.prgm.set("Excellence"),
                self.niveau.
                set("Module\\ 1 Module\\ 2 Module\\ 3 Module\\ 4 Module\\ 5 Module\\ 6 Module\\ 7 Module\\ 8 Module\\ 9 Module\\ 10 Module\\ 11 Module\\ 12 Verbes\\ Pronominaux\\ II"
                    ),
                self.Menu_Unpack(),
                self.Menu_2(self.BG2)
            ],
            bg="#a2d417",
            highlightthickness=2,
            bd=0,
            height=6,
            width=12,
            font=('Helvetica', '10', "bold"))
        self.btn_cus = Button(self.root,
                              text="CUSTOM",
                              bg="#a2d417",
                              command=lambda: [
                                  self.prgm.set("CUS"),
                                  self.niveau.set(""),
                                  self.Menu_Unpack(),
                                  self.Menu_3(self.BG3)
                              ],
                              activebackground="#ffffff",
                              bd=0,
                              height=6,
                              width=12,
                              font=('Helvetica', '10', "bold"))
        self.btn_auto = Button(self.root,
                               image=self.Auto_off,
                               command=self.switch_bot,
                               bg="#a2d417",
                               activebackground="#a2d417",
                               bd=0)
        self.btn_manual = Button(
            self.root,
            image=self.Manual,
            command=lambda: Thread(target=self.ROUTINE_MANUAL).start(),
            bg="#23272A",
            activebackground="#23272A",
            bd=0)
        self.btn_load_file = Button(self.root,
                                    image=self.load_file,
                                    command=self.init_module,
                                    bg="#23272A",
                                    activebackground="#23272A",
                                    bd=0)
        self.btn_back = Button(
            self.root,
            image=self.back,
            command=lambda: [self.Menu_Unpack(),
                             self.Menu_1(self.BG1)],
            bg="#23272A",
            activebackground="#23272A",
            bd=0)
        self.btn_quit = Button(self.root,
                               image=self.Quitter,
                               command=self.root.destroy,
                               bg="#23272A",
                               activebackground="#23272A",
                               bd=0)
        self.listB_Module = Listbox(self.root,
                                    exportselection=0,
                                    listvariable=self.niveau,
                                    selectmode="single",
                                    activestyle="none",
                                    height=14,
                                    width=21,
                                    bd=0,
                                    bg="#2C2F33",
                                    fg="#ffffff",
                                    selectbackground="#a2d417",
                                    font=('Helvetica', '10'))
        self.log = Text(self.root,
                        height=12,
                        width=47,
                        bg="#2C2F33",
                        fg="#ffffff",
                        bd=0,
                        font=('Helvetica', '10'))
        self.log.tag_config("green", foreground="#40ff46")
        self.log.tag_config("red", foreground="#ff4040")
        self.log.tag_config("yellow", foreground="#f5ff40")
        self.log.tag_config("cyan", foreground="#00ffff")
        self.log.tag_config("magenta", foreground="#ff00ff")
        self.log.tag_config("white", foreground="#ffffff")
        self.menuAide = Menubutton(self.root,
                                   text='Aide',
                                   width='6',
                                   fg='#ffffff',
                                   bg='#2c2e30',
                                   activebackground='#a2d417',
                                   bd=0)
        self.SousMenuAide = Menu(self.menuAide,
                                 fg='#ffffff',
                                 bg='#2c2e30',
                                 activebackground='#a2d417')
        self.SousMenuAide.add_command(
            label='Notice', command=lambda: open_file("./file/NOTICE.pdf"))
        self.SousMenuAide.add_command(
            label='réinitialiser Login',
            command=lambda: [Login(self.driver, self.root)])
        self.menuAide.configure(menu=self.SousMenuAide)

        self.menuOption = Menubutton(self.root,
                                     text='Option',
                                     width='6',
                                     fg='#ffffff',
                                     bg='#2c2e30',
                                     activebackground='#a2d417',
                                     bd=0)
        self.SousMenuOption = Menu(self.menuOption,
                                   fg='#ffffff',
                                   bg='#2c2e30',
                                   activebackground='#a2d417')
        self.SousMenuOption.add_command(
            label='OverClock',
            command=lambda: [
                self.time_next.set(1),
                print_debug("[MAIN] Overclock ON", "yellow"),
                self.log.insert("end", "Overclock ON\n", "yellow")
            ])
        self.SousMenuOption.add_command(
            label='options',
            command=lambda: [self.Menu_Unpack(),
                             self.Menu_4()])
        self.menuOption.configure(menu=self.SousMenuOption)
        self.option_auto_login = Button(
            self.root,
            text="auto login",
            command=lambda: [
                self.log.delete(1.0, "end"),
                self.input_data.place_forget(),
                self.log.insert(
                    "end",
                    "L'auto login permet de se connecter automatiquement a son compte projet voltaire lors du démarage"
                ),
                self.switch_auto_login.place(x=320, y=30)
            ],
            bg="#a2d417",
            highlightthickness=2,
            bd=0,
            height=2,
            width=20,
            font=('Helvetica', '10'))
        self.option_accuracy = Button(
            self.root,
            text="précision",
            command=lambda: [
                self.switch_auto_login.place_forget(),
                self.log.delete(1.0, "end"),
                self.set_accurate_buffer(),
                self.input_data.place(x=320, y=30),
                self.log.insert("end",
                                "Définit le pourcentage de bonnes réponses")
            ],
            bg="#a2d417",
            highlightthickness=2,
            bd=0,
            height=2,
            width=20,
            font=('Helvetica', '10'))
        self.option_time = Button(
            self.root,
            text="temps d'attente",
            command=lambda: [
                self.switch_auto_login.place_forget(),
                self.log.delete(1.0, "end"),
                self.set_time_buffer(),
                self.input_data.place(x=320, y=30),
                self.log.insert(
                    "end", "définit le temps d'attente entre chaque question")
            ],
            bg="#a2d417",
            highlightthickness=2,
            bd=0,
            height=2,
            width=20,
            font=('Helvetica', '10'))

        self.switch_auto_login = Button(self.root,
                                        text="",
                                        command=None,
                                        bg="#a2d417",
                                        highlightthickness=2,
                                        bd=0,
                                        height=1,
                                        width=10,
                                        font=('Helvetica', '10'))

        self.time_buffer = StringVar()
        self.time_buffer.set(found_data("./file/options.txt", "time", "int"))
        self.accurate_buffer = StringVar()
        self.accurate_buffer.set(
            found_data("./file/options.txt", "accuracy", "int"))

        self.input_data = Entry(self.root,
                                textvariable=None,
                                bg="#2C2F33",
                                fg="#ffffff",
                                width=11,
                                bd=1,
                                font=('Helvetica', '10'))

    def auto_login_switch(self):
        if found_data("./file/options.txt", "auto_login", "int"):
            self.switch_auto_login["bg"] = "#a2d417"
            self.switch_auto_login["text"] = "activer"
            self.switch_auto_login["command"] = lambda: [
                write_data("./file/options.txt", "auto_login", 0),
                self.auto_login_switch()
            ]
        else:
            self.switch_auto_login["bg"] = "#2C2F33"
            self.switch_auto_login["text"] = "desactiver"
            self.switch_auto_login["command"] = lambda: [
                write_data("./file/options.txt", "auto_login", 1),
                self.auto_login_switch()
            ]

    def Menu_1(self, BG):
        self.fond["image"] = BG
        self.fond.pack()
        self.btn_pont_sup.place(x=22, y=170)
        self.btn_sup.place(x=174, y=170)
        self.btn_exc.place(x=326, y=170)
        self.btn_cus.place(x=478, y=170)
        self.btn_quit.place(x=478, y=307)
        self.menuAide.place(x=555, y=0)
        self.menuOption.place(x=510, y=0)

    def Menu_2(self, BGaff):
        self.fond["image"] = BGaff
        self.log["width"] = 47
        self.btn_auto["bg"] = "#a2d417"
        self.btn_auto["activebackground"] = "#a2d417"
        self.fond.pack()
        self.btn_load_file.place(x=30, y=308)
        self.btn_manual.place(x=255, y=60)
        self.btn_auto.place(x=402, y=60)
        self.btn_back.place(x=477, y=309)
        self.log.place(x=255, y=105)
        self.listB_Module.place(x=32, y=60)
        self.listB_Module.selection_set(0)
        self.menuAide.place(x=555, y=0)
        self.menuOption.place(x=510, y=0)

    def Menu_3(self, BGaff):
        self.fond["image"] = BGaff
        self.log["width"] = 79
        self.btn_auto["bg"] = "#23272A"
        self.btn_auto["activebackground"] = "#23272A"
        self.fond.pack()
        self.btn_load_file.place(x=30, y=308)
        self.btn_manual.place(x=30, y=63)
        self.btn_auto.place(x=156, y=63)
        self.btn_back.place(x=477, y=309)
        self.log.place(x=30, y=103)
        self.menuAide.place(x=555, y=0)
        self.menuOption.place(x=500, y=0)
        open_file("./Modules/Custom/Module1.txt")

    def Menu_4(self):
        self.btn_back["command"] = lambda: [
            self.Menu_Unpack(),
            self.Menu_1(self.BG1),
            write_data("./file/options.txt", "time", self.time_buffer.get()),
            write_data("./file/options.txt", "accuracy",
                       self.accurate_buffer.get()),
            self.accuracy.set(
                found_data("./file/options.txt", "accuracy", "int")),
            self.time_next.set(
                found_data("./file/options.txt", "accuracy", "int"))
        ]
        self.auto_login_switch()
        self.log["width"] = 58
        self.log["bg"] = "#23272A"
        self.btn_back.place(x=477, y=309)
        self.menuAide.place(x=555, y=0)
        self.option_auto_login.place(x=0, y=10)
        self.option_accuracy.place(x=0, y=65)
        self.option_time.place(x=0, y=120)
        self.log.place(x=180, y=80)

    def set_time_buffer(self):
        self.input_data["textvariable"] = self.time_buffer

    def set_accurate_buffer(self):
        self.input_data["textvariable"] = self.accurate_buffer

    def Menu_Unpack(self):
        self.log["bg"] = "#2C2F33"
        self.log.delete(1.0, "end")
        self.bot_on = False
        self.btn_auto["image"] = self.Auto_off
        self.btn_back["command"] = lambda: [
            self.Menu_Unpack(), self.Menu_1(self.BG1)
        ]
        self.input_data.place_forget()
        self.switch_auto_login.place_forget()
        self.fond.pack_forget()
        self.btn_load_file.place_forget()
        self.btn_manual.place_forget()
        self.btn_auto.place_forget()
        self.btn_back.place_forget()
        self.listB_Module.place_forget()
        self.log.place_forget()
        self.btn_pont_sup.place_forget()
        self.btn_sup.place_forget()
        self.btn_exc.place_forget()
        self.btn_cus.place_forget()
        self.btn_quit.place_forget()
        self.menuAide.place_forget()
        self.menuOption.place_forget()
        self.option_auto_login.place_forget()
        self.option_accuracy.place_forget()
        self.option_time.place_forget()

    def init_module(self):
        try:
            self.module = Module("./Modules/" + self.prgm.get() + "/Module" +
                                 str(self.listB_Module.curselection()[0] + 1) +
                                 ".txt")
        except:
            self.module = Module("./Modules/Custom/Module1.txt")

        if self.module.data == []:
            self.log.insert("end", "erreur aucun fichier chargé\n", "red")
        else:
            self.log.insert("end", "fichier correctement chargé\n", "green")

    def switch_bot(self):
        if self.bot_on:
            self.bot_on = False
            self.btn_auto["image"] = self.Auto_off
        elif self.module.data != []:
            self.bot_on = True
            self.btn_auto["image"] = self.Auto_on
            self.td = Thread(target=self.ROUTINE_BOT)
            self.td.start()
        else:
            self.log.insert("end", "erreur aucun fichier chargé\n", "red")
            print_debug("AUCUN  FICHIER CHARGÉ", "red")

    def ROUTINE_BOT(self):
        if self.accuracy.get() < 0:
            self.accuracy.set(0)
            write_data("./file/options.txt", "accuracy", 0)
            print_debug("[option] accuracy valeur interdite", "red")
        if self.time_next.get() < 1:
            self.time_next.set(1)
            write_data("./file/options.txt", "time", 1)
            print_debug("[option] time valeur interdite", "red")

        while self.bot_on:
            self.log.delete(1.0, "end")
            return_tag = BOT(self.driver, self.module.data,
                             self.module.test_blanc, self.accuracy.get())
            print_debug("return_tag: " + str(return_tag) + "\n", "yellow")
            if type(return_tag) != list:
                if return_tag == "feature_in":
                    self.log.insert("end", "Merci de fermer la Pop-up\n",
                                    "yellow")
                elif "can't_touche" in return_tag:
                    self.log.insert(
                        "end", "Je n'arrive pas a toucher: " +
                        return_tag[return_tag.index("&") + 1:len(return_tag)] +
                        "\n", "yellow")
                elif return_tag == "not_found":
                    self.log.insert("end", "je trouve pas sorry UwU\n",
                                    "yellow")
                break

            self.number_q += 1
            if self.module.test_blanc == False:
                if self.driver.find_elements_by_xpath(
                        "//span[@title='Mauvaise réponse']"
                ) != [] and return_tag != ["auto_fail"]:
                    text = ''
                    answer_word_els = self.driver.find_elements_by_xpath(
                        "//span[@class = 'answerWord']/span[@class = 'pointAndClickSpan']"
                    )
                    if len(answer_word_els) >= 1:
                        text = answer_word_els[1].text
                    else:
                        text = answer_word_els[0].text or ""

                    if return_tag == []:
                        auto_learning().add_match(
                            self.driver.find_element_by_class_name(
                                "sentence").text, text)
                    else:
                        auto_learning().add_data(return_tag, text)
                    self.log.insert("end",
                                    "erreur détéctée apprentissage...\n",
                                    "green")

                try:
                    self.driver.find_element_by_class_name(
                        "nextButton").click()
                except Exception:
                    pass

            self.log.insert("end",
                            "[" + str(self.number_q) + "]: Clique fait !\n",
                            "green")
            self.log.insert(
                "end",
                open("./file/VTMtext.txt", "r", encoding="utf-8").read())
            self.log.insert("end", "\n\nWaiting...\n", "green")
            i = 0
            while i < self.time_next.get() and self.bot_on:
                sleep(1)
                i += 1

        self.bot_on = False
        self.btn_auto["image"] = self.Auto_off
        self.time_next.set(found_data("./file/options.txt", "time", "int"))
        print_debug(
            "[BOT_ROUTINE] I am a bot, and this action was performed automatically.\nI answered "
            + str(self.number_q) + " questions", "green")
        self.log.insert(
            "end",
            "I am a bot, and this action was performed automatically.\nI answered "
            + str(self.number_q) + " questions\n", "green")
        self.number_q = 0
        return 0

    def ROUTINE_MANUAL(self):
        self.log.delete(1.0, "end")
        return_tag = MANUAL(self.driver, self.module.data,
                            self.module.test_blanc)
        if return_tag == "feature_in":
            self.log.insert("end", "Merci de fermer la Pop-up\n", "yellow")
        elif return_tag == "not_found":
            self.log.insert("end", "je trouve pas sorry UwU\n", "yellow")
        elif return_tag == "no_error":
            self.log.insert("end", "pas de faute :D\n", "green")
        else:
            self.log.insert("end", "la faute est: " + return_tag + "\n",
                            "green")

        self.log.insert(
            "end",
            open("./file/VTMtext.txt", "r", encoding="utf-8").read())
Пример #15
0
class Application:
    def __init__(self, master,name):

        master.geometry("600x450+405+183")
        self.TPanedwindow1 = ttk.Panedwindow(master, orient="horizontal")
        self.TPanedwindow1.place(relx=0.0, rely=0.0, relheight=0.98
                , relwidth=1.01)
        self.TPanedwindow1_p1 = ttk.Labelframe(width=405)
        self.TPanedwindow1.add(self.TPanedwindow1_p1)
        self.TPanedwindow1_p2 = ttk.Labelframe()
        self.TPanedwindow1.add(self.TPanedwindow1_p2)

        self.txtMsgs = tk.Text(self.TPanedwindow1_p1,state='disabled')
        self.txtMsgs.place(relx=0.0, rely=0.0, relheight=0.93, relwidth=1.0, y=-12
                , h=12)
        self.txtMsgs.configure(background="white")
        self.txtMsgs.configure(font="TkTextFont")
        self.txtMsgs.configure(foreground="black")
        self.txtMsgs.configure(highlightbackground="#d9d9d9")
        self.txtMsgs.configure(highlightcolor="black")
        self.txtMsgs.configure(insertbackground="black")
        self.txtMsgs.configure(selectbackground="#c4c4c4")
        self.txtMsgs.configure(selectforeground="black")
        self.txtMsgs.configure(width=405)

        self.txtMsg = tk.Entry(self.TPanedwindow1_p1)
        self.txtMsg.place(relx=0.0, rely=0.95,height=20, relwidth=0.73)
        self.txtMsg.configure(background="white")
        self.txtMsg.configure(disabledforeground="#a3a3a3")
        self.txtMsg.configure(font="TkFixedFont")
        self.txtMsg.configure(foreground="#000000")
        self.txtMsg.configure(highlightbackground="#d9d9d9")
        self.txtMsg.configure(highlightcolor="black")
        self.txtMsg.configure(insertbackground="black")
        self.txtMsg.configure(selectbackground="#c4c4c4")
        self.txtMsg.configure(selectforeground="black")

        self.btnSend = Button(self.TPanedwindow1_p1, command = self.btnSendClicked)
        self.btnSend.place(relx=0.74, rely=0.94, height=24, width=107, y=3)
        self.btnSend.configure(activebackground="#d9d9d9")
        self.btnSend.configure(activeforeground="#000000")
        self.btnSend.configure(background="#d9d9d9")
        self.btnSend.configure(disabledforeground="#a3a3a3")
        self.btnSend.configure(foreground="#000000")
        self.btnSend.configure(highlightbackground="#d9d9d9")
        self.btnSend.configure(highlightcolor="black")
        self.btnSend.configure(pady="0")
        self.btnSend.configure(text='Send')

        self.list = Listbox(self.TPanedwindow1_p2)
        self.list.place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0
                , y=-12, h=12)
        self.list.configure(background="white")
        self.list.configure(disabledforeground="#a3a3a3")
        self.list.configure(font="TkFixedFont")
        self.list.configure(foreground="#000000")
        self.list.configure(highlightbackground="#d9d9d9")
        self.list.configure(highlightcolor="black")
        self.list.configure(selectbackground="#c4c4c4")
        self.list.configure(selectforeground="black")
        self.list.configure(width=134)


        #self.btnSend.bind("<Button-1>", self.btnSendClicked)
        self.list.bind('<<ListboxSelect>>', self.listBoxSelectionChanged)
        self.name = name
        self.startBroadCasting() # start broadcasting that i am online
        self.p2pPort = 49789 # p2p port

    # Send button click event
    def btnSendClicked(self):
        peerName = str(self.list.get(self.list.curselection())) # get peer name whom to send the message
        peerName =peerName.lower()
        if peerName in peersList.keys():
            self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
            self.sock.connect((peersList[peerName],self.p2pPort))  
            msg = self.name + ": "+self.txtMsg.get() 
            if peerName in peersChatList.keys():
                peersChatList[peerName] = peersChatList[peerName] + "\n" + msg + "\n" + datetime.now().strftime('%Y-%m-%d %I:%M:%S %p')
            else:
                peersChatList[peerName] = msg + "\n" + datetime.now().strftime('%Y-%m-%d %I:%M:%S %p')
            
            msg =self.do_padding(msg)
            msg = encrypt(msg,key)     # encrypt the message  
            self.sock.send(msg.encode()) # send the message
            self.sock.close()
            self.txtMsgs.configure(state='normal')
            self.txtMsgs.delete("1.0",END)
            self.txtMsgs.insert(END,peersChatList[peerName]+"\n") # update the chat
            self.txtMsgs.configure(state='disabled')
            self.txtMsg.delete(0,END)

    def do_padding(self,msg):
       return msg.rjust(500, '~')

    # list box selection chnaged event to update the chat
    def listBoxSelectionChanged(self,event):
        try:
            try:
                self.txtMsgs.delete("1.0",END) # clear the chat area
            except Exception as e  :
                pass
            peerName = str(self.list.get(ANCHOR)) # get current selected peer name
            peerName = peerName.lower()
            if(peerName in  peersChatList.keys()): 
                self.txtMsgs.insert(END,peersChatList[peerName]) # update chat
            else:
                self.txtMsgs.insert(END,"")
        except Exception as e:
            pass


    # one of the peers that is started first will become UDP server that listens broadcast request and handles whos online
    class UDPServerThread(threading.Thread):
        def __init__(self, threadID, name,listBoxClients):
            threading.Thread.__init__(self)
            self.threadID = threadID
            self.name = name
            self.listBoxClients = listBoxClients
        def run(self):
            print("Starting " + self.name)
            self.serverSide()

        # to handle udp connections
        def serverSide(self):
            name = self.name
            address = ('', 54545)
            server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
            server_socket.bind(address)
            while True: # keep listening
                print("Listening")
                try:
                    recv_data, addr = server_socket.recvfrom(2048) # get data from socket
                    sender_ip = addr[0] # get sender ip
                    data_received = recv_data.decode() # get data
                    print(sender_ip,':',data_received)
                    if data_received.lower() in peersList.keys() or data_received.lower() == name.lower(): # check if name already exists ask sender to change name
                        server_socket.sendto("Invalid Name".encode(), addr)
                        continue
                    server_socket.sendto(name.encode(), addr) # send my name to connecting client
                    time.sleep(1)
                    server_socket.sendto(key.encode(),addr) # send key for encrypting/decrypting
                    for peer in peersList.keys(): # tell each available peer that a new client has arrived so that they can update their list
                        server_socket.sendto(str((peer.lower(),peersList[peer])).encode(),addr)
                    for sck in udpSockets: # send other available client details to new client
                        try:
                            sck[0].sendto(str((data_received,sender_ip)).encode(),sck[1])
                        except  :
                            pass
                    udpSockets.append((server_socket,addr))
                    peersList[data_received.lower()] = sender_ip 
                    self.listBoxClients.insert(END,data_received)  # add client in list
                except  Exception as e:
                    pass
    
    # this class handles UDP thread functionality, i.e when a new client arrives UDP server will broadcast a message and this class handles it and updates its list. 
    class UDPClientThread(threading.Thread):
        def __init__(self, threadID, name,listBoxClients,client_socket):
            threading.Thread.__init__(self)
            self.threadID = threadID
            self.listBoxClients = listBoxClients
            self.name = name
            self.client_socket = client_socket
        def run(self):
            print("Starting " + self.name)
            self.clientSide()    
       


        # this method handles the udp connections
        def clientSide(self):
            while True:
                try:
                    self.client_socket.settimeout(1000)
                    peer_data,sender_address = self.client_socket.recvfrom(2048) # get data sent by udp server
                    peer = str(peer_data.decode()) # decode the data
                    peer_name = str(peer.split(', ')[0].replace('(','')).replace("'","") # get peerName
                    peer_addr = str(peer.split(', ')[1].replace(')','')).replace("'","") # get perrAddress
                    peersList[peer_name.lower()] = peer_addr 
                    self.listBoxClients.insert(END,peer_name.lower())  # add client in list
                except Exception as e:
                    pass
        


    # this function starts broadcasting and if a UDP server is available connect to it otherwise start a server
    def startBroadCasting(self): 
        address = ('<broadcast>', 54545) 
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        
        global key
        name = self.name
        client_socket.sendto(name.encode(), address) # send the name to server
        try: # try to connect to a broadcast server if available 
            client_socket.settimeout(5) 
            recv_data, addr = client_socket.recvfrom(2048) # get the message from server 
            while str(recv_data.decode()) == "Invalid Name": # if server says its invaild name then ask to re input the name
                name = input("Name already taken, Enter Naw name = ")
                client_socket.sendto(name.encode(), address) 
                recv_data, addr = client_socket.recvfrom(2048)
            peersList[recv_data.decode().lower()] = addr[0] # add the server in peer list
            self.list.insert(END,recv_data.decode().lower()) # update the listBox
            recv_data, addr = client_socket.recvfrom(2048) # get key from server
            
            key = recv_data.decode()
            self.UDPClientThread(1, name,self.list, client_socket).start() #starts udp client
        except Exception as e: # if server is not available start udp server
            key = genKey(500) # generate key
            self.UDPServerThread(2, name,self.list).start()
Пример #16
0
class Main(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        self.db_set = False

        self.configure(relief=GROOVE)
        self.configure(borderwidth="2")

        # Manual link adding
        self.manual_btn = Button(self)
        self.manual_btn.place(relx=0.07, rely=0.81, height=45, width=130)
        self.manual_btn.configure(activebackground="#d9d9d9")
        self.manual_btn.configure(highlightbackground="#d9d9d9")
        self.manual_btn.configure(pady="0")
        self.manual_btn.configure(text="Add manually")
        self.manual_btn.configure(width=130)

        self.file_btn = Button(self)
        self.file_btn.place(relx=0.67, rely=0.81, height=45, width=150)
        self.file_btn.configure(activebackground="#d9d9d9")
        self.file_btn.configure(highlightbackground="#d9d9d9")
        self.file_btn.configure(pady="0")
        self.file_btn.configure(text="Add from file")

        self.label = Label(self)
        self.label.place(relx=0.08, rely=0.0, height=61, width=484)
        self.label.configure(text="Create new playlists and add content to them")
        self.label.configure(width=485)

        self.listbox = Listbox(self)
        self.listbox.place(relx=0.38, rely=0.22, relheight=0.31, relwidth=0.17)
        self.listbox.configure(background="white")
        self.listbox.configure(disabledforeground="#a3a3a3")
        self.listbox.configure(foreground="#000000")
        self.listbox.configure(selectmode=SINGLE)
        self.listbox.configure(width=105)
        for name, value in config.configparser.items('Playlists'):
            if os.path.isdir(value):
                self.listbox.insert('end', name)
            else:
                config.remove_value('Playlists', name)
        self.listbox.bind('<<ListboxSelect>>', self.onselect)

        self.label_name = Label(self)
        self.label_name.place(relx=0.7, rely=0.22, height=31, width=84)
        self.label_name.configure(foreground="#000000")
        self.label_name.configure(text="Name")
        self.label_name.configure(width=85)

        self.entry = Entry(self)
        self.entry.place(relx=0.63, rely=0.31, relheight=0.08, relwidth=0.29)
        self.entry.configure(background="white")
        self.entry.configure(foreground="#000000")
        self.entry.configure(insertbackground="black")
        self.entry.configure(takefocus="0")
        self.entry.configure(width=175)

        self.change_name = Button(self)
        self.change_name.place(relx=0.7, rely=0.42, height=34, width=97)
        self.change_name.configure(activebackground="#d9d9d9")
        self.change_name.configure(highlightbackground="#d9d9d9")
        self.change_name.configure(highlightcolor="black")
        self.change_name.configure(pady="0")
        self.change_name.configure(text="Rename")
        self.change_name.configure(width=100)

        self.new_playlist = Button(self, command=self.new_database)
        self.new_playlist.place(relx=0.08, rely=0.28, height=54, width=107)
        self.new_playlist.configure(activebackground="#d9d9d9")
        self.new_playlist.configure(highlightbackground="#d9d9d9")
        self.new_playlist.configure(highlightcolor="black")
        self.new_playlist.configure(pady="0")
        self.new_playlist.configure(text="Create new playlist")
        self.new_playlist.configure(width=105)

        self.db_name = Entry(self)
        self.db_name.place(relx=0.07, rely=0.44, relheight=0.08, relwidth=0.22)
        self.db_name.configure(fg='grey')
        self.db_name.configure(width=135)
        self.db_name.insert(0, "Input database name here")
        self.db_name.bind('<Button-1>', lambda event: greytext(self.db_name))

    def onselect(self, event):
        w = event.widget
        index = int(w.curselection()[0])
        value = w.get(index)
        set_database(config.configparser.get('Playlists', value))
        if not database.check_integrity():
            messagebox.showwarning('Integrity check failed', 'You might be missing some entries in your list')
        if not self.db_set:
            self.manual_btn.configure(command=lambda: self.controller.show_frame('AddManually'))
            self.file_btn.configure(command=lambda: self.controller.show_frame('ReadFromFile'))
            self.db_set = True

    def new_database(self):
        name = self.db_name.get()
        names = config.configparser.options('Playlists')
        print(name, names)
        if name.strip() == '' or self.db_name.cget('fg') == 'grey':
            messagebox.showerror('Invalid name', "Please input a valid name for the database")
            return
        if name in names:
            messagebox.showerror('Name already in use', "Please select another name")
            return
        path = '../playlists/%s/' % name
        if set_database(path, create=True) is False:
            return
        config.set_value('Playlists', name, path)
        self.listbox.insert('end', name)
Пример #17
0
class Home(TkPage):
    Name = 'Home' #name of the class (attributes)
    Font = lambda Size: ('Courier', Size) #font of the page

    def __init__(self, Parent, *args, **kwargs):
        super().__init__(Parent, *args, **kwargs) #constructor of super class

        self.Songs = [Song.replace('.mid', '') for Song in DirList('Songs') if Song.endswith('.mid')] #mappable songs
        self.MappedSongs = [Song for Song in DirList('MappedSongs') if Song.endswith('.cmid')] #mapped and compiled song
        self.Playing = ThreadEvent() #pause state
        self.Stop = ThreadEvent() #playing state
        self.Stop.set()

        TopLabel = Label(self, text = 'Genshin Lyre Player', font= Home.Font(24), bd = 10) #top label with a title for the page
        TopLabel.place(anchor= 'n', relx= 0.5, rely = 0.015, relwidth = 1, relheight=0.15) #placing the label

        self.ItemList = ListBox(self) #item list of the song
        for Index,Item in enumerate(self.MappedSongs): #for loop for every compiled comiled song
            self.ItemList.insert(Index, Item) #indexing the song in the list
            self.ItemList.itemconfig(Index, {'bg' : '#C2C2C2'}) #background of itemlist
        self.ItemList.place(anchor= 'n', relx= 0.5, rely = 0.19, relwidth = 1, relheight = 0.46) #placing the item list

        #RefreshLogo = Photo(file = 'Res/Refresh.png') #logo of refresh button (not showing at the moment)
        self.RefreshButton = Button\
        (
            self,
            text = 'Refresh',
            command = lambda : self.Refresh()
        ) #button to refresh the song list
        #self.RefreshButton.image = RefreshLogo ########
        self.RefreshButton.place(anchor= 'nw', relx = 0.01, rely = 0.7, relwidth = 0.18, relheight = 0.2) #placing the button

        self.StopButton = Button\
        (
            self,
            text = 'Stop',
            command = lambda : self.StopSong()
        )
        self.StopButton.place(anchor= 'nw', relx= 0.21, rely = 0.7, relwidth = 0.18, relheight = 0.2)

        #PlayLogo = Photo(file = 'Res/Play.png') #logo of play button (not showing at the moment)
        self.PlayButton = Button\
        (
            self,
            text = 'Play',
        )#button to play the song selected
        self.PlayButton.config\
        (
            command =\
            lambda:
            [
                Thread(target = self.PlayTrack, args = (Track,), name = f'{self.ItemList.get("active")}[{i}]', daemon = True).start()
                for i, Track in enumerate(self.LoadSong())
            ]#lambda: self.Play()
        )
        #self.PlayButton.image = PlayLogo ##########
        self.PlayButton.place(anchor= 'nw', relx= 0.41, rely = 0.7, relwidth = 0.18, relheight = 0.2) #placing the button

        #PauseLogo = Photo(file = '') #logo of the pause button
        self.PauseButton = Button\
        (
            self,
            text = 'Pause',
            command = lambda : self.PauseSong()
        ) #button to pause a song
        self.PauseButton.place(anchor= 'nw', relx= 0.61, rely = 0.7, relwidth = 0.18, relheight = 0.2) #placing the button

        self.CompileButton = Button\
        (
            self,
            text = 'Compilation\n     Screen',
            command = lambda : self.Compile(),
        )
        self.CompileButton.place(anchor = 'nw', relx= 0.81, rely = 0.7, relwidth = 0.18, relheight = 0.2) #placing the button

    def Refresh(self): #this function refresh the song list
        self.MappedSongs = [Song for Song in DirList('MappedSongs') if Song.endswith('.cmid')] #check the folder for the songs
        self.ItemList.delete('0','end') #delete every item of the list
        for Index, Item in enumerate(self.MappedSongs): #loop for every song in the folder
            self.ItemList.insert(Index, Item) #index the song in the item list
            self.ItemList.itemconfig(Index, {'bg' : '#C2C2C2'}) #background of the itemlist

    def Countdown(self): #this function create an initial countdown
        for i in range(3): #3...2...1
            print(3-i)
            self.after(1000)

    def LoadSong(self):
        self.PlayButton.state(['disabled']) #disable the play button (might cause some unexpected behaviours)
        Song = self.ItemList.get('active') #getting the selected song from the list
        self.Stop.clear() #reset the stop state
        self.Playing.set()

        with open('MappedSongs/' + Song, 'rb') as InputFile: #opening the compiled midi file
            Music = Load(InputFile) #load the searialized object

        self.Countdown() #initial countdown to give user time to switch to genshin

        return Music

    def PlayTrack(self, Part = None): #this (THREADED) function play a single part (track) of the selected song
        if Part == None:
            raise ValueError('Part cannot be None')
        else:
            print(f'{Identity()} ready')

        global Notes
        global DXCodes
        global NotesFlags
        Elements = len(Part) #keystrokes to execute
        Actual = 0 #element counter

        def PlayNote(Sound, Duration): #this function play a single note of the part
            NotesFlags[Sound] = False #make the resource unavailable for other threads (to avoid deadlock)
            PressKey(DXCodes[Notes[Sound]]) #press note-corresponding key
            Sleep(abs(Duration)) #wait the duration of the note
            ReleaseKey(DXCodes[Notes[Sound]]) #release note-corresponding key
            NotesFlags[Sound] = True #make the resource available for other threads

        def PlayChord(Sounds, Duration): # function play a single chord of the part
            #print(Duration)
            for Sound in Sounds: #for loop  to make every note of the chord unavailable for other threads (to avoid deadlock)
                NotesFlags[Sound] = False #lock single resource

            for Sound in Sounds: #for loop to press chord-corresponding keys
                PressKey(DXCodes[Notes[Sound]]) #press the note-corresponding key of the chord

            Sleep(abs(Duration)) #wait the duration of the notes

            for Sound in Sounds: #for loop to release chord-corresponding keys
                ReleaseKey(DXCodes[Notes[Sound]]) #release the note-corresponding key of the chord

            for Sound in Sounds:#for loop to make every note of the chord available for other threads
                NotesFlags[Sound] = True #unlock single resource

        while not self.Stop.is_set() and Actual < Elements:
            if IsPressed('ctrl+space'):
                if not PauseFunction.locked():
                    PauseFunction.acquire()
                    self.StopSong()
                    PauseFunction.release()
                break
            if IsPressed('shift'):
                print('resume trigger')
                Sleep(1)
                self.Playing.set()

            while self.Playing.is_set() and Actual < Elements:
                if IsPressed('ctrl+space'):
                    if not PauseFunction.locked():
                        PauseFunction.acquire()
                        self.StopSong()
                        PauseFunction.release()
                    break
                if IsPressed('shift'):
                    print('pause trigger')
                    Sleep(1)
                    self.Playing.clear()
                    break

                Counter = 0

                if Part[Actual]['Type'] == 'Note': #check if the element is a note
                    Duration = float(Part[Actual]['Duration'])
                    PartialDuration = Duration / 10 #duration splitted to check multiple times
                    Note = f'{Part[Actual]["Sound"]}{Part[Actual]["Octave"]}' #extract the note

                    if NotesFlags[Note] and IsMainAlive(): #check if the resource is available
                        PlayNote(Note, Duration) #if the reseourse plays the note at full duration
                    else: #if the resource is not available at the moment
                        while not NotesFlags[Note] or Counter < 10: #check if the note is still playable
                            Sleep(PartialDuration) #waiting the partial duration to check availability
                            Counter += 1 #increasing wastd times

                        if NotesFlags[Note] and Counter < 10: #check if the resource are available and the note is still playable
                            RemainingDuration = Duration - (PartialDuration * Counter) #calculate remaining duration
                            PlayNote(Note, RemainingDuration) #play the note at partial duration
                elif Part[Actual]['Type'] == 'Chord': # check if the element is a chord (multiple notes together)
                    NotesList = Part[Actual]['Sound'] #extract notes of the chord
                    Octaves = Part[Actual]['Octave'] #extract respective octaves of the notes
                    Chord = [f'{Note}{Octave}' for Note, Octave in zip(NotesList, Octaves)] # combine notes and octaves together
                    Duration = float(Part[Actual]['Duration'])
                    PartialDuration = Duration / 10 #duration splitted to check multiple times

                    if all([NotesFlags[Note] for Note in Chord]) and IsMainAlive(): #check if all the notes in the chord are available (otherwise the cord wouldn't make sense)
                        PlayChord(Chord, Duration) #play the chord at full duration
                    else:
                        while not all([NotesFlags[Note] for Note in Chord]): #check if the chord is stil playable
                            Sleep(PartialDuration) #waiting the partial duration to check availability
                            Counter += 1 #increasing wasted times

                        if all([NotesFlags[Note] for Note in Chord]) and IsMainAlive(): #check if the resources are available and the chors is still playable
                            RemainingDuration = Duration - (PartialDuration * Counter) #calculate remaining duration
                            PlayChord(Chord, RemainingDuration) #play the chord at partial duration
                elif Part[Actual]['Type'] == 'Rest': #check if the element is a rest
                    Duration = float(Part[Actual]['Duration'])
                    Sleep(abs(Duration)) #wait the rest

                Actual += 1 #increase the played notes

        Sleep(5)
        print(f'{Identity()} ended')

    def PauseSong(self): #this fucntion pause the song playing
        Sleep(2) #delay to get rid of function call besides the first
        if self.Playing.is_set(): #check if the song is playing
            print(f'{Identity()} is pausing')
            self.Playing.clear() #clear the playing state
        if not self.Playing.is_set(): #check if the song is not playing
            print(f'{Identity()} is resuming')
            self.Playing.set() #set the song as playing

    def StopSong(self): #this fucntion stop the song
        if not StopFunction.locked(): #check if the fucntion has called by multiple thread
            print('Stop called')
            Sleep(1)
            self.Stop.set() #set the stop state
            self.Playing.clear() #clear the playing state
            self.PlayButton.state(['!disabled']) #enable the play button
            self.PlayButton.state(['!pressed']) #reset the play button to the default state
            ReleaseResources() #release possible hanging resources

    def Compile(self): #this function switch to compilation screen
        GenshinLyrePlayer.Raise(CompilationScreen.Name)
Пример #18
0
class App:
    def __init__(self):
        self.w = Tk()
        self.w.geometry('320x340')
        self.w.title('python库下载器V2.1')
        self.creat_res()
        self.res_config()  # 配置文件
        self.pp = Pip_downs()
        self.w.mainloop()

    def creat_res(self):  # 创建控件
        self.temp = StringVar()  # 输入框
        self.path_file = StringVar()  # 存储路径
        self.sorce = StringVar()  # 选择源
        self.B_search = Button(self.w, text='查找')
        self.B_file = Button(self.w, text='选择存储目录')
        self.B_down = Button(self.w, text='下载')
        self.B_add = Button(self.w, text='添加')
        self.L_search = Label(self.w, text='选择源:', bg='#B2DFEE')
        self.E_input = Entry(self.w, textvariable=self.temp)
        self.E_path = Entry(self.w, textvariable=self.path_file)
        self.L_pack = Label(self.w, text='找到:', bg='#B2DFEE')
        self.L_packs = Label(self.w, text='找到:', bg='#B2DFEE')
        self.L_box = Listbox(self.w, selectmode=SINGLE)
        self.L_box_se = Listbox(self.w, selectmode=SINGLE)
        self.S_col_y_1 = Scrollbar(self.w, orient=VERTICAL)  # 左边Y
        self.S_col_x_1 = Scrollbar(self.w, orient=HORIZONTAL)  # 左边X
        self.S_col_y_2 = Scrollbar(self.w, orient=VERTICAL)  # 右边Y
        self.S_col_x_2 = Scrollbar(self.w, orient=HORIZONTAL)  # 右边X
        self.L_message = Label(self.w, text='', bg='#C6E2FF')
        self.creat_radios()
        self.res_place()

    def creat_radios(self):  # 选择器
        self.R_qinghua = Radiobutton(self.w,
                                     text='清华',
                                     variable=self.sorce,
                                     value='1')
        self.R_alibaba = Radiobutton(self.w,
                                     text='阿里',
                                     variable=self.sorce,
                                     value='2')
        self.R_douban = Radiobutton(self.w,
                                    text='豆瓣',
                                    variable=self.sorce,
                                    value='3')

    def res_place(self):  # 控件布局
        self.L_search.place(x=10, y=10, width=100, height=20)
        self.B_search.place(x=200, y=40, width=50, height=30)
        self.E_input.place(x=10, y=40, width=170, height=30)
        self.E_path.place(x=10, y=80, width=170, height=30)
        self.L_pack.place(x=10, y=113, width=200, height=23)
        self.L_packs.place(x=220, y=113, width=90, height=23)
        self.B_file.place(x=200, y=80, width=90, height=30)
        self.R_qinghua.place(x=110, y=10, width=60, height=20)
        self.R_alibaba.place(x=170, y=10, width=60, height=20)
        self.R_douban.place(x=230, y=10, width=60, height=20)
        self.L_box.place(x=10, y=140, width=140, height=175)
        self.L_box_se.place(x=180, y=140, width=120, height=120)
        self.B_down.place(x=250, y=279, width=50, height=28)
        self.B_add.place(x=186, y=279, width=50, height=28)
        self.S_col_y_1.place(x=150, y=140, width=15, height=175)
        self.S_col_x_1.place(x=10, y=315, width=140, height=15)
        self.S_col_y_2.place(x=300, y=140, width=15, height=120)
        self.S_col_x_2.place(x=180, y=260, width=120, height=15)
        self.L_message.place(x=170, y=308, width=140, height=28)

    def res_config(self):  # 滚动条配置
        self.S_col_y_1.config(command=self.L_box.yview)
        self.L_box["yscrollcommand"] = self.S_col_y_1.set
        self.S_col_x_1.config(command=self.L_box.xview)
        self.L_box["xscrollcommand"] = self.S_col_x_1.set
        self.S_col_y_2.config(command=self.L_box_se.yview)
        self.L_box_se["yscrollcommand"] = self.S_col_y_2.set
        self.S_col_x_2.config(command=self.L_box_se.xview)
        self.L_box_se["xscrollcommand"] = self.S_col_x_2.set
        self.B_file.config(command=self.select_menu)
        self.B_search.config(command=self.search_res)
        self.sorce.set('1')
        self.B_add.config(command=self.add_pack_to_box)
        self.B_down.config(command=self.lis_box_down)

    def select_menu(self):
        self.path_f = askdirectory()
        self.path_file.set(self.path_f)

    def clear_box(self):
        self.L_box.delete(0, END)

    def search_res(self):  # 查找库
        print('search')
        print(self.temp.get())
        self.clear_box()
        lis_new = []
        if self.temp.get() != '':
            lis = self.pp.get_cons(self.sorce.get())
            count = 0
            for s_str in lis:
                if self.temp.get() in s_str:
                    print('找到库{}'.format(s_str))
                    lis_new.append(s_str)
                else:
                    count += 1
            if count == len(lis):
                messagebox.showwarning(title='警告',
                                       message='没找到库{}'.format(
                                           self.temp.get()))
            msg = '找到{}个与{}相关的库'.format(len(lis_new), self.temp.get())
            print(msg)
            self.L_pack.config(text=msg)
            for msg in lis_new:
                self.L_box.insert(END, msg)
            return lis_new
        else:
            messagebox.showerror(title='警告', message='请输入库名')

    def add_pack_to_box(self):  # 添加列表至lisbox
        cur_index = self.L_box.curselection()
        print(cur_index)
        if len(cur_index) != 0:
            files_dic = self.pp.get_files_url(self.sorce.get(),
                                              self.L_box.get(cur_index))
            self.L_packs.config(text='各版本{}个'.format(len(files_dic)))
            for name, url in files_dic.items():
                self.L_box_se.insert(END, name)
        else:
            messagebox.showwarning(title='警告', message='请选择库')

    def lis_box_down(self):
        print('down')
        cur_index = self.L_box_se.curselection()
        if len(cur_index) != 0:
            print('路径', self.path_file.get())
            if self.path_file.get() != '':
                pack_name = self.L_box_se.get(cur_index).split('-')[0]
                if '_' in pack_name:
                    pack_name = pack_name.replace('_', '-')
                print(self.sorce.get(), pack_name,
                      self.L_box_se.get(cur_index), self.path_file.get())
                self.pp.down_file(self.sorce.get(), pack_name,
                                  self.L_box_se.get(cur_index),
                                  self.path_file.get())
                self.L_message.config(text='{}已下载'.format(pack_name))
            else:
                messagebox.showwarning(title='警告', message='请选择存储路径')
        else:  # 如果没选择
            messagebox.showwarning(title='警告', message='请选择库')
Пример #19
0
class Application:
    def __init__(self, master, name):

        master.geometry("600x450+405+183")
        self.TPanedwindow1 = ttk.Panedwindow(master, orient="horizontal")
        self.TPanedwindow1.place(relx=0.0,
                                 rely=0.0,
                                 relheight=0.98,
                                 relwidth=1.01)
        self.TPanedwindow1_p1 = ttk.Labelframe(width=405)
        self.TPanedwindow1.add(self.TPanedwindow1_p1)
        self.TPanedwindow1_p2 = ttk.Labelframe()
        self.TPanedwindow1.add(self.TPanedwindow1_p2)

        self.txtMsgs = tk.Text(self.TPanedwindow1_p1, state='disabled')
        self.txtMsgs.place(relx=0.0,
                           rely=0.0,
                           relheight=0.93,
                           relwidth=1.0,
                           y=-12,
                           h=12)
        self.txtMsgs.configure(background="white")
        self.txtMsgs.configure(font="TkTextFont")
        self.txtMsgs.configure(foreground="black")
        self.txtMsgs.configure(highlightbackground="#d9d9d9")
        self.txtMsgs.configure(highlightcolor="black")
        self.txtMsgs.configure(insertbackground="black")
        self.txtMsgs.configure(selectbackground="#c4c4c4")
        self.txtMsgs.configure(selectforeground="black")
        self.txtMsgs.configure(width=405)

        self.txtMsg = tk.Entry(self.TPanedwindow1_p1)
        self.txtMsg.place(relx=0.0, rely=0.95, height=20, relwidth=0.73)
        self.txtMsg.configure(background="white")
        self.txtMsg.configure(disabledforeground="#a3a3a3")
        self.txtMsg.configure(font="TkFixedFont")
        self.txtMsg.configure(foreground="#000000")
        self.txtMsg.configure(highlightbackground="#d9d9d9")
        self.txtMsg.configure(highlightcolor="black")
        self.txtMsg.configure(insertbackground="black")
        self.txtMsg.configure(selectbackground="#c4c4c4")
        self.txtMsg.configure(selectforeground="black")

        self.btnSend = Button(self.TPanedwindow1_p1)
        self.btnSend.place(relx=0.74, rely=0.94, height=24, width=107, y=3)
        self.btnSend.configure(activebackground="#d9d9d9")
        self.btnSend.configure(activeforeground="#000000")
        self.btnSend.configure(background="#d9d9d9")
        self.btnSend.configure(disabledforeground="#a3a3a3")
        self.btnSend.configure(foreground="#000000")
        self.btnSend.configure(highlightbackground="#d9d9d9")
        self.btnSend.configure(highlightcolor="black")
        self.btnSend.configure(pady="0")
        self.btnSend.configure(text='Send')

        self.list = Listbox(self.TPanedwindow1_p2)
        self.list.place(relx=0.0,
                        rely=0.0,
                        relheight=1.0,
                        relwidth=1.0,
                        y=-12,
                        h=12)
        self.list.configure(background="white")
        self.list.configure(disabledforeground="#a3a3a3")
        self.list.configure(font="TkFixedFont")
        self.list.configure(foreground="#000000")
        self.list.configure(highlightbackground="#d9d9d9")
        self.list.configure(highlightcolor="black")
        self.list.configure(selectbackground="#c4c4c4")
        self.list.configure(selectforeground="black")
        self.list.configure(width=134)
Пример #20
0
                fg="red")
lblinfo.grid(row=0, column=0)
list = []
list5 = []
for rt, dirs, files in os.walk('D:/INNOVATIVE/songs'):
    for file in files:
        if file.endswith('.mp3'):
            list.append(os.path.join(rt, file))
txtdisplay = Listbox(root,
                     height=23,
                     width=38,
                     bd=16,
                     font=('arial', 15, 'bold'),
                     fg="green",
                     bg="black")
txtdisplay.place(relx=0.7, rely=0.6, anchor=CENTER)

i = 0
for name in list:
    list5.append(ntpath.basename(name))
    txtdisplay.insert(END, list5[i])
    i += 1
index = 0


def next():

    global index
    index += 1
    if index == len(list):
        btn5['state'] = 'disabled'
Пример #21
0
class App:
    # 初始化类的一些属性和方法
    def __init__(self):
        self.root = Tk()
        self.width = self.root.winfo_screenwidth()  # 获取电脑窗体的宽度
        self.height = self.root.winfo_screenheight()  # 获取电脑窗体的高度

        '''设置开学日期'''
        self.basicDate = '2019-9-2'
        self.basicDate = strptime(self.basicDate, "%Y-%m-%d")

        '''获取当前日期'''
        self.today = strftime('%Y-%m-%d')
        # print(type(self.today))
        # self.today = '2019-9-16'
        self.today = strptime(self.today, "%Y-%m-%d")
        # print(type(self.today))
        '''获取当前日期'''

        '''计算当前是第几周'''
        self.basicDate = datetime(self.basicDate[0], self.basicDate[1], self.basicDate[2])
        self.today = datetime(self.today[0], self.today[1], self.today[2])
        self.result = (self.today - self.basicDate).days + 1  # 今天是开学的第self.result天
        # print(self.result)
        self.week = 0
        if self.result % 7 == 0:
            self.week = self.result // 7
        else:
            self.week = self.result // 7 + 1
        '''计算当前是第几周'''

        self.initForm()

    # 初始化应用窗体
    def initForm(self):
        self.root.title("课表(当前是第"+str(self.week)+"周)—— 作者:逸轩")
        w = int((self.width - 880) / 2)
        h = int((self.height - 500) / 2)
        self.root.geometry('880x500+%s+%s' % (w, h))


        self.initClasses(self.week)

        self.initListbox()


        self.root.mainloop()

    # 初始化课表
    def initClasses(self, week):


        self.fm = Frame(self.root, height=200, width=400)
        self.fm.place(x=0, y=0)

        # 上课时间
        labelTime = Label(self.fm, text=' ', fg='black')
        labelTime.grid(row=0, column=0, sticky=E, padx=5, pady=5)

        labelTime = Label(self.fm, text='1(8:00)', fg='black', background='#7FFF00', width=12)
        labelTime.grid(row=1, column=0, sticky=E, padx=5, pady=5)

        labelTime = Label(self.fm, text='2(8:55)', fg='black', background='#FFD700', width=12)
        labelTime.grid(row=2, column=0, sticky=E, padx=5, pady=5)

        labelTime = Label(self.fm, text='3(10:00)', fg='black', background='#FF69B4', width=12)
        labelTime.grid(row=3, column=0, sticky=E, padx=5, pady=5)

        labelTime = Label(self.fm, text='4(10:55)', fg='black', background='#BA2BE2', width=12)
        labelTime.grid(row=4, column=0, sticky=E, padx=5, pady=5)

        labelTime = Label(self.fm, text='5(14:00)', fg='black', background='#FFA07A', width=12)
        labelTime.grid(row=5, column=0, sticky=E, padx=5, pady=5)

        labelTime = Label(self.fm, text='6(14:55)', fg='black', background='#87CEFA', width=12)
        labelTime.grid(row=6, column=0, sticky=E, padx=5, pady=5)

        labelTime = Label(self.fm, text='7(16:00)', fg='black', background='#00FFFF', width=12)
        labelTime.grid(row=7, column=0, sticky=E, padx=5, pady=5)

        labelTime = Label(self.fm, text='8(16:55)', fg='black', background='#98FB98', width=12)
        labelTime.grid(row=8, column=0, sticky=E, padx=5, pady=5)

        labelTime = Label(self.fm, text='9(19:00)', fg='black', background='#FFFF00', width=12)
        labelTime.grid(row=9, column=0, sticky=E, padx=5, pady=5)

        labelTime = Label(self.fm, text='10(19:55)', fg='black', background='#D2691E', width=12)
        labelTime.grid(row=10, column=0, sticky=E, padx=5, pady=5)

        labelTime = Label(self.fm, text='11(20:50)', fg='black', background='#FF6347', width=12)
        labelTime.grid(row=11, column=0, sticky=E, padx=5, pady=5)

        label1 = Label(self.fm, text='星期一', fg='black', background='#FF8C00', width=20)
        label1.grid(row=0, column=1, sticky=W + S + N + E, padx=5, pady=5)

        label2 = Label(self.fm, text='星期二', fg='black', background='#FF8C00', width=20)
        label2.grid(row=0, column=2, sticky=W + S + N + E, padx=5, pady=5)

        label3 = Label(self.fm, text='星期三', fg='black', background='#FF8C00', width=20)
        label3.grid(row=0, column=3, sticky=W + S + N + E, padx=5, pady=5)

        label4 = Label(self.fm, text='星期四', fg='black', background='#FF8C00', width=20)
        label4.grid(row=0, column=4, sticky=W + S + N + E, padx=5, pady=5)

        label5 = Label(self.fm, text='星期五', fg='black', background='#FF8C00', width=20)
        label5.grid(row=0, column=5, sticky=W + S + N + E, padx=5, pady=5)
        # self.fm.place_forget()


        # 整理星期一*************************************************

        if week >= 16 and week <= 17:
            label1 = Label(self.fm, text='VC++(计科楼101)', fg='black', background='#7FFF00')
            label1.grid(row=1, column=1, sticky=W + S + N + E, padx=5, pady=5)

            label1 = Label(self.fm, text='VC++(计科楼101)', fg='black', background='#FFD700', width=20)
            label1.grid(row=2, column=1, sticky=W + S + N + E, padx=5, pady=5)

        if (week >= 4 and week <= 6) or (week >= 8 and week <= 16):
            label1 = Label(self.fm, text='JavaScript(教1楼307)', fg='black', background='#FF69B4', width=20)
            label1.grid(row=3, column=1, sticky=W + S + N + E, padx=5, pady=5)

            label1 = Label(self.fm, text='JavaScript(教1楼307)', fg='black', background='#BA2BE2', width=20)
            label1.grid(row=4, column=1, sticky=W + S + N + E, padx=5, pady=5)

        if week >= 1 and week <= 16:
            label1 = Label(self.fm, text='大学英语(经法楼107)', fg='black', background='#FFA07A', width=20)
            label1.grid(row=5, column=1, sticky=W + S + N + E, padx=5, pady=5)

            label1 = Label(self.fm, text='大学英语(经法楼107)', fg='black', background='#87CEFA', width=20)
            label1.grid(row=6, column=1, sticky=W + S + N + E, padx=5, pady=5)

        if (week >= 1 and week <= 6) or (week >= 8 and week <= 17):
            label1 = Label(self.fm, text='VC++(教1楼306)', fg='black', background='#00FFFF', width=20)
            label1.grid(row=7, column=1, sticky=W + S + N + E, padx=5, pady=5)

            label1 = Label(self.fm, text='VC++(教1楼306)', fg='black', background='#98FB98', width=20)
            label1.grid(row=8, column=1, sticky=W + S + N + E, padx=5, pady=5)

        if (week >= 1 and week <= 6) or (week >= 8 and week <= 17):
            label1 = Label(self.fm, text='VC++(计科楼203)', fg='black', background='#FFFF00', width=20)
            label1.grid(row=9, column=1, sticky=W + S + N + E, padx=5, pady=5)

            label1 = Label(self.fm, text='VC++(计科楼203)', fg='black', background='#D2691E', width=20)
            label1.grid(row=10, column=1, sticky=W + S + N + E, padx=5, pady=5)

        # 整理星期一*************************************************

        # 整理星期二*************************************************

        if (week >= 1 and week <= 6) or (week >= 8 and week <= 17):
            label2 = Label(self.fm, text='JSP(教1楼506)', fg='black', background='#7FFF00', width=20)
            label2.grid(row=1, column=2, sticky=W + S + N + E, padx=5, pady=5)

            label2 = Label(self.fm, text='JSP(教1楼506)', fg='black', background='#FFD700', width=20)
            label2.grid(row=2, column=2, sticky=W + S + N + E, padx=5, pady=5)

        if (week >= 5 and week <= 6) or (week >= 8 and week <= 17):
            label2 = Label(self.fm, text='JSP(计科楼203)', fg='black', background='#FF69B4', width=20)
            label2.grid(row=3, column=2, sticky=W + S + N + E, padx=5, pady=5)

            label2 = Label(self.fm, text='JSP(计科楼203)', fg='black', background='#BA2BE2', width=20)
            label2.grid(row=4, column=2, sticky=W + S + N + E, padx=5, pady=5)

        if (week >= 5 and week <= 6) or (week >= 8 and week <= 17):
            label2 = Label(self.fm, text='IOS(教1楼509)', fg='black', background='#FFA07A', width=20)
            label2.grid(row=5, column=2, sticky=W + S + N + E, padx=5, pady=5)

            label2 = Label(self.fm, text='IOS(教1楼509)', fg='black', background='#87CEFA', width=20)
            label2.grid(row=6, column=2, sticky=W + S + N + E, padx=5, pady=5)

        if week == 17:
            label2 = Label(self.fm, text='Java(计科楼203)', fg='black', background='#7FFF00', width=20)
            label2.grid(row=9, column=2, sticky=W + S + N + E, padx=5, pady=5)

            label2 = Label(self.fm, text='Java(计科楼203)', fg='black', background='#7FFF00', width=20)
            label2.grid(row=10, column=2, sticky=W + S + N + E, padx=5, pady=5)

        if (week <= 16) and (week % 2 == 0):
            label2 = Label(self.fm, text='计算机网络(计科楼104)', fg='black', background='#FFFF00', width=20)
            label2.grid(row=9, column=2, sticky=W + S + N + E, padx=5, pady=5)

            label2 = Label(self.fm, text='计算机网络(计科楼104)', fg='black', background='#D2691E', width=20)
            label2.grid(row=10, column=2, sticky=W + S + N + E, padx=5, pady=5)

        if (week <= 16) and (week % 2 == 0):
            label2 = Label(self.fm, text='计算机网络(计科楼104)', fg='black', background='#FF6347', width=20)
            label2.grid(row=11, column=2, sticky=W + S + N + E, padx=5, pady=5)

        # 整理星期二*************************************************

        # 整理星期三*************************************************

        if (week >= 9 and week <= 17) and (week % 2 != 0):
            label3 = Label(self.fm, text='计算机网络(教1楼308)', fg='black', background='#FF69B4', width=20)
            label3.grid(row=3, column=3, sticky=W + S + N + E, padx=5, pady=5)

            label3 = Label(self.fm, text='计算机网络(教1楼308)', fg='black', background='#BA2BE2', width=20)
            label3.grid(row=4, column=3, sticky=W + S + N + E, padx=5, pady=5)

        if (week >= 1 and week <= 6) or (week == 8):
            label3 = Label(self.fm, text='计算机网络(教1楼308)', fg='black', background='#FF69B4', width=20)
            label3.grid(row=3, column=3, sticky=W + S + N + E, padx=5, pady=5)

            label3 = Label(self.fm, text='计算机网络(教1楼308)', fg='black', background='#BA2BE2', width=20)
            label3.grid(row=4, column=3, sticky=W + S + N + E, padx=5, pady=5)

        if (week >= 10 and week <= 16) and (week % 2 == 0):
            label3 = Label(self.fm, text='IOS(计科楼203)', fg='black', background='#FF69B4', width=20)
            label3.grid(row=3, column=3, sticky=W + S + N + E, padx=5, pady=5)

            label3 = Label(self.fm, text='IOS(计科楼203)', fg='black', background='#BA2BE2', width=20)
            label3.grid(row=4, column=3, sticky=W + S + N + E, padx=5, pady=5)

        if (week >= 1 and week <= 6) or (week >= 8 and week <= 17):
            label3 = Label(self.fm, text='Java(教1楼509)', fg='black', background='#FFA07A', width=20)
            label3.grid(row=5, column=3, sticky=W + S + N + E, padx=5, pady=5)

            label3 = Label(self.fm, text='Java(教1楼509)', fg='black', background='#87CEFA', width=20)
            label3.grid(row=6, column=3, sticky=W + S + N + E, padx=5, pady=5)

        if (week >= 1 and week <= 6) or (week >= 8 and week <= 17):
            label3 = Label(self.fm, text='Java(计科楼203)', fg='black', background='#00FFFF', width=20)
            label3.grid(row=7, column=3, sticky=W + S + N + E, padx=5, pady=5)

            label3 = Label(self.fm, text='Java(计科楼203)', fg='black', background='#98FB98', width=20)
            label3.grid(row=8, column=3, sticky=W + S + N + E, padx=5, pady=5)

        # 整理星期三*************************************************

        # 整理星期四*************************************************

        if (week >= 1 and week <= 6) or (week >= 8 and week <= 17):
            label4 = Label(self.fm, text='数据库(教1楼406)', fg='black', background='#7FFF00', width=20)
            label4.grid(row=1, column=4, sticky=W + S + N + E, padx=5, pady=5)

            label4 = Label(self.fm, text='数据库(教1楼406)', fg='black', background='#FFD700', width=20)
            label4.grid(row=2, column=4, sticky=W + S + N + E, padx=5, pady=5)

        if (week >= 4 and week <= 6) or (week >= 8 and week <= 16):
            label4 = Label(self.fm, text='JavaScript(计科楼104)', fg='black', background='#FF69B4', width=20)
            label4.grid(row=3, column=4, sticky=W + S + N + E, padx=5, pady=5)

            label4 = Label(self.fm, text='JavaScript(计科楼104)', fg='black', background='#BA2BE2', width=20)
            label4.grid(row=4, column=4, sticky=W + S + N + E, padx=5, pady=5)

        if week == 6 or week == 8:
            label4 = Label(self.fm, text='IOS(计科楼203)', fg='black', background='#FFA07A', width=20)
            label4.grid(row=5, column=4, sticky=W + S + N + E, padx=5, pady=5)

            label4 = Label(self.fm, text='IOS(计科楼203)', fg='black', background='#87CEFA', width=20)
            label4.grid(row=6, column=4, sticky=W + S + N + E, padx=5, pady=5)

        if week >= 6 and week <= 11:
            label4 = Label(self.fm, text='心理健康(教1楼211)', fg='black', background='#FFFF00', width=20)
            label4.grid(row=9, column=4, sticky=W + S + N + E, padx=5, pady=5)

            label4 = Label(self.fm, text='心理健康(教1楼211)', fg='black', background='#D2691E', width=20)
            label4.grid(row=10, column=4, sticky=W + S + N + E, padx=5, pady=5)

        if week >= 6 and week <= 11:
            label4 = Label(self.fm, text='心理健康(教1楼211)', fg='black', background='#FF6347', width=20)
            label4.grid(row=11, column=4, sticky=W + S + N + E, padx=5, pady=5)

        # 整理星期四*************************************************

        # 整理星期五*************************************************

        if (week <= 17 and week % 2 != 0) and (week != 7):
            label5 = Label(self.fm, text='数据库(教1楼408)', fg='black', background='#7FFF00', width=20)
            label5.grid(row=1, column=5, sticky=W + S + N + E, padx=5, pady=5)

            label5 = Label(self.fm, text='数据库(教1楼408)', fg='black', background='#FFD700', width=20)
            label5.grid(row=2, column=5, sticky=W + S + N + E, padx=5, pady=5)

        if (week >= 5 and week <= 16) and (week % 2 == 0):
            label5 = Label(self.fm, text='数据库(计科楼203)', fg='black', background='#7FFF00', width=20)
            label5.grid(row=1, column=5, sticky=W + S + N + E, padx=5, pady=5)

            label5 = Label(self.fm, text='数据库(计科楼203)', fg='black', background='#FFD700', width=20)
            label5.grid(row=2, column=5, sticky=W + S + N + E, padx=5, pady=5)

        if (week <= 17 and week % 2 != 0) and (week != 7):
            label5 = Label(self.fm, text='Python(教1楼507)', fg='black', background='#FF69B4', width=20)
            label5.grid(row=3, column=5, sticky=W + S + N + E, padx=5, pady=5)

            label5 = Label(self.fm, text='Python(教1楼507)', fg='black', background='#BA2BE2', width=20)
            label5.grid(row=4, column=5, sticky=W + S + N + E, padx=5, pady=5)

        if (week >= 4 and week <= 6) or (week >= 8 and week <= 16):
            label5 = Label(self.fm, text='Python(计科楼303)', fg='black', background='#FFA07A', width=20)
            label5.grid(row=5, column=5, sticky=W + S + N + E, padx=5, pady=5)

            label5 = Label(self.fm, text='Python(计科楼303)', fg='black', background='#87CEFA', width=20)
            label5.grid(row=6, column=5, sticky=W + S + N + E, padx=5, pady=5)

        # 整理星期五*************************************************

    # 点击确定按钮
    def confirmBtn(self):
        value = self.listbox.get(self.listbox.curselection())
        # messagebox.showinfo('提示', '你刚才点击了' + str(value))confirmBtn
        self.fm.place_forget()
        if str(value) == '自动':
            self.initClasses(self.week)
            self.root.title("课表(当前是第" + str(self.week) + "周)—— 作者:逸轩")
        else:
            self.initClasses(value)
            self.root.title("课表(当前是第" + str(value) + "周)—— 作者:逸轩")



    # 初始化滑动列表
    def initListbox(self):
        label = Label(self.root, text='手动选择周数查看:')
        label.place(x=500, y=450)

        self.listbox = Listbox(self.root, width=5, height=4, background='yellow')
        self.listbox.place(x=630, y=420)
        self.listbox.insert(1, '自动')

        for i in range(1, 18):
            self.listbox.insert(17, i)
        self.listbox.selection_set(0)

        scroll = Scrollbar(self.root, relief='ridge', command=self.listbox.yview)
        scroll.place(x=670, y=420, height=65)
        self.listbox.configure(yscrollcommand=scroll.set)

        button = Button(self.root, text='确定', width=6, command=self.confirmBtn)
        button.place(x=720, y=450)
Пример #22
0
class Settings_for_frame(Frame):
    def __init__(self, master, board, tag, board_dims):
        super().__init__(master, bg="#435661")

        self.board = board
        self.board_width, self.board_height = board_dims
        self.tag = tag
        self.background = "white"
        self.record = {}
        self.index = 0
        self.spin_relx = None
        self.spin_rely = None
        self.spin_relw = None
        self.spin_relh = None
        self.label_arguments = None
        self.entry_arguments = None
        self.listbox = None
        self.entry_name = None
        self.set_layout()
        self.set_bindings()
        self.set_listbox()
        self.set_spinboxes()

    def set_layout(self):
        # self-explanatory
        Label(self, background='#435661', text='relx:', foreground='#defffc') \
            .place(relx=0.145, rely=0.0125, relwidth=0.1625, relheight=0.025, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='rely:') \
            .place(relx=0.6845, rely=0.0135, relwidth=0.155, relheight=0.0225, anchor='nw')

        Label(self, background='#435661', text='relwidth:', foreground='#defffc') \
            .place(relx=0.044, rely=0.089, relwidth=0.37, relheight=0.02125, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='relheight:') \
            .place(relx=0.667, rely=0.0875, relwidth=0.195, relheight=0.02375, anchor='nw')

        self.spin_relx = Spinbox(self,
                                 readonlybackground='#defffc',
                                 highlightthickness=0,
                                 foreground='#435661',
                                 from_=0,
                                 command=self.mod,
                                 to_=1,
                                 increment=0.001,
                                 justify='center')
        self.spin_relx.place(relx=0.085,
                             rely=0.0425,
                             relwidth=0.295,
                             relheight=0.03375,
                             anchor='nw')

        self.spin_rely = Spinbox(self,
                                 readonlybackground='#defffc',
                                 foreground='#435661',
                                 justify='center',
                                 highlightthickness=0,
                                 command=self.mod,
                                 from_=0,
                                 to_=1,
                                 increment=0.001)
        self.spin_rely.place(relx=0.6135,
                             rely=0.0425,
                             relwidth=0.3005,
                             relheight=0.03375,
                             anchor='nw')

        self.spin_relw = Spinbox(self,
                                 readonlybackground='#defffc',
                                 foreground='#435661',
                                 justify='center',
                                 highlightthickness=0,
                                 command=self.mod,
                                 from_=0,
                                 to_=1,
                                 increment=0.001)
        self.spin_relw.place(relx=0.084,
                             rely=0.1175,
                             relwidth=0.295,
                             relheight=0.035,
                             anchor='nw')

        self.spin_relh = Spinbox(self,
                                 readonlybackground='#defffc',
                                 foreground='#435661',
                                 justify='center',
                                 highlightthickness=0,
                                 command=self.mod,
                                 from_=0,
                                 to_=1,
                                 increment=0.001)
        self.spin_relh.place(relx=0.6115,
                             rely=0.1177,
                             relwidth=0.304,
                             relheight=0.035,
                             anchor='nw')

        self.label_arguments = Label(self,
                                     background='#557282',
                                     foreground='#defffc')
        self.label_arguments.place(relx=0.086,
                                   rely=0.1832,
                                   relwidth=0.8305,
                                   relheight=0.06125,
                                   anchor='nw')

        self.entry_arguments = Entry(self,
                                     background='#defffc',
                                     foreground='#435661',
                                     justify='center')
        self.entry_arguments.place(relx=0.22,
                                   rely=0.2625,
                                   relwidth=0.545,
                                   relheight=0.04375,
                                   anchor='nw')

        self.listbox = Listbox(self,
                               background='#557282',
                               foreground='#defffc',
                               borderwidth=0)
        self.listbox.place(relx=0.085,
                           rely=0.3275,
                           relwidth=0.83,
                           relheight=0.4062,
                           anchor='nw')

        myButton(self, command=lambda *a: self.set_value(), text='OK') \
            .place(relx=0.8245, rely=0.2672, relwidth=0.13, relheight=0.0355, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='Name:', anchor='w') \
            .place(relx=0.083, rely=0.766, relwidth=0.1205, relheight=0.035, anchor='nw')

        self.entry_name = Entry(self,
                                background='#defffc',
                                foreground='#435661',
                                justify='center')
        self.entry_name.place(relx=0.245,
                              rely=0.7662,
                              relwidth=0.5225,
                              relheight=0.035,
                              anchor='nw')

        myButton(self, command=lambda *a: self.confirm(), text='CONFIRM') \
            .place(relx=0.201, rely=0.8575, relwidth=0.6155, relheight=0.0825, anchor='nw')

    def set_bindings(self):
        # self-explanatory
        self.entry_arguments.bind("<Return>", lambda *a: self.set_value())
        self.listbox.bind("<ButtonRelease-1>",
                          lambda *a: self.listbox_clicked())

    def set_spinboxes(self):
        # self-explanatory
        self.spin_relx.delete(0, "end")
        self.spin_rely.delete(0, "end")
        self.spin_relw.delete(0, "end")
        self.spin_relh.delete(0, "end")

        self.spin_relx.insert("end", self.master.fake_frame_place_info["relx"])
        self.spin_rely.insert("end", self.master.fake_frame_place_info["rely"])
        self.spin_relw.insert("end",
                              self.master.fake_frame_place_info["relwidth"])
        self.spin_relh.insert("end",
                              self.master.fake_frame_place_info["relheight"])

        self.spin_relx.configure(state="readonly")
        self.spin_rely.configure(state="readonly")
        self.spin_relw.configure(state="readonly")
        self.spin_relh.configure(state="readonly")

    def mod(self):
        relx = float(self.spin_relx.get())
        rely = float(self.spin_rely.get())
        relw = float(self.spin_relw.get())
        relh = float(self.spin_relh.get())

        x, y = int(relx * self.board_width), int(rely * self.board_height)
        width, height = int(relw * self.board_width), int(relh *
                                                          self.board_height)

        self.board.delete(self.tag)
        self.board.create_rectangle(x,
                                    y,
                                    x + width,
                                    y + height,
                                    width=0,
                                    fill=self.background,
                                    tag=self.tag)

    def set_listbox(self):
        self.listbox.insert("end", "background")
        self.record["background"] = self.master.fake_frame_background

    def listbox_clicked(self):
        # Changes entry_arguments's text and label_arguments's text, sets focus on entry_name
        self.index = self.listbox.curselection()[0]
        parameter = list(self.record.keys())[self.index]
        value = self.record[parameter]
        self.entry_arguments.delete(0, "end")
        self.entry_arguments.insert("end", value)
        self.label_arguments.configure(text=f"{parameter} = {value}")
        self.entry_arguments.focus_set()

    def set_value(self):

        parameter = list(self.record.keys())[self.index]
        value = self.entry_arguments.get()

        try:
            evaluated_value = eval(value)
            self.record[parameter] = evaluated_value
        except:
            evaluated_value = value
            self.record[parameter] = f"{evaluated_value}"

        self.background = evaluated_value
        self.mod()

        self.label_arguments.configure(text=f"{parameter} = {value}")

    def fake_place_info(self):
        relx = float(self.spin_relx.get())
        rely = float(self.spin_rely.get())
        relw = float(self.spin_relw.get())
        relh = float(self.spin_relh.get())
        return {
            "relx": relx,
            "rely": rely,
            "relwidth": relw,
            "relheight": relh,
            "anchor": "nw"
        }

    def confirm(self):
        name = self.entry_name.get().replace(" ", "")
        if name and name not in self.master.record_of_names:
            self.master.record_of_names[name] = Frame(self.board)
            widget_cls = "Frame"

            self.master.writer.define_widget(name, widget_cls,
                                             self.fake_place_info())
            self.master.writer.begin_configure(name)
            for key, value in self.record.items():
                if value:
                    self.master.writer.write_configure(name, key, f"'{value}'")
            self.master.writer.end_configure(name)

            self.destroy()
Пример #23
0
listVarY = StringVar()
listboxY = Listbox(UI,
                   selectmode=MULTIPLE,
                   listvariable=listVarY,
                   exportselection=False)
listVarX = StringVar()
listboxX = Listbox(UI,
                   selectmode=MULTIPLE,
                   listvariable=listVarX,
                   exportselection=False)
label1.pack()
label1.place(x=10, y=10, width=300, height=40)
button1.pack()
button1.place(x=10, y=50, width=300, height=40)
label4.pack()
label4.place(x=10, y=100, width=140, height=40)
label5.pack()
label5.place(x=170, y=100, width=140, height=40)
listboxY.pack()
listboxY.place(x=10, y=150, width=140, height=200)
listboxX.pack()
listboxX.place(x=170, y=150, width=140, height=200)
label2.pack()
label2.place(x=10, y=360, width=300, height=40)
button2.pack()
button2.place(x=10, y=400, width=300, height=40)
button3.pack()
button3.place(x=10, y=450, width=300, height=40)
label6.pack()
label6.place(x=10, y=500, width=300, height=20)
UI.mainloop()
Пример #24
0
class Settings(Frame):
    def __init__(self, master, widget, items, modifying=False):
        super().__init__(master, bg="#435661")

        self.widget = widget
        self.id = id(widget)
        self.modifying = modifying
        self.record = {}
        self.index = 0
        self.standard_params = []
        self.spin_relx = None
        self.spin_rely = None
        self.spin_relw = None
        self.spin_relh = None
        self.label_arguments = None
        self.entry_arguments = None
        self.listbox = None
        self.entry_name = None
        self.set_layout()
        self.set_bindings()
        self.set_listbox(items)
        self.set_spinboxes()

    def set_layout(self):
        # self-explanatory
        Label(self, background='#435661', text='relx:', foreground='#defffc') \
            .place(relx=0.145, rely=0.0125, relwidth=0.1625, relheight=0.025, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='rely:') \
            .place(relx=0.6845, rely=0.0135, relwidth=0.155, relheight=0.0225, anchor='nw')

        Label(self, background='#435661', text='relwidth:', foreground='#defffc') \
            .place(relx=0.044, rely=0.089, relwidth=0.37, relheight=0.02125, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='relheight:') \
            .place(relx=0.667, rely=0.0875, relwidth=0.195, relheight=0.02375, anchor='nw')

        self.spin_relx = Spinbox(self,
                                 readonlybackground='#defffc',
                                 highlightthickness=0,
                                 foreground='#435661',
                                 from_=0,
                                 command=self.mod_relx,
                                 to_=1,
                                 increment=0.001,
                                 justify='center')
        self.spin_relx.place(relx=0.085,
                             rely=0.0425,
                             relwidth=0.295,
                             relheight=0.03375,
                             anchor='nw')

        self.spin_rely = Spinbox(self,
                                 readonlybackground='#defffc',
                                 foreground='#435661',
                                 justify='center',
                                 highlightthickness=0,
                                 command=self.mod_rely,
                                 from_=0,
                                 to_=1,
                                 increment=0.001)
        self.spin_rely.place(relx=0.6135,
                             rely=0.0425,
                             relwidth=0.3005,
                             relheight=0.03375,
                             anchor='nw')

        self.spin_relw = Spinbox(self,
                                 readonlybackground='#defffc',
                                 foreground='#435661',
                                 justify='center',
                                 highlightthickness=0,
                                 command=self.mod_relwidth,
                                 from_=0,
                                 to_=1,
                                 increment=0.001)
        self.spin_relw.place(relx=0.084,
                             rely=0.1175,
                             relwidth=0.295,
                             relheight=0.035,
                             anchor='nw')

        self.spin_relh = Spinbox(self,
                                 readonlybackground='#defffc',
                                 foreground='#435661',
                                 justify='center',
                                 highlightthickness=0,
                                 command=self.mod_relheight,
                                 from_=0,
                                 to_=1,
                                 increment=0.001)
        self.spin_relh.place(relx=0.6115,
                             rely=0.1177,
                             relwidth=0.304,
                             relheight=0.035,
                             anchor='nw')

        self.label_arguments = Label(self,
                                     background='#557282',
                                     foreground='#defffc')
        self.label_arguments.place(relx=0.086,
                                   rely=0.1832,
                                   relwidth=0.8305,
                                   relheight=0.06125,
                                   anchor='nw')

        self.entry_arguments = Entry(self,
                                     background='#defffc',
                                     foreground='#435661',
                                     justify='center')
        self.entry_arguments.place(relx=0.22,
                                   rely=0.2625,
                                   relwidth=0.545,
                                   relheight=0.04375,
                                   anchor='nw')

        self.listbox = Listbox(self,
                               background='#557282',
                               foreground='#defffc',
                               borderwidth=0)
        self.listbox.place(relx=0.085,
                           rely=0.3275,
                           relwidth=0.83,
                           relheight=0.4062,
                           anchor='nw')

        myButton(self, command=lambda *a: self.set_value(), text='OK') \
            .place(relx=0.8245, rely=0.2672, relwidth=0.13, relheight=0.0355, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='Name:', anchor='w') \
            .place(relx=0.083, rely=0.766, relwidth=0.1205, relheight=0.035, anchor='nw')

        self.entry_name = Entry(self,
                                background='#defffc',
                                foreground='#435661',
                                justify='center')
        self.entry_name.place(relx=0.245,
                              rely=0.7662,
                              relwidth=0.5225,
                              relheight=0.035,
                              anchor='nw')

        self.entry_name.bind("<Return>", lambda *a: self.confirm())

        if self.modifying:
            self.entry_name.insert("end", self.master.record_of_ids[self.id])

        myButton(self, command=lambda *a: self.confirm(), text='CONFIRM') \
            .place(relx=0.201, rely=0.8575, relwidth=0.6155, relheight=0.0825, anchor='nw')

    def set_bindings(self):
        # self-explanatory
        self.entry_arguments.bind("<Return>", lambda *a: self.set_value())
        self.listbox.bind("<ButtonRelease-1>",
                          lambda *a: self.listbox_clicked())

        self.master.root.bind("<Left>",
                              lambda event: self.pressed_left_right(-1))
        self.master.root.bind("<Right>",
                              lambda event: self.pressed_left_right(1))

        self.master.root.bind("<Up>", lambda event: self.pressed_up_down(-1))
        self.master.root.bind("<Down>", lambda event: self.pressed_up_down(1))

    def set_spinboxes(self):
        # self-explanatory
        self.spin_relx.delete(0, "end")
        self.spin_rely.delete(0, "end")
        self.spin_relw.delete(0, "end")
        self.spin_relh.delete(0, "end")

        self.spin_relx.insert("end", self.widget.place_info()["relx"])
        self.spin_rely.insert("end", self.widget.place_info()["rely"])
        self.spin_relw.insert("end", self.widget.place_info()["relwidth"])
        self.spin_relh.insert("end", self.widget.place_info()["relheight"])

        self.spin_relx.configure(state="readonly")
        self.spin_rely.configure(state="readonly")
        self.spin_relw.configure(state="readonly")
        self.spin_relh.configure(state="readonly")

    def mod_relx(self):
        # Changes widget's relx parameter accordingly
        value = float(self.spin_relx.get())
        self.widget.place_configure(relx=value)

    def mod_rely(self):
        # Changes widget's rely parameter accordingly
        value = float(self.spin_rely.get())
        self.widget.place_configure(rely=value)

    def mod_relwidth(self):
        # Changes widget's relwidth parameter accordingly
        value = float(self.spin_relw.get())
        self.widget.place_configure(relwidth=value)

    def mod_relheight(self):
        # Changes widget's relheight parameter accordingly
        value = float(self.spin_relh.get())
        self.widget.place_configure(relheight=value)

    def pressed_left_right(self, factor):
        value = float(self.spin_relx.get())
        self.spin_relx.configure(state="normal")
        self.spin_relx.delete(0, "end")
        self.spin_relx.insert("end", value + factor * 0.001)
        self.spin_relx.configure(state="readonly")
        self.widget.place_configure(relx=value + factor * 0.001)

    def pressed_up_down(self, factor):
        value = float(self.spin_rely.get())
        self.spin_rely.configure(state="normal")
        self.spin_rely.delete(0, "end")
        self.spin_rely.insert("end", value + factor * 0.001)
        self.spin_rely.configure(state="readonly")
        self.widget.place_configure(rely=value + factor * 0.001)

    def set_listbox(self, items):
        for item in items:
            self.listbox.insert("end", item)
            parameter = self.widget.cget(item)
            self.record[item] = parameter
            self.standard_params.append(parameter)
        if self.modifying:
            self.standard_params = self.master.writer.standard_params[
                self.widget]
        else:
            self.master.writer.standard_params[
                self.widget] = self.standard_params

    def listbox_clicked(self):
        # Changes entry_arguments's text and label_arguments's text, sets focus on entry_name
        self.index = self.listbox.curselection()[0]
        parameter = list(self.record.keys())[self.index]
        value = self.record[parameter]
        self.entry_arguments.delete(0, "end")
        self.entry_arguments.insert("end", value)
        self.label_arguments.configure(text=f"{parameter} = {value}")
        self.entry_arguments.focus_set()

    def set_value(self):
        # Sets entry_arguments's value as widget's argument, it needs to be evaluated first to avoid errors
        parameter = list(self.record.keys())[self.index]
        value = self.entry_arguments.get()

        try:
            evaluated_value = eval(value)
            self.record[parameter] = evaluated_value
        except:
            evaluated_value = value
            self.record[parameter] = f"{evaluated_value}"

        self.widget.configure({parameter: evaluated_value})

        self.label_arguments.configure(text=f"{parameter} = {value}")

    def confirm(self):
        # Checks if entry_name isn't empty or already used and then sends it to the master.Writer
        # After that it quits with .destroy()
        name = self.entry_name.get().replace(" ", "")
        if not self.modifying:
            if name and name not in self.master.record_of_names:
                self.master.record_of_names[name] = self.widget
                self.master.record_of_ids[self.id] = name
                widget_cls = self.widget.winfo_class()

                self.master.writer.define_widget(name, widget_cls,
                                                 self.widget.place_info())
                self.master.writer.begin_configure(name)
                for j, (key, value) in enumerate(self.record.items()):
                    if value != self.standard_params[j]:
                        self.master.writer.write_configure(
                            name, key, f"'{value}'")
                self.master.writer.end_configure(name)

                self.master.root.unbind("<Down>")
                self.master.root.unbind("<Up>")
                self.master.root.unbind("<Left>")
                self.master.root.unbind("<Right>")

                self.destroy()
        else:
            widget_cls = self.widget.winfo_class()

            self.master.writer.define_widget(name, widget_cls,
                                             self.widget.place_info(), True)
            self.master.writer.begin_configure(name)

            for j, (key, value) in enumerate(self.record.items()):
                if value != self.standard_params[j]:
                    self.master.writer.write_configure(name, key, f"'{value}'")
            self.master.writer.end_configure(name)

            self.master.root.unbind("<Down>")
            self.master.root.unbind("<Up>")
            self.master.root.unbind("<Left>")
            self.master.root.unbind("<Right>")

            self.destroy()
Пример #25
0
               tickinterval=20,
               length=150,
               background='#3C3C3C',
               fg='white',
               activebackground='#3C3C3C',
               command=set_volume1)
volume.place(y=530, x=1)
volume.set(50)
lyrics_indict = Label(root, text='Lyrics', font=('Arial', 20, 'bold'))
lyrics_indict.place(x=200, y=150)
lyrics = Listbox(root,
                 bg='#3C3C3C',
                 width=55,
                 fg='orange',
                 font=('Arial', 12, 'bold'))
lyrics.place(x=1, y=200)
lyrics.insert(0, "blackpink!".upper())
play_list = Listbox(root,
                    width=32,
                    bg="#3C3C3C",
                    fg='cyan',
                    font=('Arial', 12, 'bold'),
                    listvar=song_Data)
play_list.place(x=505, y=60)
play_List_indict = Label(root,
                         text='Playlist - Default',
                         font=('Arial', 20, 'bold'))
play_List_indict.place(x=400, y=10)
add_song = Button(root,
                  text='Add Folder',
                  font=('Arial', 20, 'bold'),
Пример #26
0
class BookManager(Frame):
    # 생성자
    # DB와 연결
    # 라벨과 엔트리 생성
    # UI 초기 설정
    # 윈도우 중앙 위치
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.conn = sqlite3.connect('bookInfo.db')
        self.cur = self.conn.cursor()
        self.parent = parent
        self.nameLabel = StringVar()
        self.authorLabel = StringVar()
        self.priceLabel = StringVar()
        self.infoLabel = StringVar()
        self.nameEntry = ttk.Entry(self)
        self.authorEntry = ttk.Entry(self)
        self.priceEntry = ttk.Entry(self)
        self.initUI()
        self.centerWindow()

    # 윈도우 생성과 위젯에 배치를 담당
    def initUI(self):
        self.parent.title("Book DataBase")
        self.pack(fill=BOTH, expand=1)

        self.lb = Listbox(self, height=15, width=93)
        self.lb.place(x=20, y=100)

        # 라벨을 생성해서 화면에 뿌려줌
        self.createLabel(65, 25, self.nameLabel, '책 이름 : ')
        self.createLabel(65, 45, self.authorLabel, '저     자: ')
        self.createLabel(65, 65, self.priceLabel, '가     격: ')
        # 엔트리를 생성해서 화면에 뿌려줌
        self.createEntry(2, 1, self.nameEntry)
        self.createEntry(3, 1, self.authorEntry)
        self.createEntry(4, 1, self.priceEntry)

        # 버튼 생성과 이벤트 연결
        add = ttk.Button(self, text="ADD", command=lambda: self.addBook())
        add.grid(row=1, column=0, padx=20)
        delete = ttk.Button(self, text="DEL", command=lambda: self.delBook())
        delete.grid(row=1, column=1, padx=20)
        search = ttk.Button(self, text="SEARCH", command=lambda: self.search())
        search.grid(row=1, column=2, padx=20)
        show = ttk.Button(self,
                          text="SHOW",
                          command=lambda: self.showBookInfo())
        show.grid(row=1, column=3, padx=20)

        # 책 정보를 출력
        self.showBookInfo()

    # 전달받은 인자를 통해 적재적소에 라벨 생성
    def createLabel(self, x, y, o, s):
        o.set(s)
        self.label = Label(self, text=0, textvariable=o)
        self.label.place(x=x, y=y)

    # 전달받은 인자를 통해 적재적소에 엔트리 위치
    def createEntry(self, row, col, o):
        o.grid(row=row, column=col, columnspan=4, sticky=W + E)

    # 윈도우 중앙 위치
    def centerWindow(self):
        w = 700
        h = 400

        # screen 크기를 구함
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()

        x = (sw - w) / 2
        y = (sh - h) / 2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))

    # 쿼리 실행 담당
    def execteQuery(self, query):
        self.query = query
        self.cur.execute(query)
        self.conn.commit()

    # 책 정보를 검색한다
    def search(self):
        # 리스트를 모두 지운다
        self.lb.delete(0, END)

        # 이름에 값이 존재할 경우
        if (self.nameEntry.get() != ''):
            # 어느정도만 입력해도 검색할 수 있도록 쿼리문 작성
            self.query = 'select count (*) from book where name like \'%{0}%\''.format(
                self.nameEntry.get())
            self.execteQuery(self.query)
            # 책 정보가 존재하지 않을 경우
            if ('{0}', format(self.cur.fetchone()) == 0):
                self.createLabel(20, 350, self.infoLabel, '해당하는 정보가 존재하지 않습니다')

            # 책 정보가 존재할 때 패턴 정보를 가진 책을 모두 가져옴
            self.query = 'select * from book where name like \'%{0}%\''.format(
                self.nameEntry.get())
            self.execteQuery(self.query)
        # 저자에 값이 존재할 경우
        elif (self.authorEntry.get() != ''):
            # 어느정도만 입력해도 검색할 수 있도록 쿼리문 작성
            self.query = 'select count (*) from book where name like \'%{0}%\''.format(
                self.authorEntry.get())
            self.execteQuery(self.query)
            # 책 정보가 존재하지 않을 경우
            if ('{0}', format(self.cur.fetchone()) == 0):
                self.createLabel(20, 350, self.infoLabel, '해당하는 정보가 존재하지 않습니다')

            # 책 정보가 존재할 때 패턴 정보를 가진 책을 모두 가져옴
            self.query = 'select * from book where author like \'%{0}%\''.format(
                self.authorEntry.get())
            self.execteQuery(self.query)
        # 값이 입력되지 않았을 때
        else:
            self.createLabel(20, 350, self.infoLabel, '정보를 정확히 입력해주세요')
            return

        # 검색된 책 정보를 출력
        for book in self.cur.fetchall():
            print(book)
            s = '책 이름 : {0[0]:30}저    자 : {0[1]:30}가    격 : {0[2]:30}'.format(
                book)
            self.lb.insert(END, s)

    # 모든 책 정보를 출력
    def showBookInfo(self):
        temp = ''

        self.lb.delete(0, END)
        # 모든 정보를 가져오는 쿼리문
        self.query = 'select * from book'
        self.execteQuery(self.query)
        # 책을 제거 했을 때 동일한 정보를 가진 책 정보가 본의 아니게 만들어 져서
        # 임시값을 이용해 같은 정보가 있는지 검사하여 없을 경우 출력
        for book in self.cur.fetchall():
            rec = '책 이름 : {0[0]:30}저    자 : {0[1]:30}가    격 : {0[2]:30}'.format(
                book)
            if (temp == rec):
                continue
            self.lb.insert(END, rec)
            temp = rec

    # 책 정보 추가
    def addBook(self):
        # 책 정보를 입력할 때 책 이름, 저자, 가격 정보가 모두 필요함
        if (self.nameEntry.get() == '' or self.authorEntry.get() == ''
                or self.priceEntry.get() == ''):
            self.createLabel(20, 350, self.infoLabel, '정보를 정확히 입력해주세요')
            return

        # 책 정보를 추가하는 쿼리문
        self.query = 'INSERT INTO book VALUES (\'{0}\', \'{1}\', \'{2}\')'.format(
            self.nameEntry.get(), self.authorEntry.get(),
            self.priceEntry.get())
        self.cur.execute(self.query)
        self.createLabel(20, 350, self.infoLabel, '추가완료')
        self.showBookInfo()
        self.clearEntry()

    # 책 정보 제거
    def delBook(self):
        # 책을 제거할 때 책 이름과 저자정보 모두가 있어야 제거가 가능하도록 구현
        if (self.nameEntry.get() == '' or self.authorEntry.get() == ''):
            self.createLabel(20, 350, self.infoLabel, '정보를 정확히 입력해주세요')
            return

        # 책 정보를 제거하는 쿼리문
        self.query = 'DELETE FROM book WHERE name = \'{0}\' and author = \'{1}\''.format(
            self.nameEntry.get(), self.authorEntry.get())
        self.cur.execute(self.query)
        self.showBookInfo()
        self.createLabel(20, 350, self.infoLabel, '제거완료')
        self.clearEntry()

    # 책 정보가 입력되고 제거되었을 때 다시 입력할 수 있도록 엔트리를 비워준다
    def clearEntry(self):
        self.nameEntry.delete(0)
        self.authorEntry.delete(0)
        self.priceEntry.delete(0)
Пример #27
0
class Project(Thread):
    def __init__(self, gp_root, user, project):
        super(Project, self).__init__()

        # root of GP and the root of the specific object. for doing Top-level
        self.__gp_root = gp_root
        self.__project_root = None

        # useful objects to match the presented window to a specific user and specific project.
        self.__user = user
        self.__project = project
        self.__client_socket = None

        # objects
        self.__chatText = None
        self.__chatEntry = None
        self.__users_list = None

        self.__presented_directories = []

    # responding to user actions.
    def alert(self, message):
        messagebox.showinfo(EMPTY, message)

    # overrides the function 'run' that exists in the threading package.
    def run(self):
        # creating connection with the server and setting up the ssl.
        context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        # try:
        self.__client_socket = create_connection(('127.0.0.1', 1025))
        self.__client_socket = context.wrap_socket(self.__client_socket, server_hostname='127.0.0.1')
        self.__client_socket.write(self.complete_protocol("1", get_user_name(self.__user), EMPTY).encode())
        self.create_window()
        # except:
        # self.controller.alert("there is a problem with1 the servers.\nplease try connecting again in few minutes.")

    # create a new tkinter window for the project.
    def create_window(self):
        # Toplevel means that if the GP window will be closed the project page will be closed to.
        window = Toplevel(self.__gp_root)
        self.__project_root = window
        window.iconbitmap('GP_logo.ico')
        window.geometry('1200x800')
        window.resizable(width=False, height=False)

        window.title_font = tkfont.Font(family=HELVETICA, size=18, weight=BOLD)
        window.cretiria_font = tkfont.Font(family=FIXEDSYS, size=10)

        self.menuBar()

        self.present_project_directories()

        Label(window, text=get_project_name(self.__project), font=window.title_font).pack()

        self.__chatText = tktext.ScrolledText(master=window, wrap=WORD, state=DISABLED, width=45, height=40)
        self.__chatText.place(x=700, y=50)
        self.__chatEntry = Entry(window, width=60)
        self.__chatEntry.place(x=700, y=720)
        self.__users_list = Listbox(self.__project_root, width=15, height=40, selectmode=SINGLE)
        self.__users_list.place(x=1070, y=50)
        self.users_list()
        self.__users_list.bind('<Double-1>', self.open_profile_pages)
        self.chat_history()
        self.__chatEntry.bind('<Return>', self.send_messages)
        GetMessages(self.__client_socket, self.__chatText, self.__project, self).start()
        self.__project_root.protocol("WM_DELETE_WINDOW", self.close_project_page)

    def menuBar(self):
        menu_bar = Menu(self.__project_root)
        # create a pull-down menu, and add it to the menu bar

        project_menu = Menu(menu_bar, tearoff=0)
        project_menu.add_command(label="project information", command=self.delete_directory)
        project_menu.add_separator()
        if get_user_name(self.__user) == get_project_manager(self.__project):
            project_menu.add_command(label="edit project info", command=self.release_directory)
            project_menu.add_separator()
            project_menu.add_command(label="delete project", command=self.delete_directory)
            project_menu.add_separator()

        menu_bar.add_cascade(label="Project", menu=project_menu)

        file_menu = Menu(menu_bar, tearoff=0)
        file_menu.add_command(label="add directory", command=self.add_directory)
        file_menu.add_separator()
        if get_user_name(self.__user) == get_project_manager(self.__project):
            file_menu.add_command(label="release directory", command=self.release_directory)
            file_menu.add_separator()
            file_menu.add_command(label="delete directory", command=self.delete_directory)
            file_menu.add_separator()

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

        if get_user_name(self.__user) == get_project_manager(self.__project):
            users_menu = Menu(menu_bar, tearoff=0)
            users_menu.add_command(label="block user", command=self.release_directory)
            users_menu.add_separator()
            users_menu.add_command(label="fire user", command=self.delete_directory)
            users_menu.add_separator()
            menu_bar.add_cascade(label="Manage Users", menu=users_menu)

        help_menu = Menu(menu_bar, tearoff=0)
        help_menu.add_command(label="About")
        help_menu.add_separator()

        menu_bar.add_cascade(label="Help", menu=help_menu)

        # display the menu
        self.__project_root.config(menu=menu_bar)

    # when clicking a name in user list, open a user page.
    def open_profile_pages(self, event):
        profile_user_username = self.__users_list.get(ACTIVE)
        if profile_user_username not in OPEN_PROFILE_PAGES:
            profile_page = Profile(self.__project_root, self.__user, query_user_by_username(profile_user_username))
            OPEN_PROFILE_PAGES[profile_user_username] = profile_page
            profile_page.start()

    # ----------directories functions
    # adding a new directory for the project.
    def add_directory(self):
        directory_name = askopenfilename(parent=self.__project_root, initialdir="/", title="select a directory",
                                   filetypes=(("python files", "*.py"), ("all types", "*.*")))
        if directory_name is not None and directory_name != '':
            directory = open(directory_name, encoding='latin-1')
            if not add_new_directory(get_project_name(self.__project), directory):
                self.alert("invalid directories names:\n" + str(INVALID_DIRECTORIES_NAMES))
            else:
                message = self.complete_protocol("5", get_user_name(self.__user), EMPTY)
                self.__client_socket.write(message.encode())
                self.present_project_directories()
                self.alert("directory added successfully!")
            directory.close()

    def open_directory(self, directory):
        if not get_directory_isopen(directory):
            set_directory_isopen(directory)
            set_directory_lasteditor(directory, get_user_name(self.__user))
            RunDirectory(get_project_name(self.__project), directory).start()
        else:
            self.alert(IS_OPEN)

    def release_directory(self):
        directories = query_project_directories(get_project_name(self.__project))
        project_open_directories = []
        for directory in directories:
            if get_directory_isopen(directory):
                print("ahahahaha")
                project_open_directories.append(get_directory_name(directory))
        print(project_open_directories)
        if not project_open_directories:
            self.alert(NO_OPEN_DIRECTORIES)
        else:
            directories_list = Listbox(self.__project_root, width=15, height=40, selectmode=SINGLE)
            directories_list.pack()
            for i in range(len(project_open_directories)):
                directories_list.insert(i + 1, project_open_directories[i])
                directories_list.bind('<Double-1>', lambda x: self.release_directory_2(directories_list))
            directories_list.insert(i + 1, "non of the above")
            directories_list.bind('<Double-1>', lambda x: self.release_directory_2(directories_list))

    def release_directory_2(self, object):
        directory_name = object.get(ACTIVE)
        object.destroy()
        project_directories = query_project_directories(get_project_name(self.__project))
        for directory in project_directories:
            if get_directory_name(directory) == directory_name:
                set_directory_isopen(directory)
                break

    def delete_directory(self):
        directory_name = simpledialog.askstring(EMPTY, ENTER_DIRECTORY_NAME)
        if not delete_directory(get_project_name(self.__project), directory_name):
            self.alert("no such directory. check you spelled it correctly!")
        else:
            message = self.complete_protocol("7", get_user_name(self.__user), EMPTY)
            self.__client_socket.write(message.encode())
            self.present_project_directories()
            self.alert("directory deleted successfully!")

    def present_project_directories(self):
        directories = query_project_directories(get_project_name(self.__project))
        if self.__presented_directories:
            for d in self.__presented_directories:
                d.destroy()
            self.__presented_directories = []
        # Creating a photoimage object to use image
        # photo = PhotoImage(file=r"C:\Users\schur\PycharmProjects\GP\file.png")
        # Resizing image to fit on button
        # photo_image = photo.subsample(2, 2)
        num = 0
        num_y = 100
        for d in directories:
            # compound- align the image to a side of the button. (((, image=photo_image, compound=TOP,)))
            p = Button(self.__project_root, text=get_directory_name(d),
                       command=lambda directory=d: self.open_directory(directory))
            p.place(x=50 + 200*num, y=num_y)
            self.__presented_directories.append(p)
            num = num + 1
            if num == 3:
                num = 0
                num_y = num_y + 200

    def users_list(self):
        users_names = get_project_users(self.__project).split(INVALID_CHAR1)
        for i in range(len(users_names)):
            self.__users_list.insert(i+1, users_names[i])

    # writing all the chats history in the chatText object.
    def chat_history(self):
        if get_project_messages(self.__project) != EMPTY:
            messages = get_project_messages(self.__project).split(INVALID_CHAR1)
            messages.pop(-1)
            self.__chatText.config(state=NORMAL)
            for i in messages:
                message = self.split_old_message(i)
                self.__chatText.insert(END, message + '\n\n')
                self.__chatText.yview(END)
            self.__chatText.config(state=DISABLED)

    def split_old_message(self, message):
        t = message[0]
        u_len = int(message[1])
        time = message[2:8]
        username = message[8:u_len+8]
        useful_part = message[u_len+8:u_len+10]
        message = message[u_len+10:]
        if not username == get_user_name(self.__user):
            return time + username + useful_part + message
        return time + message

    def send_messages(self, event):
        message = self.__chatEntry.get()
        # --------------------------------------- check why I need it...
        if message == EMPTY:
            pass
        elif not message.find(INVALID_CHAR1) == -1:
            self.alert(TRY_USE_IN_CHAR)
        else:
            self.write_message(self.add_time() + SPACE + message)
            message = self.complete_protocol("2", get_user_name(self.__user), message)
            self.__client_socket.write(message.encode())

    def add_time(self):
        time = datetime.datetime.now()
        hour = str(time.hour)
        if len(hour) == 1:
            hour = "0" + hour
        minute = str(time.minute)
        if len(minute) == 1:
            minute = "0" + minute
        return hour + ":" + minute

    def complete_protocol(self, message_type, username, message):
        project_name = get_project_name(self.__project)
        project_name_len = str(len(project_name))
        while len(project_name_len) != 2:
            project_name_len = "0" + project_name_len
        u_len = str(len(username))
        final_message = message_type + project_name_len + project_name + u_len + self.add_time() + username + message
        return final_message

    def write_message(self, message):
        self.__chatText.config(state=NORMAL)
        self.__chatText.insert(END, message + '\n\n')
        self.__chatText.yview(END)
        self.__chatText.config(state=DISABLED)
        self.__chatEntry.delete(0, 'end')

    def close_project_page(self):
        del constants.OPEN_PROJECTS[get_project_name(self.__project)]
        message = self.complete_protocol("9", get_user_name(self.__user), EMPTY)
        self.__client_socket.write(message.encode())
        self.__client_socket.close()
        self.__project_root.destroy()
Пример #28
0
class AutocompleteEntry(Entry):
    def __init__(self, parent, autocompleteList, *args, **kwargs):
        self.parent = parent
        # Listbox length
        if 'listboxLength' in kwargs:
            self.listboxLength = kwargs['listboxLength']
            del kwargs['listboxLength']
        else:
            self.listboxLength = 8

        if 'window_frame' in kwargs:
            self.window_frame = kwargs['window_frame']
            del kwargs['window_frame']
        else:
            self.window_frame = tk.Tk()

        # Custom matches function
        if 'matchesFunction' in kwargs:
            self.matchesFunction = kwargs['matchesFunction']
            del kwargs['matchesFunction']
        else:

            def matches(fieldValue, acListEntry):
                pattern = re.compile('.*' + re.escape(fieldValue) + '.*',
                                     re.IGNORECASE)
                return re.match(pattern, acListEntry)

            self.matchesFunction = matches

        Entry.__init__(self, master=parent, *args, **kwargs)
        self.focus()

        self.autocompleteList = autocompleteList

        self.var = self["textvariable"]
        if self.var == '':
            self.var = self["textvariable"] = StringVar()

        self.var.trace('w', self.changed)
        self.bind("<Right>", self.selection)
        self.bind("<Up>", self.moveUp)
        self.bind("<Down>", self.moveDown)

        self.listboxUp = False

    def changed(self, name, index, mode):
        if self.var.get() == '':
            if self.listboxUp:
                self.listbox.destroy()
                self.listboxUp = False
        else:
            words = self.comparison()
            if words:
                if not self.listboxUp:
                    self.listbox = Listbox(master=self.window_frame,
                                           width=self["width"],
                                           height=self.listboxLength)
                    self.listbox.bind("<Button-1>", self.selection)
                    self.listbox.bind("<Right>", self.selection)
                    self.listbox.place(x=self.winfo_x(),
                                       y=self.winfo_y() + self.winfo_height())
                    self.listboxUp = True

                self.listbox.delete(0, tk.END)
                for w in words:
                    self.listbox.insert(tk.END, w)
            else:
                if self.listboxUp:
                    self.listbox.destroy()
                    self.listboxUp = False

    def selection(self, event):
        if self.listboxUp:
            self.var.set(self.listbox.get(tk.ACTIVE))
            self.listbox.destroy()
            self.listboxUp = False
            self.icursor(tk.END)

    def moveUp(self, event):
        if self.listboxUp:
            if self.listbox.curselection() == ():
                index = '0'
            else:
                index = self.listbox.curselection()[0]

            if index != '0':
                self.listbox.selection_clear(first=index)
                index = str(int(index) - 1)

                self.listbox.see(index)  # Scroll!
                self.listbox.selection_set(first=index)
                self.listbox.activate(index)

    def moveDown(self, event):
        if self.listboxUp:
            if self.listbox.curselection() == ():
                index = '0'
            else:
                index = self.listbox.curselection()[0]

            if index != tk.END:
                self.listbox.selection_clear(first=index)
                index = str(int(index) + 1)

                self.listbox.see(index)  # Scroll!
                self.listbox.selection_set(first=index)
                self.listbox.activate(index)

    def comparison(self):
        return [
            w for w in self.autocompleteList
            if self.matchesFunction(self.var.get(), w)
        ]
Пример #29
0
class AutocompleteEntry(Entry):

    def __init__(self, *args, **kwargs):
        Entry.__init__(self, width=100, *args, **kwargs)

        self.focus_set()
        self.pack()

        self.var = self["textvariable"]
        if self.var == '':
            self.var = self["textvariable"] = StringVar()

        self.var.trace('w', self.changed)
        self.bind("<Right>", self.selection)
        self.bind("<Up>", self.up)
        self.bind("<Down>", self.down)
        self.bind("<Return>", self.enter)
        self.lb_up = False
        self.lb = None

    def enter(self, event):
        print(event)

    def changed(self, name, index, mode):

        if self.var.get() == '':
            if self.lb:
                self.lb.destroy()
            self.lb_up = False
        else:
            words = self.comparison()
            if words:
                if not self.lb_up:
                    self.lb = Listbox(master=root, width=100)

                    self.lb.bind("<Double-Button-1>", self.selection)
                    self.lb.bind("<Right>", self.selection)
                    self.lb.place(x=self.winfo_x(), y=self.winfo_y()+self.winfo_height())
                    self.lb_up = True

                self.lb.delete(0, END)
                for w in words:
                    self.lb.insert(END,w)
            else:
                if self.lb_up:
                    self.lb.destroy()
                    self.lb_up = False

    def selection(self, _):

        if self.lb_up:
            self.var.set(self.lb.get(ACTIVE))
            self.lb.destroy()
            self.lb_up = False
            self.icursor(END)

    def up(self, _):

        if self.lb_up:
            if self.lb.curselection() == ():
                index = '0'
            else:
                index = self.lb.curselection()[0]
            if index != '0':
                self.lb.selection_clear(first=index)
                index = str(int(index)-1)
                self.lb.selection_set(first=index)
                self.lb.activate(index)

    def down(self, _):

        if self.lb_up:
            if self.lb.curselection() == ():
                index = '0'
            else:
                index = self.lb.curselection()[0]
            if index != END:
                self.lb.selection_clear(first=index)
                index = str(int(index)+1)
                self.lb.selection_set(first=index)
                self.lb.activate(index)

    def comparison(self):
        q = self.var.get()
        q = str(q.decode('utf8'))
        for hit in searcher.search(qp.parse(q), limit=50):
            if hit['author']:
                yield '%s. "%s"' % (hit['author'], hit['title'])
            else:
                yield hit['title']
Пример #30
0
class Editor(ttk.Notebook):
    COR_FUNDO = '#282a36'
    COR_FRENTE = '#ffffdd'

    def __init__(self, parent):
        self.parent = parent
        ttk.Notebook.__init__(self, master=self.parent)
        self.pack(expand=True, fill='both')
        self.bind('<Button><3>', self.criaMenuFlutuante)
        self.fonte = font.Font(family='Consolas',
                               size=12,
                               weight='normal',
                               slant='roman')
        self.criaAbas()
        self.rolagemHorizontal()

    # // cria o menu flutuante com o widget listbox...

    def criaMenuFlutuante(self, e):
        opcoes = [
            f'Fechar aba atual {" "*14} Ctrl+W',
            f'Selecionar todo o texto{" "*3} Ctrl+A', f'colar{" "*35} Ctrl+V',
            f'copiar{" "*33} Ctrl+C', f'recortar{" "*30} Ctrl+X'
        ]
        self.menuFlutuante = Listbox(self,
                                     width=30,
                                     height=5,
                                     bg=self.COR_FUNDO,
                                     fg=self.COR_FRENTE)
        for x in range(len(opcoes)):
            self.menuFlutuante.insert(x, opcoes[x])
        self.menuFlutuante.place(x=e.x, y=e.y)
        self.menuFlutuante.bind('<Leave>', self.fechaMenuFlutuante)
        self.menuFlutuante.bind('<<ListboxSelect>>', self.menuFlutuanteSelecao)

    # identifica o elemento clicado no menu flutuante
    # e age de acordo com a selecao

    def menuFlutuanteSelecao(self, e=None):
        item = self.menuFlutuante.curselection()[0]
        print(item)
        if item == 0:
            aba = self.index('current')
            self.forget(aba)
        elif item == 1:
            self.selecionarTudo()
        elif item == 2:
            self.colar()
        elif item == 3:
            self.copiar()

    def copiar(self, e=None):
        self.texto.tag_delete('sels')
        texto = self.texto.get(1.0, 'end-1c')
        self.clipboard_clear()
        self.clipboard_append(texto)

    def colar(self):
        self.texto.insert('insert', self.clipboard_get())
        self.texto.tag_delete('sels')

    def recortar(self):
        texto = self.texto.get('1.0', 'end-1c')
        self.texto.delete('1.0', 'end')
        self.clipboard_append(texto)
        self.texto.tag_delete('sels')

    # fecha o menu flutuante quando mouse sai...

    def fechaMenuFlutuante(self, e):
        self.menuFlutuante.destroy()

    # cria as novas abas ao clica no menu ou ctrl+n...

    def criaAbas(self):
        self.frame = Frame(self, bg=self.COR_FUNDO)
        self.contaLinha = Text(self.frame,
                               width=5,
                               bd=0,
                               relief='flat',
                               font=self.fonte,
                               bg=self.COR_FUNDO,
                               fg=self.COR_FRENTE)
        self.contaLinha.bind('<MouseWheel>', self.naoRolar)
        self.frame.pack(fill='both', expand=True)
        self.contaLinha.pack(side='left', anchor='w', fill='y')
        self.texto = Text(self.frame,
                          bd=0,
                          relief='flat',
                          font=self.fonte,
                          bg=self.COR_FUNDO,
                          fg=self.COR_FRENTE,
                          insertbackground='#fff',
                          wrap='none')
        self.texto.focus_force()
        self.add(self.frame, text='aba')
        self.texto.pack(fill='both', side='left', expand=True)
        self.texto.bind('<KeyPress>', self.insereLinhas)
        self.texto.bind('<Tab>', self.espacosTab)
        self.texto.bind('<MouseWheel>', self.detectaRolagem)
        self.texto.bind('<Button><3>', self.criaMenuFlutuante)
        self.texto.bind('<Control_L><w>', self.fechaAba)

    # fecha aba atual com ctrl+w

    def fechaAba(self, e=None):
        aba = self.index('current')
        self.forget(aba)

    def selecionarTudo(self):
        self.texto.tag_add('sels', '1.0', 'end-1c')
        self.texto.tag_config('sels', background='blue')
        self.texto.mark_set('insert', '1.0')
        self.texto.see('insert')
        return 'break'

    # insere as linhas na lateral esquerda...

    def insereLinhas(self, e):
        self.tecla = e.char
        self.autoPar()
        if self.tecla in ['\'', '\"', '(', '{', '[']:
            return 'break'
        self.linhaAtual = float(self.texto.index('end-1c'))
        self.contaLinha.insert(self.linhaAtual + 1,
                               str(int(self.linhaAtual)) + '\n')
        self.deletaLinhas()
        self.texto.tag_delete('sels')

    # deleta as linhas sobresalentes....

    def deletaLinhas(self):
        self.contaLinha.delete(float(self.texto.index('end')), 'insert')
        self.contaLinha.see(float(self.texto.index('insert')) - 1)

    # transforma os TAB´s em 4 espaços...

    def espacosTab(self, e):
        self.texto.insert(self.texto.index('end-1c'), f'{" "*4}')
        return 'break'

    # autocompleta pares de delimitadores

    def autoPar(self):
        tam = self.texto.index('end-1c')
        i = tam.index('.')
        tam = tam[i + 1:]
        pares = ['\'', '\"', '(', '{', '[']
        fechaPares = ['\'', '\"', ')', '}', ']']
        if self.tecla in pares:
            par = pares.index(self.tecla)
        else:
            return
        if len(tam) == 1:
            indice = '%.1f' % (float(self.texto.index('insert')))
        elif len(tam) == 2:
            indice = '%.2f' % (float(self.texto.index('insert')))
        elif len(tam) == 3:
            indice = '%.3f' % (float(self.texto.index('insert')))
        self.texto.mark_set('insert', indice)
        print(indice)
        self.texto.insert(indice, pares[par] + fechaPares[par])

    # detecta a rolagem da area de texto e indica
    # a mesma para o contador de linhas para rolar junto

    def detectaRolagem(self, e):
        self.contaLinha.yview_scroll(int(-1 * (e.delta / 120)), 'units')
        print(int(-1 * (e.delta)))

    # detecta se o comprimento da linha ja atingiu o maximo da lagura da
    # tela e rola automaticamente na horizontal

    def rolagemHorizontal(self):
        self.rolagem = Scrollbar(self.texto, orient='horizontal')
        self.rolagem.pack(side='bottom', fill='x')
        self.rolagem.configure(command=self.texto.xview)
        self.texto.configure(xscrollcommand=self.rolagem.set)

    # impede a rolagem do contador de linhas ao receber um
    # evento de entrada e rolagem do mouse

    def naoRolar(self, e):
        return 'break'
Пример #31
0
class AutoCompleteEntry(Entry): # pylint: disable=too-many-ancestors
    """
    An entry widget with asdf.
    """
    def __init__(self, autocomplete_list, *args, **kwargs):
        self.autocomplete_list = autocomplete_list
        self.list_box_length = kwargs.pop('list_box_length', 8)
        self.matches_function = kwargs.pop('matches_function',
                                           self._default_match)

        # function to initate_string_var_no_textvariable
        self.textvariable = kwargs.get('textvariable', StringVar())
        self.list_box = None
        super().__init__(*args, **kwargs)
        self.config(textvariable=self.textvariable)
        self.focus()

        self.textvariable.trace('w', self._changed)

    @property
    def existing_list_box(self):
        """
        Check if this instance has its' listbox defined/open.
        """
        return self.__dict__.get('list_box', False)

    @staticmethod
    def _default_match(query, list_entry):
        """
        The default match function if none is given during instantiation.
        """
        pattern = re.compile(re.escape(query) + '.*', re.IGNORECASE)
        return re.match(pattern, list_entry)

    def _changed(self, name, index, mode):
        """
        Event handler for changes to entry.
        """
        print("in _changed")
        print(name, index, mode)

        if self.textvariable.get():  # not empty string
            words = self.__comparison()

            if not words:
                return self.__delete_existing_list_box()

            if not self.existing_list_box:
                self.list_box = Listbox(width=self["width"],
                                        height=self.list_box_length)
                # looks hacky
                self.list_box.place(
                    x=self.winfo_x(), y=self.winfo_y() + self.winfo_height())
                self.list_box.delete(0, END)
                for word in words:
                    self.list_box.insert(END, word)
        else:
            self.__delete_existing_list_box()

    def __delete_existing_list_box(self):
        """
        Deletes open listbox.
        """
        if self.existing_list_box:
            self.list_box.destroy()

    # hmmmm
    def __comparison(self):
        """
        Finds words similar to query. TODO
        """
        if len(self.get()) < 3:
            return []
        ans = [w for w in self.autocomplete_list if
               self.matches_function(self.textvariable.get(), w)]
        print(ans)
        return ans[:5]
Пример #32
0
t = Label(init_window, text="波特率")
t.place(x=15, y=60)

text_baud = Text(init_window, width=10, height=1)  # 波特率设置
text_baud.place(x=15, y=60 + 30)
text_baud.insert(END, '115200')

b1 = Button(init_window, text='串口', width=10, height=1, command=print_selection)
b1.place(x=15, y=60 + 30 + 30)  # 60
# b1.grid(row=1, column=2)

var2 = StringVar()
var2.set(tuple(serial_com))
lis = Listbox(init_window, width=10, height=5, listvariable=var2)  # 显示串口
lis.place(x=15, y=160)  # 95
print("chuangk", serial_com)
val_com = 'COM9'

b3 = Button(init_window, text="刷新串口", width=9, height=1, command=freshen)
b3.place(x=15, y=160 + 100)  # 200

rbtn_lab = Label(init_window, bg='yellow', width=10, text='empty')
rbtn_lab.place(x=15, y=260 + 30)

rbtn_var = StringVar()  # 定义一个var用来将radiobutton的值和Label的值联系在一起.
rbtn_var.set('output_str')  # # 如果1,那么儒家被默认选中
rbtn = Radiobutton(init_window, text='字符输出', variable=rbtn_var, value='output_str', command=print_btn_selection)
rbtn.place(x=15, y=290 + 30)
rbtn = Radiobutton(init_window, text='hex输出', variable=rbtn_var, value='output_hex', command=print_btn_selection)
rbtn.place(x=15, y=320 + 30)
Пример #33
0
class LoggedUI:
    def __init__(self, master, user_name):
        self.master = master
        self.user_name = user_name
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if server_connection:
            try:
                self.client.connect(ADDR)
            except socket.error as ConnectionAbortedError:
                self.master.quit()
                self.connection_info = messagebox.showerror(title='Connection Error',
                                                            message=f'{ConnectionAbortedError}')

        master.title("Password Master")
        master.geometry('1280x720')
        master.resizable(0, 0)
        self.background = PhotoImage(file='Images/background.png')
        self.background_label = Label(master, image=self.background).pack()

        self.user_account_label = Label(master, text='Logged in: {}'.format(user_name), font=LABEL_FONT).place(x=100,
                                                                                                               y=100)
        self.user_pass_label = Label(master, text='Passwords: ', font=LABEL_FONT).place(x=100, y=150)

        # Adding passwords
        self.user_add_passw_label = Label(master, text='Password Name         Password', font=LABEL_FONT).place(x=772,
                                                                                                                y=150)
        self.user_pass_name_entry = Entry(master, width=12, font=ENTRY_FONT)
        self.user_pass_name_entry.place(x=780, y=230)
        self.user_password_entry = Entry(master, width=12, font=ENTRY_FONT)
        self.user_password_entry.place(x=1000, y=230)
        self.submit_button = Button(master, text="Add Password", height=BUTTON_HEIGHT,
                                    width=BUTTON_WIDTH, font=BUTTON_FONT, command=self.add_password).place(x=1045,
                                                                                                           y=300)

        # Deleting Passwords
        self.user_add_passw_label = Label(master, text='ID of Password', font=LABEL_FONT).place(x=982, y=420)
        self.pass_id_entry = Entry(master, width=12, font=ENTRY_FONT)
        self.pass_id_entry.place(x=1000, y=500)
        self.delete_button = Button(master, text="Delete", height=BUTTON_HEIGHT,
                                    width=BUTTON_WIDTH, font=BUTTON_FONT, command=self.delete_password).place(x=1045,
                                                                                                              y=550)

        # Logut button
        self.submit_button = Button(master, text="Log out", height=BUTTON_HEIGHT,
                                    width=BUTTON_WIDTH, font=BUTTON_FONT, command=self.logout).place(x=50, y=625)

        self.testt = '1 Netflix xsd@xd# \n 2 Email xsddasd23sda '
        # Password holder
        self.show_password_button = Button(master, text="Show Passwords", height=BUTTON_HEIGHT,
                                           width=13, font=BUTTON_FONT, command=self.display_passwords).place(x=350,
                                                                                                             y=625)
        self.pass_list = Listbox(self.master, width=75, height=22)
        self.pass_list.place(x=100, y=220)

    def logout(self):
        self.send_request('Q')
        self.master.destroy()

    def delete_password(self):
        pass_id = self.pass_id_entry.get()
        pass_request = 'D' + ';' + self.user_name + ';' + pass_id
        self.send_request(pass_request)
        server_response = self.client.recv(HEADER).decode(FORMAT)
        if int(server_response):
            messagebox.showinfo(message='Password Deleted!')
            self.display_passwords()
        else:
            messagebox.showerror(title='Invalid Input!', message='Index of pass does not exist')

    def add_password(self):
        password_name = self.user_pass_name_entry.get()
        password = self.user_password_entry.get()
        password_data = 'A' + ';' + self.user_name + ';' + password_name + ';' + password
        self.send_request(password_data)
        server_response = self.client.recv(HEADER).decode(FORMAT)
        if int(server_response):
            messagebox.showinfo(message='Password Added!')
            self.display_passwords()
        else:
            messagebox.showerror(message='Failed when inserting the password')

    def display_passwords(self):
        self.send_request(f'S;{self.user_name}')
        final = []
        counter = 0
        row = []
        string_data = self.client.recv(HEADER).decode(FORMAT)
        data_separeted = string_data.split(';')
        self.pass_list.delete(0, END)
        for i in range(len(data_separeted) - 1):
            if counter < 3:
                row.append(data_separeted[i])
                counter += 1
            if counter == 3:
                final.append(row)
                row = []
                counter = 0
        for i in range(len(final)):
            self.pass_list.insert(END, final[i])

    def send_request(self, request):
        request = request.encode(FORMAT)
        self.client.send(request)
Пример #34
0
class CompilationScreen(TkPage):
    Name = 'Compilation'
    Font = lambda Size: ('Courier', Size) #font of the page

    def __init__(self, Parent, *args, **kwargs):
        super().__init__() #constructor of super class
        self.Songs = [Song for Song in DirList('Songs') if Song.endswith('.mid')] #mappable songs
        self.MappedSongs = [Song for Song in DirList('MappedSongs') if Song.endswith('.cmid')] #mapped and compiled song

        TopLabel = Label(self, text = 'Compile a Song', font= CompilationScreen.Font(24), bd = 10) #top label with a title for the page
        TopLabel.place(anchor= 'n', relx= 0.5, rely = 0.015, relwidth = 1, relheight=0.15) #placing the label

        self.ItemList = ListBox(self) #item list of the song
        for Index, Item in enumerate(self.Songs): #for loop for every compiled comiled song
            self.ItemList.insert(Index, Item) #indexing the song in the list
            self.ItemList.itemconfig(Index, {'bg' : '#C2C2C2'})
        self.ItemList.place(anchor= 'n', relx= 0.5, rely = 0.19, relwidth = 1, relheight = 0.46) #placing the item list

        self.ApproxValue = IntVar()
        self.ApproxValue.set(1)
        self.SingleTracks = IntVar()
        self.SingleTracks.set(0)

        self.Closest = Radio(self, text = 'Closest Approximation (A# = A, A- = A)', variable = self.ApproxValue, value = 1)
        self.Closest.place(anchor = 'nw', relx = 0.008, rely = 0.65, relheight = 0.07, relwidth = 0.6)
        self.Upper = Radio(self, text = 'Upper Approximation (A# = B, A- = A)', variable = self.ApproxValue, value = 0)
        self.Upper.place(anchor = 'nw', relx = 0.008, rely = 0.71, relheight = 0.07, relwidth = 0.6)
        self.Split = Check(self, text = 'Split MIDI into single tracks', variable = self.SingleTracks, onvalue = 1, offvalue = 0)
        self.Split.place(anchor = 'nw', relx = 0.008, rely = 0.77, relheight = 0.07, relwidth = 0.6)

        self.Compilation = Button\
        (
            self,
            text = 'Compile selected song',
            command = lambda : self.CompileSong()
        )
        self.Compilation.place(anchor = 'nw', relx = 0.615, rely = 0.66, relheight = 0.17, relwidth = 0.38)

        self.Back = Button\
        (
            self,
            text = 'Back to Home',
            command = lambda : self.TurnBack()
        )
        self.Back.place(anchor = 'nw', relx = 0.008, rely = 0.84, relheight = 0.07, relwidth = 0.988)

    def CompileSong(self):
        Song = str(self.ItemList.get('active'))
        Approximation = bool(self.ApproxValue.get())
        SplitMIDI = bool(self.SingleTracks.get())

        if Approximation:
            print('closest approximation')
            Compile(Song, True, False, SplitMIDI)
        else:
            print('upper approximation')
            Compile(Song, False, True, SplitMIDI)

    def TurnBack(self):
        GenshinLyrePlayer.Raise(Home.Name)

    def Refresh(self): #this function update the song list
        self.Songs = [Song for Song in DirList('Songs') if Song.endswith('.mid')] #check the folder for the songs
        self.ItemList.delete('0','end') #delete every item of the list
        for Index, Item in enumerate(self.Songs): #loop for every song in the folder
            self.ItemList.insert(Index, Item) #index the song in the item list
            self.ItemList.itemconfig(Index, {'bg' : '#C2C2C2'}) #background of the itemlist