Пример #1
0
    def test_dateentry_get_set(self):
        widget = DateEntry(self.window, width=12, background='darkblue',
                           locale='en_US', foreground='white', borderwidth=2,
                           font='Arial 9', year=2019, month=7, day=3)
        widget.pack()
        self.window.update()

        keys = ['exportselection',
                'invalidcommand',
                'justify',
                'show',
                'cursor',
                'calendar_cursor',
                'style',
                'state',
                'takefocus',
                'textvariable',
                'validate',
                'validatecommand',
                'width',
                'xscrollcommand']
        keys.extend(widget._calendar.keys())
        self.assertEqual(sorted(list(set(keys))), sorted(widget.keys()))

        self.assertEqual(widget["background"], 'darkblue')
        self.assertEqual(widget.cget("width"), 12)

        widget["borderwidth"] = 5
        self.window.update()
        self.assertEqual(widget["borderwidth"], 5)

        widget.configure({'foreground': 'cyan', 'font': 'FreeMono 10',
                          'background': 'green'},
                         background="blue", borderwidth=4,
                         font="Arial 20 bold", justify='center')
        self.window.update()
        self.assertEqual(widget["foreground"], "cyan")
        self.assertEqual(widget["background"], "blue")
        self.assertEqual(widget["borderwidth"], 4)
        self.assertEqual(widget["font"], "Arial 20 bold")
        self.assertEqual(widget["justify"], "center")

        widget.config(font="Arial 20 bold")
        self.window.update()
        self.assertEqual(widget["font"], "Arial 20 bold")

        widget.config(style="my.TEntry")
        self.window.update()
        self.assertEqual(widget["style"], "my.TEntry")

        style = ttk.Style(self.window)
        style.theme_use('clam')

        self.assertEqual(widget["locale"], "en_US")
        self.assertEqual(widget.get(), '7/3/19')
        widget.config(locale="fr_FR")
        self.window.update()
        self.assertEqual(widget["locale"], "fr_FR")
        self.assertEqual(widget.get(), '03/07/2019')
Пример #2
0
    def test_dateentry_allow_empty(self):
        widget = DateEntry(self.window, allow_empty=True)
        widget.pack()
        self.window.update()

        self.assertTrue(widget._allow_empty)
        self.assertEqual(widget.get(), '')  # should start with no value
        widget.focus_set()
        self.window.focus_set()
        self.assertEqual(widget.get(), '')  # should not populate with a value
        
        self.assertRaises(IndexError, widget.get_date)
        self.assertRaises(ValueError, widget.set_date, '')
Пример #3
0
def create_task_view(tk):
    clear_view(tk)
    Label(tk, text="Enter your task name: ").grid(row=0,
                                                  column=0,
                                                  padx=20,
                                                  pady=20)
    name = Entry(tk)
    name.grid(row=0, column=1, padx=20, pady=20)
    Label(tk, text="Due date: ").grid(row=1, column=0, padx=20, pady=20)
    date = DateEntry(tk)
    date.grid(row=1, column=1, padx=20, pady=20)
    Label(tk, text="Description: ").grid(row=2, column=0, padx=20, pady=20)
    description = ScrolledText(tk, width=20, height=10)
    description.grid(row=2, column=1, padx=20, pady=20)
    Label(tk, text="Select priority: ").grid(row=3, column=0, padx=20, pady=20)
    selected = IntVar()
    rad1 = Radiobutton(tk, text='Low', value=1, variable=selected)
    rad2 = Radiobutton(tk, text='Medium', value=2, variable=selected)
    rad3 = Radiobutton(tk, text='High', value=3, variable=selected)
    rad1.grid(column=1, row=3)
    rad2.grid(column=2, row=3)
    rad3.grid(column=3, row=3)
    Label(tk, text="Check if completed: ").grid(row=4,
                                                column=0,
                                                padx=20,
                                                pady=20)
    chk_state = BooleanVar()
    chk_state.set(False)  # set check state
    chk = Checkbutton(tk, text='Choose', var=chk_state)
    chk.grid(column=1, row=4)
    all_fields = [name, date, description, selected, chk_state]
    Button(
        tk,
        text="Create new task",
        bg="green",
        fg="white",
        command=lambda: create_task(name.get(), date.get(
        ), description.get("1.0", END), selected.get(), chk_state.get())).grid(
            row=5, column=0)
    Button(tk,
           text="Cancel",
           bg="black",
           fg="white",
           command=lambda: main_view(tk)).grid(row=5,
                                               column=1,
                                               padx=100,
                                               pady=100)
Пример #4
0
def render_create_task_view(tk):
    clear_view(tk)
    Label(tk, text='Enter your task name:').grid(row=0,
                                                 column=0,
                                                 padx=20,
                                                 pady=20)
    task_name = Entry(tk)
    task_name.grid(row=0, column=1, padx=20, pady=20)
    Label(tk, text='Due date:').grid(row=1, column=0, padx=20, pady=20)
    date = DateEntry(tk)
    date.grid(row=1, column=1)
    Label(tk, text='Description').grid(row=2, column=0, padx=20, pady=20)
    description = ScrolledText(tk, width=50, height=10)
    description.grid(row=2, column=1, padx=20, pady=20)
    Label(tk, text='Select priority:').grid(row=3, column=0, padx=20, pady=20)
    selected_priority = IntVar()
    Radiobutton(tk, text='Low', value=1,
                variable=selected_priority).grid(row=3,
                                                 column=1,
                                                 padx=20,
                                                 pady=20)
    Radiobutton(tk, text='Medium', value=2,
                variable=selected_priority).grid(row=3,
                                                 column=2,
                                                 padx=20,
                                                 pady=20)
    Radiobutton(tk, text='High', value=3,
                variable=selected_priority).grid(row=3,
                                                 column=3,
                                                 padx=20,
                                                 pady=20)
    Label(tk, text='Is completed?').grid(row=4, column=0, padx=20, pady=20)
    is_completed = BooleanVar()
    Checkbutton(tk, text='Check', variable=is_completed).grid(row=4,
                                                              column=1,
                                                              padx=20,
                                                              pady=20)
    Button(tk,
           text='Create task',
           bg='green',
           fg='white',
           command=lambda: create_task(name=task_name.get(),
                                       date=date.get(),
                                       description=description.get('1.0', END),
                                       priority=selected_priority.get(),
                                       is_completed=is_completed.get())).grid(
                                           row=5, column=0, padx=20, pady=80)
Пример #5
0
def make_appointment_page_date(frame, nextframe, nextframe2, nextframe3,
                               backframe):
    """
    Asks user to enter details for a new appointment. Once entered, asks user to
    select an available doctor and submit.
    :param frame: current frame
    :param nextframe: next frame - choose preferred doctor
    :param nextframe2: frame for checking details of appointment
    :param nextframe3: frame for confirmation of appointment
    :param backframe: main menu
    """
    tk.Label(frame, text="Please choose a date.").pack()
    cal = DateEntry(frame,
                    locale="en_UK",
                    date_pattern="dd/mm/yyyy",
                    showweeknumbers=False,
                    font="Arial 10",
                    width=12,
                    background='grey',
                    foreground='white',
                    borderwidth=2,
                    mindate=date.today(),
                    maxdate=date.today() + timedelta(365 / 12))
    cal.pack(padx=10, pady=10)
    tk.Label(frame, text="Choose appointment time.").pack()
    time_slots = []
    create_time_slots(time_slots)
    default_text = tk.StringVar(frame)
    default_text.set("Select time:")
    app_time = tk.OptionMenu(frame,
                             default_text,
                             *time_slots,
                             command=print_my_var)
    app_time.pack()
    tk.Button(frame,
              text="Submit",
              command=lambda: [
                  get_app_details(cal.get(), "", drop_down_time),
                  preferred_doctor(nextframe, nextframe2, nextframe3, frame,
                                   backframe),
                  raise_frame(nextframe)
              ]).pack()

    tk.Button(frame,
              text="Go back to main menu",
              command=lambda: raise_frame(backframe)).pack()
Пример #6
0
    def test_dateentry_functions(self):
        widget = DateEntry(self.window,
                           width=12,
                           background='darkblue',
                           foreground='white',
                           borderwidth=2)
        widget.pack()
        self.window.update()

        widget.set_date(format_date(date(2018, 12, 31), 'short'))
        self.assertEqual(widget.get_date(), date(2018, 12, 31))
        with self.assertRaises(ValueError):
            widget.set_date("ab")
        widget.set_date(date(2015, 12, 31))
        self.assertEqual(widget.get_date(), date(2015, 12, 31))
        self.assertEqual(widget.get(), format_date(date(2015, 12, 31),
                                                   'short'))

        widget.delete(0, "end")
        widget.insert(0, "abc")
        self.window.focus_force()
        self.assertEqual(widget.get_date(), date(2015, 12, 31))

        widget._on_motion(TestEvent(x=10, y=20))
        widget._on_b1_press(TestEvent(x=10, y=20))
        widget._on_b1_press(TestEvent(x=widget.winfo_width() - 2, y=2))
        widget._on_focus_out_cal(TestEvent(x=10, y=20))

        widget.state(("disabled", ))
        self.window.update()
        self.assertIn("disabled", widget.state())

        widget.drop_down()
        self.window.update()
        widget._select()
        self.window.update()
        widget.drop_down()
        self.window.update()
        widget.drop_down()
        self.window.update()

        widget.configure(state='readonly')
        self.window.update()
        widget._select()
        self.assertIn('readonly', widget.state())
Пример #7
0
def add_task(tk):
    clear_view(tk)

    # window configuration
    tk.title("Add task")
    tk.geometry("500x500")

    # task name
    Label(tk, text="Enter your task name:").grid(row=0, column=0, padx=15, pady=25)
    name = Entry(tk, width=30)
    name.grid(row=0, column=1)

    # date
    Label(tk, text="Due date:").grid(row=1, column=0, pady=25)
    date = DateEntry(tk)
    date.grid(row=1, column=1)

    # description
    Label(tk, text="Description:").grid(row=2, column=0, pady=25)
    description = Text(tk, width=25, height=10)
    description.grid(row=2, column=1)

    # priority
    Label(tk, text="Select priority:").grid(row=3, column=0, pady=25)
    priority = IntVar()
    Radiobutton(tk, text="Low", value=1, variable=priority).grid(row=3, column=1)
    Radiobutton(tk, text="Medium", value=2, variable=priority).grid(row=3, column=2)
    Radiobutton(tk, text="High", value=3, variable=priority).grid(row=3, column=3)

    # is completed
    Label(tk, text="Check if completed:").grid(row=4, column=0, pady=25)
    is_completed = BooleanVar()
    Checkbutton(tk, text="Choose", variable=is_completed).grid(row=4, column=1)

    # goes to create_task function
    Button(tk, text="Create task", bg="green", fg="white",
           command=lambda: create_task(name=name.get(), date=date.get(), description=description.get('1.0', END),
                                       priority=priority.get(), is_completed=is_completed.get())) \
        .grid(row=5, column=0, pady=15)

    # goes to main screen
    Button(tk, text="Cancel", bg="black", fg="white", command=lambda: main_screen(tk)).grid(row=5, column=1)
class Funcionario_view(tk.Frame):

    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.criar_widget_funcionario()
        self.funcionario = Funcionario("", 0, 0, "", "", "", 0)

    def criar_widget_funcionario(self):
        # Título
        self.container_titulo = tk.Frame(self.master)
        self.container_titulo["pady"] = 10
        self.container_titulo["padx"] = 20
        self.container_titulo.pack()

        self.titulo_dados = tk.Label(self.container_titulo, text="CADASTRAR NOVO FUNCIONÁRIO")
        self.titulo_dados.pack()

        # Campo id
        self.container_id = self.criar_container_padrao()

        self.id_label = tk.Label(self.container_id, text="Id")
        self.id_label["width"] = 20
        self.id_label["anchor"] = tk.NW
        self.id_label.pack(side=tk.LEFT)

        self.id = tk.Entry(self.container_id)
        self.id["width"] = 10
        self.id.pack(side=tk.LEFT)

        self.botao_buscar = tk.Button(self.container_id)
        self.botao_buscar["text"] = "Buscar"
        self.botao_buscar["command"] = self.buscar_funcionario
        self.botao_buscar.pack(side=tk.LEFT)

        # Campo nome
        self.container_nome = self.criar_container_padrao()

        self.nome_label = tk.Label(self.container_nome, text="Nome")
        self.nome_label["width"] = 20
        self.nome_label["anchor"] = tk.NW
        self.nome_label.pack(side=tk.LEFT)

        self.nome = tk.Entry(self.container_nome)
        self.nome["width"] = 20
        self.nome.pack(side=tk.LEFT)

        # Campo nascimento
        self.container_nascimento = self.criar_container_padrao()

        self.nascimento_label = tk.Label(self.container_nascimento, text="Data de nascimento")
        self.nascimento_label["width"] = 20
        self.nascimento_label["anchor"] = tk.NW
        self.nascimento_label.pack(side=tk.LEFT)

        self.nascimento = DateEntry(self.container_nascimento, width=18, background='darkblue',
                                    foreground='white', borderwidth=2)
        self.nascimento.pack(side=tk.LEFT)

        # Campo sexo
        self.container_sexo = self.criar_container_padrao()

        self.sexo_label = tk.Label(self.container_sexo, text="Sexo")
        self.sexo_label["width"] = 20
        self.sexo_label["anchor"] = tk.NW
        self.sexo_label.pack(side=tk.LEFT)

        self.sexo = tk.StringVar(self.container_sexo)
        self.sexo.set("")  # default value
        self.sexo_combo = tk.OptionMenu(self.container_sexo, self.sexo, "Masculino", "Feminino", "")
        self.sexo_combo["width"] = 15
        self.sexo_combo.pack(side=tk.LEFT)

        # Campo cargo
        self.container_cargo = self.criar_container_padrao()

        self.cargo_label = tk.Label(self.container_cargo, text="Cargo")
        self.cargo_label["width"] = 20
        self.cargo_label["anchor"] = tk.NW
        self.cargo_label.pack(side=tk.LEFT)

        self.cargo = tk.Entry(self.container_cargo)
        self.cargo["width"] = 20
        self.cargo.pack(side=tk.LEFT)

        # Campo qtde dependentes
        self.container_qtde_dependetes = self.criar_container_padrao()

        self.qtde_dependetes_label = tk.Label(self.container_qtde_dependetes, text="Dependentes")
        self.qtde_dependetes_label["width"] = 20
        self.qtde_dependetes_label["anchor"] = tk.NW
        self.qtde_dependetes_label.pack(side=tk.LEFT)

        self.qtde_dependetes = tk.StringVar(self.container_qtde_dependetes)
        self.qtde_dependetes.set("0")  # default value
        self.qtde_dependetes_combo = tk.OptionMenu(self.container_qtde_dependetes, self.qtde_dependetes, "0", "1", "2", "3", "4", "5")
        self.qtde_dependetes_combo["width"] = 15
        self.qtde_dependetes_combo.pack(side=tk.LEFT)

        # Botões
        self.container_botoes = self.criar_container_padrao()

        self.botao_criar = tk.Button(self.container_botoes)
        self.botao_criar["text"] = "Criar"
        self.botao_criar["command"] = self.add_funcionario
        self.botao_criar["bg"] = "blue"
        self.botao_criar["fg"] = "white"
        self.botao_criar.pack(side=tk.LEFT)

        self.botao_atualizar = tk.Button(self.container_botoes)
        self.botao_atualizar["text"] = "Atualizar"
        self.botao_atualizar["command"] = self.atualizar_funcionario
        self.botao_atualizar["bg"] = "green"
        self.botao_atualizar["fg"] = "white"
        self.botao_atualizar["state"] = "disabled"
        self.botao_atualizar.pack(side=tk.LEFT)

        self.botao_excluir = tk.Button(self.container_botoes)
        self.botao_excluir["text"] = "Excluir"
        self.botao_excluir["command"] = self.excluir_funcionario
        self.botao_excluir["bg"] = "red"
        self.botao_excluir["fg"] = "white"
        self.botao_excluir["state"] = "disabled"
        self.botao_excluir.pack(side=tk.LEFT)

        self.botao_limpar = tk.Button(self.container_botoes)
        self.botao_limpar["text"] = "Limpar"
        self.botao_limpar["command"] = self.limpar_tela
        self.botao_limpar.pack()

        # Mensagem
        self.container_mensagem = self.criar_container_padrao()

        self.mensagem = tk.Label(self.container_mensagem, text="")
        self.mensagem.pack()

    def criar_container_padrao(self):
        container = tk.Frame(self.master)
        container["padx"] = 20
        container["pady"] = 5
        container.pack()

        return container

    def add_funcionario(self):
        self.funcionario.nome = self.nome.get()
        self.funcionario.cargo = self.cargo.get()
        self.funcionario.id_setor = 0
        self.funcionario.qtd_dependentes = self.qtde_dependetes.get()
        self.funcionario.sexo = self.sexo.get()
        self.funcionario.data_nascimento = self.nascimento.get()
        self.funcionario.salario = 950

        status, id_gerado, mensagem = self.funcionario.insert_funcionario()

        if status:
            self.id.insert(0, id_gerado)
            self.botao_criar.config(state="disabled")
            self.botao_excluir.config(state="normal")
            self.botao_atualizar.config(state="normal")

        self.mensagem["text"] = mensagem

    def limpar_tela(self):
        self.id.delete(0, tk.END)
        self.nome.delete(0, tk.END)
        self.nascimento.delete(0, tk.END)
        self.cargo.delete(0, tk.END)
        self.sexo.set("")
        self.qtde_dependetes.set("0")
        self.mensagem["text"] = ""
        self.funcionario = Funcionario("", 0, 0, "", "", "", 0)

        self.botao_criar.config(state="normal")
        self.botao_excluir.config(state="disabled")
        self.botao_atualizar.config(state="disabled")

    def buscar_funcionario(self):
        status, mensagem = self.funcionario.select_funcionario(self.id.get())

        if status:
            self.nome.insert(0, self.funcionario.nome)
            self.nascimento.set_date(self.funcionario.data_nascimento)
            self.cargo.insert(0, self.funcionario.cargo)
            self.sexo.set(self.funcionario.sexo)
            self.qtde_dependetes.set(self.funcionario.qtd_dependentes)

            self.botao_criar.config(state="disabled")
            self.botao_excluir.config(state="normal")
            self.botao_atualizar.config(state="normal")
        else:
            self.limpar_tela()

        self.mensagem["text"] = mensagem

    def atualizar_funcionario(self):
        self.funcionario.nome = self.nome.get()
        self.funcionario.cargo = self.cargo.get()
        self.funcionario.id_setor = 0
        self.funcionario.qtd_dependentes = self.qtde_dependetes.get()
        self.funcionario.sexo = self.sexo.get()
        self.funcionario.data_nascimento = self.nascimento.get()
        self.funcionario.salario = 950

        status, mensagem = self.funcionario.update_funcionario()

        if status:
            self.limpar_tela()

        self.mensagem["text"] = mensagem

    def excluir_funcionario(self):
        self.funcionario.id_funcionario = self.id.get()
        status, mensagem = self.funcionario.delete_funcionario()

        if status:
            self.limpar_tela()

        self.mensagem["text"] = mensagem
Пример #9
0
class Print(object):
    TEMPLATES = os.path.join(os.path.dirname(__file__), 'Templates')

    IMAGENS = os.path.join(os.path.dirname(__file__), 'Imagens')
    if not os.path.exists(IMAGENS):
        os.makedirs(IMAGENS)

    _WKTHMLTOPDF_ = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
    report_path = r'c:\temp'
    report_data = datetime.datetime.now().strftime('%Y_%m_%d')
    report_file_html = report_path + '\\HTMLReport_' + report_data + '.html'
    report_file_pdf = report_path + '\\PDFReport_' + report_data + '.pdf'
    options = {
        'quiet': '',
        'page-size': 'A4',
        'margin-top': '1.0cm',
        'margin-right': '1.5cm',
        'margin-bottom': '1.0cm',
        'margin-left': '1.5cm',
        'encoding': 'UTF-8',
    }

    def __init__(self, root, mmember, mfrequencia):
        self.toplevel = root
        self.toplevel.title('Impressão de Frequência(s)')
        self.modelmember = mmember()
        self.modelfrequencia = mfrequencia()

        self.TIPOPESQUISA = [("Individual", "I"), ("Todos", "T")]
        self.vPesquisa = StringVar()
        self.vPesquisa.set('T')
        self.mensagem = StringVar()

        self.comboCache = list()
        """Estilos"""
        style = ttk.Style()

        style.configure("PR.TLabel",
                        padding=6,
                        foreground="black",
                        font=('helvetica', 9, 'bold'))
        style.configure("PR.TEntry",
                        padding=6,
                        background="#ccc",
                        relief="flat")
        style.configure("PR.TButton",
                        padding=6,
                        relief="flat",
                        background="#ccc")

        self.btnCancelImage = PhotoImage(file=self.IMAGENS +
                                         '\\cancel.png').subsample(3, 3)
        self.btnPrintImage = PhotoImage(
            file=self.IMAGENS +
            '\\iconfinder_document_print_118913.png').subsample(3, 3)

        self.formFrame = ttk.Frame(self.toplevel)
        self.formFrame.grid(column=0, row=0, padx=10, pady=10)

        self.formBotao = ttk.Frame(self.toplevel)
        self.formBotao.grid(column=0, row=2, padx=10, pady=10)

        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)

        self.CreateGui()

    def image_file_path_to_base64_string(self, filepath: str) -> str:
        with open(filepath, 'rb') as f:
            return base64.b64encode(f.read()).decode()

    def CreateGui(self):
        self.createForm()
        self.createBotoes()

    def createForm(self):
        self.container1 = Frame(self.formFrame)
        self.container1['pady'] = 10
        self.container1.grid(row=0, column=0)
        self.lblInicial = ttk.Label(self.container1,
                                    style="PR.TLabel",
                                    text="Data Inicial:",
                                    width=12)
        self.lblInicial.pack(side=LEFT)
        self.dtaInicial = DateEntry(self.container1,
                                    width=11,
                                    background='darkblue',
                                    foreground='white',
                                    borderwidth=2,
                                    year=2019,
                                    locale='pt_BR',
                                    date_pattern='dd-MM-yyyy',
                                    state='readonly')
        self.dtaInicial.pack(side=LEFT, ipadx=25, padx=(10, 5))
        self.lblFinal = ttk.Label(self.container1,
                                  style="PR.TLabel",
                                  text="Data Final:",
                                  width=12)
        self.lblFinal.pack(side=LEFT)
        self.dtaFinal = DateEntry(self.container1,
                                  width=11,
                                  background='darkblue',
                                  foreground='white',
                                  borderwidth=2,
                                  year=2019,
                                  locale='pt_BR',
                                  date_pattern='dd-MM-yyyy',
                                  state='readonly')
        self.dtaFinal.pack(side=LEFT, ipadx=25, padx=(10, 5))
        """
         O combobox fica invisível caso o radiobutton 'todos' esteja ativado
         caso contrário mostra o combobox
        """
        self.container2_1 = Frame(self.formFrame)
        self.container2_1['pady'] = 10
        self.container2_1.grid(row=2, column=0)
        self.lbl = ttk.Label(self.container2_1,
                             style="PR.TLabel",
                             text="Membro:",
                             width=12)
        self.lbl.pack(side=LEFT)
        self.cbxCombo = ttk.Combobox(self.container2_1,
                                     state='readonly',
                                     width=53)
        self.cbxCombo.pack(side=LEFT, ipadx=25, padx=(10, 5))
        self.preencherCombo()

    def createBotoes(self):
        self.container3 = Frame(self.formBotao)
        self.container3['pady'] = 10
        self.container3.grid(row=0, column=0)
        self.btnPrint = ttk.Button(self.container3,
                                   style="PR.TButton",
                                   compound=LEFT)
        self.btnPrint['text'] = 'Imprimir'
        self.btnPrint['width'] = 12
        self.btnPrint['command'] = self.print_relatorio
        self.btnPrint['image'] = self.btnPrintImage
        self.btnPrint.pack(side=LEFT, padx=10, pady=10)

        self.btnCancel = ttk.Button(self.container3,
                                    style="PR.TButton",
                                    compound=LEFT)
        self.btnCancel['text'] = 'Fechar'
        self.btnCancel['width'] = 12
        self.btnCancel['command'] = self.exitForm
        self.btnCancel['image'] = self.btnCancelImage
        self.btnCancel.pack(side=LEFT, padx=10, pady=10)

    def createMessage(self):
        self.container4 = Frame(self.frameMensagem)
        self.container4['pady'] = 10
        self.container4.grid(row=0, column=0)
        self.lblTipoPesq = ttk.Label(self.container4,
                                     style="PR.TLabel",
                                     textvariable=self.mensagem,
                                     width=100)
        self.lblTipoPesq.pack(side=LEFT)

    """Outras funções"""

    def exitForm(self):
        self.toplevel.destroy()

    # def verificaTipoImpressao(self):
    #     # tipoPesquisa = self.vPesquisa.get()
    #     # if tipoPesquisa == 'I':
    #         self.mensagem.set('')
    #         #Exibe o combobox
    #         self.cbxCombo.pack(side=LEFT)
    #         self.preencherCombo()
    #     # elif tipoPesquisa == 'T':
    #     #     self.mensagem.set('Será impressa a frequência de todos no período acima')
    #     #     self.cbxCombo.pack_forget()

    def preencherCombo(self):
        self.comboCache.clear()  #limpa a lista
        for row in self.modelmember.getNames():
            self.comboCache.append(row[1])  #preenche a lista
            self.cbxCombo[
                'values'] = self.comboCache  #insere o retorno do bd no combo
            self.cbxCombo.current(0)

    def print_relatorio(self):
        """
            get() pega o que estiver no combo,
            já o select_get() pega o que for sendo selecionado
        """
        lista = list()
        selecao = self.cbxCombo.get()
        numcad = self.modelmember.getByNameID(selecao)
        for row in numcad:
            numcad = row[0]
        inicio = self.formataData(self.dtaInicial.get())
        fim = self.formataData(self.dtaFinal.get())
        frequenciaTotal = self.modelfrequencia.getTotalPresenca(
            numcad, inicio, fim)
        for row in frequenciaTotal:
            frequenciaTotal = row[0]
        totalFaltas = self.modelfrequencia.getTotalPresencaByTipo(
            numcad, inicio, fim, 'F')
        for row in totalFaltas:
            totalFaltas = row[0]
        totalPresenca = self.modelfrequencia.getTotalPresencaByTipo(
            numcad, inicio, fim, 'P')
        for row in totalPresenca:
            totalPresenca = row[0]
        totalJustificativa = self.modelfrequencia.getTotalPresencaByTipo(
            numcad, inicio, fim, 'J')
        for row in totalJustificativa:
            totalJustificativa = row[0]

        persons = [{
            'nome': selecao,
            'cadastro': numcad,
            'dtaInicial': inicio,
            'dtaFinal': fim,
            'total': frequenciaTotal,
            'falta': totalFaltas,
            'presenca': totalPresenca,
            'justificativa': totalJustificativa
        }]

        config = pdfkit.configuration(wkhtmltopdf=self._WKTHMLTOPDF_)
        file_loader = jinja2.FileSystemLoader(self.TEMPLATES)
        env = jinja2.Environment(loader=file_loader)
        template_report = env.get_template('report.html')
        content_report = 'REPORT: Elipse Plant Manager'
        html_report = template_report.render(
            content=content_report,
            img_string=self.image_file_path_to_base64_string(
                self.IMAGENS + '/simbolos-da-maconaria-6_xl.png'),
            persons=persons)

        # salva o relatório em html
        with open(self.report_file_html, 'w', encoding='utf-8') as html_file:
            html_file.write(html_report)

        # transforam html em pdf
        pdf_file = pdfkit.from_string(html_report,
                                      self.report_file_pdf,
                                      configuration=config,
                                      options=self.options,
                                      css=self.TEMPLATES + '/paper_pdf.css')
        if (pdf_file):
            webbrowser.open_new(self.report_file_pdf)

    def formataData(self, valor):
        """
        :param valor: passa o valor da data a ser formatada
        :return: data formatada
        """
        valoratual = valor.replace("-", "")
        valoratual = '{4}{5}{6}{7}-{2}{3}-{0}{1}'.format(*valoratual)
        return valoratual
Пример #10
0
class InputStudentWindow(tkinter.Frame):
    def __init__(self, master=None, path="data/estudiantes.json"):
        super().__init__(master)
        self.pack()
        self.master.title("Entrada de alumnos")
        self.master.resizable(False, False)
        self.default_path = path
        # self.master.protocol("WM_DELETE_WINDOW", self.faa)
        self.lb_name = tkinter.Label(self.master, text="Nombre:")
        self.lb_name.pack()

        self.in_name = tkinter.Entry(self.master, width=26)
        self.in_name.pack()

        self.lb_age = tkinter.Label(self.master, text="Edad:")
        self.lb_age.pack()

        self.in_age = tkinter.Entry(self.master, width=26)
        self.in_age.pack()

        self.lb_school = tkinter.Label(self.master, text="Estudios:")
        self.lb_school.pack()

        self.cb_school = ttk.Combobox(self.master, state="readonly")
        self.cb_school["values"] = [
            "Primaria", "Secundaria", "Preparatoria", "Licenciatura",
            "Posgrado"
        ]
        self.cb_school.current(0)
        self.cb_school.pack()

        self.lb_date = tkinter.Label(self.master, text="Fecha:")
        self.lb_date.pack()
        self.cal = DateEntry(self.master,
                             width=12,
                             background='darkblue',
                             foreground='white',
                             borderwidth=2)
        self.cal.pack()

        self.lb_time = tkinter.Label(self.master, text="Hora:")
        self.lb_time.pack()

        self.in_time = tkinter.Entry(self.master, width=26)
        self.hour = time.strftime("%H:%M:%S")
        self.in_time.insert(0, self.hour)
        self.in_time.pack()

        self.bt_save = tkinter.Button(self.master,
                                      text="Guardar",
                                      command=self.save_student)
        self.bt_save.pack(pady=10)

    def save_student(self):
        """
        Valida que la información puesta sea coherente
        guarda el nuevo estudiante en el último documento abierto
        """
        if self.in_name.get() is None or self.in_name.get(
        ) == "" or self.cb_school.get().isdigit():
            messagebox.showerror(
                "Error",
                "Por favor ingrese el nombre del estudiante. Verifique el formato."
            )
        elif self.in_age.get() is None or self.in_age.get(
        ) == "" or not self.in_age.get().isdigit():
            messagebox.showerror(
                "Error",
                "Por favor ingrese la edad del estudiante. Verifique el formato."
            )
        elif self.cb_school.get() is None or self.cb_school.get(
        ) == "" or self.cb_school.get().isdigit():
            messagebox.showerror(
                "Error",
                "Por favor ingrese la escolaridad del estudiante. Verifique la selección."
            )
        elif self.cal.get() is None or self.cal.get() == "":
            messagebox.showerror("Error",
                                 "Por favor ingrese la fecha de captura.")
        elif self.in_time.get() is None or self.in_time.get() == "":
            messagebox.showerror("Error",
                                 "Por favor ingrese la hora de captura.")
        else:
            output = pd.DataFrame({
                "Nombre": [self.in_name.get()],
                "Edad": [self.in_age.get()],
                "Escolaridad": [self.cb_school.get()],
                "Fecha": [self.cal.get()],
                "Hora": [self.in_time.get()]
            })
            if not (path.exists(self.default_path)):
                output.to_json(self.default_path)
            else:
                input_json = pd.read_json(self.default_path)
                output = pd.concat([input_json, output], axis=0)
                output.reset_index(drop=True, inplace=True)
                output.to_json(self.default_path)
Пример #11
0
class main:
    def __init__(self, n_):
        print(n_)
        self.n = n_
        ob = database_queries.database()
        re = ob.get_appoint_byn(n_)
        print(re)
        self.tk = Toplevel()

        self.frame = Frame(self.tk, height=700, width=700)
        self.frame.place(x=0, y=0)

        height = self.tk.winfo_screenheight()
        width = self.tk.winfo_screenwidth()

        y = (height - 700) // 2
        x = (width - 700) // 2
        self.tk.geometry('700x700+' + str(x) + '+' + str(y))

        self.tk.resizable(height=False, width=False)

        self.can = Canvas(self.frame, height="700", width="700")
        self.can.pack()
        self.img = PhotoImage(file="./images/img2.gif")
        self.can.create_image(0, 0, image=self.img, anchor=NW)

        self.can.create_text(360,
                             100,
                             text="Edit appointment ",
                             fill="powder blue",
                             font=('Cooper Black', 35))

        self.pn = StringVar(self.tk)
        self.pn.set(re[2])
        self.can.create_text(175,
                             220,
                             text="Patient Name",
                             fill="sandybrown",
                             font=('Cooper Black', 25))
        self.e1 = Entry(self.frame,
                        font=('Cooper Black', 18),
                        borderwidth="2",
                        textvariable=self.pn)
        self.e1.place(x=310, y=210)

        self.t = StringVar(self.tk)
        self.t.set(re[3])
        self.can.create_text(175,
                             280,
                             text="Timing",
                             fill="sandybrown",
                             font=('Cooper Black', 25))
        self.e2 = Entry(self.frame,
                        font=('Cooper Black', 18),
                        borderwidth="2",
                        textvariable=self.t)
        self.e2.place(x=310, y=260)

        self.date = StringVar(self.tk)
        self.date.set(re[4])
        self.can.create_text(175,
                             330,
                             text="Date",
                             fill="sandybrown",
                             font=('Cooper Black', 25))

        self.dob = DateEntry(self.can,
                             font=('cooper balck', 12),
                             bg='darkblue',
                             fg='white',
                             borderwidth="2",
                             textvariable=self.date)
        self.dob.place(x=310, y=310)
        self.dob.config(width=30)

        self.des = StringVar(self.tk)
        self.des.set(re[5])
        self.can.create_text(175,
                             380,
                             text="Description",
                             fill="sandybrown",
                             font=('Cooper Black', 25))
        self.e4 = Entry(self.frame,
                        font=('Cooper Black', 18),
                        borderwidth="2",
                        textvariable=self.des)
        self.e4.place(x=310, y=360)

        self.btn = Button(self.frame,
                          text="Update",
                          fg="powder blue",
                          bg="black",
                          font=('Cooper Black', 22),
                          command=self.update)
        self.btn.place(x=310, y=450)

        self.tk.mainloop()

    def update(self):
        data = [
            self.e1.get(),
            self.e2.get(),
            self.dob.get(),
            self.des.get(), self.n
        ]

        t = database_queries.database()
        t.update_appoint(data)
Пример #12
0
class export_data():
    def __init__(self, root):
        self.root = root

        # root.overrideredirect(True)
        # root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
        root.geometry('425x225')

        self.root.title('Export Data')

        frame = LabelFrame(root, text='Export Data')
        frame.place(x=30, y=50)
        Label(frame, text='Date').grid(row=0, column=0)
        self.cal = DateEntry(frame,
                             width=12,
                             date_pattern='y-mm-dd',
                             year=2020,
                             month=4,
                             day=4,
                             background='darkblue',
                             foreground='white',
                             borderwidth=2)
        self.cal.grid(row=0, column=1)
        Label(frame, text='Session').grid(row=2, column=0)
        Label(frame, text='Location').grid(row=3, column=0)
        self.n = StringVar()
        self.sessionchosen = ttk.Combobox(frame, width=20, textvariable=self.n)

        # Adding combobox drop down list
        self.sessionchosen['values'] = ('Morning', 'Evening')
        self.sessionchosen.current(0)
        self.sessionchosen.grid(row=2, column=1)

        self.l = StringVar()
        self.location = ttk.Combobox(frame, width=20, textvariable=self.l)

        # Adding combobox drop down list
        self.location['values'] = ('FTP', 'Flashdrive')
        self.location.current(0)
        self.location.grid(row=3, column=1)

        self.b3 = Button(frame, text='Export', command=self.Export)
        self.b3.grid(row=4, column=1)

    def Export(self):
        os.chdir('..')
        os.chdir('..')
        os.chdir('..')
        os.chdir('/media/pi')
        stream = os.popen('ls')
        output = stream.read()
        output = str(output.replace("\n", ""))
        name = output
        #print(name)

        print(name)
        os.chdir('..')
        os.chdir('..')

        os.chdir('..')
        os.chdir('/home/pi/tkinter code\'s_modified')
        print(os.getcwd())
        #print('Exporting '+self.cal.get()+' datetime '+datetime.date())
        session = ""
        if (self.sessionchosen.get() == "Morning"):
            session = "m"
        elif (self.sessionchosen.get() == "Evening"):
            session = "e"
        if (self.location.get() == "Flashdrive"):
            print(session)
            mydb = mysql.connector.connect(host="localhost",
                                           database="SC001",
                                           user="******",
                                           passwd="pi")
            cursor = mydb.cursor()
            cursor_1 = mydb.cursor()
            cursor_1.execute('select * from Cust_Info')
            result = cursor_1.fetchall()
            query = 'select * from Milk_Collection where Date=%s and Session=%s'

            parameters = (self.cal.get(), session)
            cursor.execute(query, parameters)
            path = str("/media/pi/" + name + "/Reports")
            #path=path.replace('\n',"")
            #print("path: ",path)
            try:
                if not os.path.exists(path):
                    os.makedirs(path)
                    print('directory made')
            except OSError:
                print("Error Creating Directory ", path)
            filename = str(path + "/" + self.cal.get() + "_" +
                           self.sessionchosen.get() + ".csv")

            with open(filename, 'w+', newline='') as file:
                writer = csv.writer(file)
                writer.writerow([
                    "Cust_ID", "Name", "Milk Type", "Fat", "Snf",
                    "Added Water", "Quantity", "Rate", "Session", "Date",
                    "Time"
                ])

                for i in cursor:
                    name = ""
                    for j in result:
                        if i[0] == j[0]:
                            name = j[1]
                            break
                    date = i[10].now.strftime('%d-%m-%Y')
                    print("Date" + date)
                    writer.writerow([
                        i[0], name, i[1], i[2], i[3], i[4], i[7], i[8], i[9],
                        str(date), i[11]
                    ])

        else:
            print(session)
            mydb = mysql.connector.connect(host="localhost",
                                           database="SC001",
                                           user="******",
                                           passwd="pi")
            cursor = mydb.cursor()
            cursor_1 = mydb.cursor()
            cursor_1.execute('select * from Cust_Info')
            result = cursor_1.fetchall()
            query = 'select * from Milk_Collection where Date=%s and Session=%s'

            parameters = (self.cal.get(), session)
            cursor.execute(query, parameters)
            filename = str(self.cal.get() + "_" + self.sessionchosen.get() +
                           ".csv")

            with open(filename, 'w+', newline='') as file:
                writer = csv.writer(file)
                writer.writerow([
                    "Cust_ID", "Name", "Milk Type", "Fat", "Snf",
                    "Added Water", "Quantity", "Rate", "Session", "Date",
                    "Time"
                ])

                for i in cursor:
                    name = ""
                    for j in result:
                        if i[0] == j[0]:
                            name = j[1]
                            break
                    date = i[9].strftime('%d-%m-%Y')
                    print("Date" + date)
                    writer.writerow([
                        i[0], name, i[1], i[2], i[3], i[4], i[6], i[7], i[8],
                        str(date), i[10]
                    ])
            ftp = FTP('shubhamcomputech.co.in')
            ftp.login(user="******",
                      passwd="demoftp@1000")
            ftp.cwd('/')
            ftp.storbinary('STOR ' + filename, open(filename, 'rb'))
            ftp.quit()
Пример #13
0
class MoreSpace(Module):
    def __init__(self, root):
        super(MoreSpace, self).__init__(root)
        self.root.title("Invoice Generator - More Space")
        self.module_name = 'MoreSpace'
        self.root.geometry('450x610')

    def load_database(self):
        self.SPACES = Sheet('morespace_spaces')
        self.ITEMS = Sheet('morespace_items')
        self.EXTRAS = Sheet('morespace_extras')

    def build_window(self):
        super(MoreSpace, self).place_admin_fields()
        super(MoreSpace, self).place_customer_fields()
        self.place_space_reservation_fields()
        super(MoreSpace, self).place_item_reservation_fields()
        super(MoreSpace, self).place_notes()
        self.clear()

    def place_space_reservation_fields(self):
        frame = tk.LabelFrame(self.master,
                              text='Space Reservation',
                              font=('Arial', 14),
                              padx=10,
                              pady=10,
                              borderwidth=0,
                              highlightthickness=0)

        spaces_frame = tk.LabelFrame(frame,
                                     borderwidth=0,
                                     highlightthickness=0)

        codes = [code[0] for code in self.SPACES.list_items()]

        self.space_reservation = [Checkbox(code) for code in sorted(codes)]
        self.tools_reservation = Checkbox('Tools')
        for checkbox in self.space_reservation + [self.tools_reservation]:
            temp = tk.Checkbutton(spaces_frame,
                                  text=checkbox.name,
                                  variable=checkbox.state)
            temp.pack(side=tk.LEFT)

        spaces_frame.pack(padx=20, anchor=tk.W)

        dates_frame = tk.LabelFrame(frame, borderwidth=0, highlightthickness=0)
        tk.Label(dates_frame,
                 text='Dates',
                 font=('Arial', 10),
                 padx=10,
                 width=5,
                 anchor=tk.W).grid(row=0, column=0)

        self.start_date = DateEntry(dates_frame,
                                    width=8,
                                    background='black',
                                    foreground='white',
                                    borderwidth=2)
        self.start_date.grid(row=0, column=1, padx=9)

        self.end_date = DateEntry(dates_frame,
                                  width=8,
                                  background='black',
                                  foreground='white',
                                  borderwidth=2)
        self.end_date.grid(row=0, column=2, padx=9)
        dates_frame.pack(padx=10, pady=5, anchor=tk.W)

        details_frame = tk.LabelFrame(frame,
                                      borderwidth=0,
                                      highlightthickness=0)

        entries = []
        for i, text in enumerate(['Tool Exclusions', 'Day Exclusions']):
            tk.Label(details_frame,
                     text=text,
                     font=('Arial', 10),
                     padx=10,
                     width=12,
                     anchor=tk.W).grid(row=i, column=0, padx=10)
            entry = tk.Spinbox(details_frame,
                               from_=0,
                               to=100,
                               wrap=True,
                               width=4,
                               justify=tk.LEFT)
            entry.grid(row=i, column=1, padx=10, sticky=tk.W)
            entries.append(entry)

        self.tool_exclusions, self.day_exclusions = entries

        tk.Label(details_frame,
                 text='Additional Makers',
                 font=('Arial', 10),
                 padx=10,
                 width=12,
                 anchor=tk.W).grid(row=0, column=2, padx=10)
        self.additional_makers = tk.Spinbox(details_frame,
                                            from_=0,
                                            to=100,
                                            wrap=True,
                                            width=4,
                                            justify=tk.LEFT)
        self.additional_makers.grid(row=0, column=3, padx=10, sticky=tk.W)

        tk.Label(details_frame,
                 text='Discount',
                 font=('Arial', 10),
                 padx=10,
                 width=12,
                 anchor=tk.W).grid(row=1, column=2, padx=10)

        self.discount = tk.Spinbox(details_frame,
                                   from_=0,
                                   to=25,
                                   increment=5,
                                   wrap=True,
                                   width=4,
                                   justify=tk.LEFT)
        self.discount.grid(row=1, column=3, padx=10, sticky=tk.W)
        details_frame.pack(anchor=tk.W)

        frame.pack(padx=20, pady=2, anchor=tk.W)

    def place_notes(self):
        frame = tk.LabelFrame(self.master,
                              text='Notes',
                              font=('Arial', 14),
                              padx=10,
                              pady=10,
                              borderwidth=0,
                              highlightthickness=0)
        self.notes = tk.Text(frame, width=49, height=2)
        self.notes.pack()

        frame.pack(padx=20, pady=2, anchor=tk.W)

    def read_inputs(self, *args):
        def convert_to_num(str, isFloat=True):
            test_str = str
            if isFloat:
                test_str = str.replace('.', '', 1)

            if test_str == '':
                return 0
            elif test_str.isnumeric():
                return float(str)
            else:
                return -1  # Error

        def separate(string_date, split_char='/'):
            string_date = string_date.split(split_char)
            m, d, y = [int(num) for num in string_date]
            return y, m, d

        def count_days(start, end):

            start, end = date(*separate(start)), date(*separate(end))
            delta_day = timedelta(days=1)

            days = {
                'mon': 0,
                'tue': 1,
                'wed': 2,
                'thu': 3,
                'fri': 4,
                'sat': 5,
                'sun': 6
            }

            dt = start
            day_count = 0

            while dt <= end:
                if dt.weekday() != days['sun']:
                    day_count += 1
                dt += delta_day

            return day_count

        def reformat(string_date, char='/'):
            date = string_date.split('/')
            for i, entry in enumerate(date):
                if len(entry) == 1:
                    date[i] = '0' + entry

            return char.join(date)

        def generate_col_ids(chars):
            res = []

            for num in range(24, 36):
                entry = []
                for char in chars:
                    entry.append(char + str(num))
                res.append(entry)

            return res

        admin, customer, company = self.admin.get(), self.customer.get(
        ), self.company.get()
        credit = convert_to_num(self.credit.get())

        additional_makers = convert_to_num(self.additional_makers.get(),
                                           isFloat=False)
        day_exclusions = convert_to_num(self.day_exclusions.get(),
                                        isFloat=False)
        tool_exclusions = convert_to_num(self.tool_exclusions.get(),
                                         isFloat=False)
        discount = convert_to_num(self.discount.get()) / 100

        current_file_count = str(len(os.listdir('Invoices/MoreSpace/')) + 1)
        zeros = ''.join(['0'] * (5 - len(current_file_count.split())))
        invoice_number = zeros + current_file_count
        invoice_date = datetime.date(datetime.now()).strftime("%m/%d/%y")

        num_of_days = count_days(self.start_date.get(), self.end_date.get())
        num_of_billable_days = num_of_days - day_exclusions

        booked_spaces = []
        for checkbox in self.space_reservation:
            if checkbox.state.get():
                _, description, rate, unit = self.SPACES[checkbox.name]
                booked_spaces += [(description, num_of_billable_days, unit,
                                   float(rate))]

        billables = [space for space in booked_spaces]
        num_of_billable_tool_days = 0
        if self.tools_reservation.state.get():  # Tools
            num_of_billable_tool_days = num_of_billable_days - tool_exclusions

            item, rate, unit = self.EXTRAS["Tool Access"]

            billables += [(item, num_of_billable_tool_days, unit, float(rate))]

        if additional_makers > 0:
            unit = 'People'

            if additional_makers == 1:
                unit = 'Person'

            item, rate, _ = self.EXTRAS["Additional Maker(s)"]
            billables += [(item, additional_makers, unit, float(rate))]

        reserved_items = []
        for item, info in self.table_fields.items():
            if item.get() != '':

                _rate, _qty = info

                rate = convert_to_num(_rate.get())
                qty = convert_to_num(_qty.get(), isFloat=False)

                if rate <= 0 or qty <= 0:
                    raise Exception("Invalid rate or quanitity used")

                item_name = item.get()
                if item_name in self.ITEMS:
                    _, _, unit = self.ITEMS[item_name]
                else:
                    unit = "Item"

                reserved_items += [(item_name, qty, unit, rate)]

        billables += reserved_items

        # Validate All inputs
        try:
            if admin == "":
                raise Exception("Insert Admin Name")

            if customer == "":
                raise Exception("Insert Customer Name")

            if company == "":
                raise Exception("Insert Company Name")

            if credit < 0:
                raise Exception("Credit is a positive number")

            if day_exclusions < 0:
                raise Exception("Day Exclusions is a positive integer")

            if tool_exclusions < 0:
                raise Exception("Tool Exclusions is a positive integer")

            if discount < 0 or discount > 1:
                raise Exception("Discount is a number between 0 and 100")

            if booked_spaces:
                if num_of_days < 1:
                    raise Exception("Start Date is after End Date")

                if num_of_billable_days < 1:
                    raise Exception("Too many day exclusions")

                if additional_makers < 0:
                    raise Exception("Additional Makers is a positive integer")

                elif (additional_makers + 1) > len(booked_spaces) * 4:
                    raise Exception("Only Four Makers Allowed per Space")

            elif num_of_billable_days > 1 or additional_makers > 0:
                raise Exception("No spaces have been booked!")

            if num_of_billable_tool_days < 0:
                raise Exception("Too many tool Exclusions")

            elif not self.tools_reservation.state.get(
            ) and num_of_billable_tool_days > 0:
                raise Exception("Tool exclusion with no tools!")

            for name, qty, unit, rate in reserved_items:
                if qty <= 0:
                    raise Exception(
                        "Invalid quantity used in item reservation")
                if rate <= 0:
                    raise Exception("Invalid rate used in item reservation")

        except Exception as e:
            return e

        target = 'Invoices/MoreSpace/' + invoice_number + "_" + customer

        cells = {
            'admin': 'A6',
            'name': 'A13',
            'company': 'A14',
            'invoice_date': 'G12',
            'invoice_number': 'G11',
            'due_date': 'G13',
            'start_date': 'B17',
            'end_date': 'B18',
            'table': (generate_col_ids(['A', 'C', 'D', 'F'])),
            'discount': 'F39',
            'credit': 'G42',
            'notes': 'A47'
        }

        entries = [(cells['admin'], admin), (cells['name'], customer),
                   (cells['company'], company),
                   (cells['invoice_date'], invoice_date),
                   (cells['invoice_number'], invoice_number),
                   (cells['start_date'], reformat(self.start_date.get())),
                   (cells['end_date'], reformat(self.end_date.get())),
                   (cells['due_date'], reformat(self.start_date.get())),
                   (cells['notes'], self.notes.get("1.0", 'end-1c'))]

        for placement, entry in zip(cells['table'], billables):
            for cell, info in zip(placement, entry):
                entries.append((cell, info))

        hidden_entries = [(cells['credit'], credit),
                          (cells['discount'], discount)]

        return [target, entries, hidden_entries]

    def clear(self, *args):
        self.admin.delete(0, 'end')
        self.admin.insert(0, 'Omar Eddin')

        self.customer.delete(0, 'end')

        self.company.delete(0, 'end')
        self.company.insert(0, 'Individual')

        self.credit.delete(0, 'end')

        for space in self.space_reservation:
            space.state.set(0)

        self.tools_reservation.state.set(0)

        self.additional_makers.delete(0, 'end')
        self.tool_exclusions.delete(0, 'end')
        self.day_exclusions.delete(0, 'end')
        self.discount.delete(0, 'end')

        for item_field, info_fields in self.table_fields.items():
            for field in [item_field, *info_fields]:
                field.delete(0, 'end')

        self.notes.delete(1.0, 'end')
        self.notes.insert(
            1.0, 'Please make your payment through Paypal to [email protected]')

    def close(self):
        super(MoreSpace, self).close()
        for sheet in [self.SPACES, self.ITEMS, self.EXTRAS]:
            sheet.close()
Пример #14
0
list1=['PYTHON','JAVA','C','C++','HTML','C#']
droplist=OptionMenu(top,c,*list1)
droplist.config(width=15)
c.set('Select Course')
droplist.place(x=240,y=195)"""
secvar=StringVar()
label_2=Label(top,text="Select expiry date",font=("bold",10))
label_2.place(x=80,y=200)
Button(top,text='SUBMIT',width=20,bg='brown',fg='white',command=certificate).place(x=180,y=280)
cal = DateEntry(top, width=12, year=2019, month=6, day=22, 
background='darkblue', foreground='white', borderwidth=2)
cal.place(x=250,y=195)




call=cal.get()

usr=Username.get()
Course=c.get()
seq=secvar.get()
plat=secvar1.get()








class rsearch(tk.Tk):
    def __init__(self, *args, **kwargs):
        # __init__ function for class Tk
        tk.Tk.__init__(self, *args, **kwargs)
        # self = Tk()
        current_date = date.today()
        tomorrow = date.today() + timedelta(1)
        print(type(tomorrow))
        self.title("Search")
        self.geometry("900x500")
        self.config(background="black", pady=10)
        label1 = tk.Label(self, text='Check In Date')
        label1.place(x='60', y='40')
        self.cal = DateEntry(self,
                             width=12,
                             year=current_date.year,
                             month=current_date.month,
                             day=current_date.day,
                             mindate=current_date,
                             date_pattern='y-mm-dd',
                             background='darkblue',
                             foreground='white',
                             borderwidth=2)
        self.cal.place(x='60', y='80')
        label2 = tk.Label(self, text='Check out Date')
        label2.place(x='200', y='40')
        self.cal.bind("<<DateEntrySelected>>", self.callback)
        date_time_obj = datetime.datetime.strptime(self.cal.get(), '%Y-%m-%d')
        print(type(date_time_obj))
        # if self.cal.get():
        #     min_date=self.cal.get()
        # else:
        #    min_date=tomorrow
        self.cal1 = DateEntry(self,
                              width=12,
                              year=tomorrow.year,
                              month=tomorrow.month,
                              day=tomorrow.day,
                              mindate=tomorrow,
                              date_pattern='y-mm-dd',
                              background='darkblue',
                              foreground='white',
                              borderwidth=2)
        self.cal1.place(x='200', y='80')
        # reg = self.register(self.callback)
        #
        # self.cal1.config(validate="key",
        #          validatecommand=(reg, '% P'))
        button = tk.Button(self, text='Search', command=self.search)
        button.place(x='150', y='120')

    def search(self):
        print(self.cal.get())
        print(self.cal1.get())
        self.destroy()
        bpage = booking()

    def callback(self, input):
        w = input.widget
        date = w.get_date() + timedelta(1)
        self.cal1.config(mindate=date)
Пример #16
0
class MainWindow(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.master.title("Delivery Accountant")
        self.master.minsize(1440, 1080)
        self.master.resizable(True, True)
        # create_tables()
        # draws searching engine
        self.duedate_dockets()
        # additional info for dates
        self.customer_info = self.draw_info(CUSTOMER,
                                            pos_x=2,
                                            pos_y=0,
                                            span_x=2,
                                            span_y=1)
        self.vendor_info = self.draw_info(VENDOR,
                                          pos_x=2,
                                          pos_y=1,
                                          span_x=2,
                                          span_y=1)
        self.draw_dates(pos_x=4, pos_y=0, span_x=2, span_y=1)
        self.draw_notes(pos_x=4, pos_y=1, span_x=2, span_y=2)
        self.draw_tasks(12, pos_x=2, pos_y=4, span_x=4, span_y=2)

        self.delivery_info(pos_x=6, pos_y=0, span_x=1, span_y=1)

        self.draw_menu()
        self.update_customer_combobox()
        self.update_vendor_combobox()
        # the only button for now in this app
        self.btn_submit = ttk.Button(text="submit")
        self.btn_submit.grid(column=0,
                             row=11,
                             columnspan=2,
                             rowspan=2,
                             sticky="NESW")

    def duedate_dockets(self):
        # search engine UI
        self.label_frame_search = tk.LabelFrame(text="Search")
        self.label_frame_search.grid(column=0,
                                     row=0,
                                     columnspan=2,
                                     rowspan=6,
                                     pady=10,
                                     padx=10,
                                     sticky="NESW")
        self.search_entry = tk.Entry(self.label_frame_search,
                                     bg=BASECOLOR,
                                     font=ENTRYFONT)
        self.search_entry.bind("<Return>", self.update_dockets_list)
        self.search_entry.grid(column=0, row=0)
        data = request_recent()
        self.list_dockets(data=data)

    def draw_menu(self):
        """Creates menue in the app"""
        self.menubar = tk.Menu(self.master)

        self.editmenu = tk.Menu(self.menubar, tearoff=0)
        self.editmenu.add_command(label="New Customer",
                                  command=lambda: self.new_partner(CUSTOMER))
        self.editmenu.add_command(label="New Vendor",
                                  command=lambda: self.new_partner(VENDOR))
        self.editmenu.add_command(label="New Delivery",
                                  command=self.new_delivery)

        self.menubar.add_cascade(label="Edit", menu=self.editmenu)

        # self.menubar.add_command(label="Report", command=report_open_tasks)
        self.menubar.add_command(label="Test database", command=self.db_test)
        self.master.config(menu=self.menubar)

    # UI labels with dockets
    def db_test(self):

        create_tables()

    def update_dockets_list(self, event):
        num = self.search_entry.get()
        self.update_by_docket(event, docket=int(num))
        self.list_dockets(data=request_recent())

    def new_delivery(self):
        self.set_active()
        self.clear_entries()
        self.clear_by_partner(CUSTOMER)
        self.clear_by_partner(VENDOR)
        self.btn_submit.configure(command=self.read_delivery_entries)

    def list_dockets(self, data=None, dockets=None):
        """
        parameter: data(list) includes list of strings to show
        """
        """if data is None:
            data = []
            for i in range(0, LENGTH_DOCKETS):
                data.append("Max and Co. \n # 30041")
        """
        # dont forget that there maybe less data than dockets!

        self.docket_labels = []
        font_list = None
        for i, obj in enumerate(data):
            if i % 2 == 0:
                font_list = SECONDARYCOLOR
            else:
                font_list = BASECOLOR
            # concatincates dict wit empty string
            text = ""
            for k, v in obj.items():
                text = text + str(k) + " : " + str(v) + "\n"
            label = tk.Label(self.label_frame_search, text=text, bg=font_list)
            label.grid(column=0, row=i + 1, sticky="NESW")
            label.bind("<Double-Button-1>", self.update_by_docket)
            self.docket_labels.append(label)

            # creates the label with data and packs it with grid

    def delivery_info(self, pos_x, pos_y, span_x, span_y):
        """
        draws delivery information of the form
        """
        self.label_frame_delivery = tk.LabelFrame(self.master,
                                                  text="Delivery Info")
        self.label_frame_delivery.grid(column=pos_x,
                                       row=pos_y,
                                       columnspan=2,
                                       sticky="NEW",
                                       padx=10,
                                       pady=10)
        self.deliver_address = tk.Label(self.label_frame_delivery,
                                        text="Delivery Address")
        self.deliver_address.grid(column=0, row=0)
        self.entry_del_address = tk.Entry(self.label_frame_delivery, width=30)
        self.entry_del_address.grid(column=1, row=0)

    def draw_info(self, name, pos_x, pos_y, span_x, span_y):
        """
        :parameter: labels: (bool) show the requirement of label of entry
        :parameter: name: whos info is going to showed up
        :return: (list) returns two lists that have information about state
        """
        label_frame = tk.LabelFrame(self.master, text="{} Info".format(name))
        label_frame.grid(column=pos_x,
                         row=pos_y,
                         columnspan=span_x,
                         rowspan=span_y,
                         pady=10,
                         padx=10,
                         sticky="NESW")

        # TODO backend method that returns all customers
        combobox = ttk.Combobox(label_frame, values=[], font=ENTRYFONT)
        combobox.grid(column=0, row=0, sticky="NESW")
        if name == CUSTOMER:
            combobox.bind("<<ComboboxSelected>>", self.update_customer_info)
        elif name == VENDOR:
            combobox.bind("<<ComboboxSelected>>", self.update_vendor_info)
        name_label = tk.Label(label_frame,
                              text="{} Name".format(name),
                              font=BASICFONT)
        name_label.grid(column=0, row=1, sticky="W")

        address_label = tk.Label(label_frame, text="Address", font=BASICFONT)
        address_label.grid(column=0, row=2, sticky="W")

        phone_label = tk.Label(label_frame, text="Phone", font=BASICFONT)
        phone_label.grid(column=0, row=3, sticky="W")

        contact_label = tk.Label(label_frame, text="Contact", font=BASICFONT)
        contact_label.grid(column=0, row=4, sticky="W")

        # if need lbels than it is going to draw labels, if not draw entries

        name = tk.Entry(label_frame, width=30)
        name.grid(column=1, row=1, sticky="NESW")

        address = tk.Entry(label_frame, width=30)
        address.grid(column=1, row=2, sticky="NESW")

        phone = tk.Entry(label_frame, width=30)
        phone.grid(column=1, row=3, sticky="NESW")

        contact = tk.Entry(label_frame, width=30)
        contact.grid(column=1, row=4, sticky="NESW")

        return [[name_label, address_label, phone_label, contact_label],
                [combobox, name, address, phone, contact]]

    def draw_dates(self, pos_x, pos_y, span_x, span_y):
        # ui for date widget
        self.label_frame_dates = tk.LabelFrame(text="About Dates")
        self.label_frame_dates.grid(column=pos_x,
                                    row=pos_y,
                                    columnspan=span_x,
                                    rowspan=span_y,
                                    padx=10,
                                    pady=10,
                                    sticky="NEW")

        # date labels

        self.date_client = tk.Label(self.label_frame_dates,
                                    text="Client",
                                    font=BASICFONT)
        self.date_client.grid(column=0, row=0, sticky="W")
        self.date_required = tk.Label(self.label_frame_dates,
                                      text="Requested",
                                      font=BASICFONT)
        self.date_required.grid(column=0, row=1, sticky="w")
        self.date_ship = tk.Label(self.label_frame_dates,
                                  text="Shipment",
                                  font=BASICFONT)
        self.date_ship.grid(column=0, row=2, sticky="w")

        self.entry_client = DateEntry(self.label_frame_dates, font=ENTRYFONT)
        self.entry_client.grid(column=1, row=0, sticky="w")

        self.entry_required = DateEntry(self.label_frame_dates, font=ENTRYFONT)
        self.entry_required.grid(column=1, row=1, sticky="w")

        self.entry_ship = DateEntry(self.label_frame_dates, font=ENTRYFONT)
        self.entry_ship.grid(column=1, row=2, sticky="w")

    def draw_tasks(self, length, pos_x, pos_y, span_x, span_y):
        """
        draws tasks in this format Task:
            goal(string)  |  checkbox(bool)  |  target date(date)
        :parameter: length: (integer) tells how any tasks to draw

        """
        self.tasks = []
        self.label_frame_tasks = tk.LabelFrame(text="Tasks")
        self.label_frame_tasks.grid(column=pos_x,
                                    row=pos_y,
                                    columnspan=span_x,
                                    rowspan=span_y,
                                    padx=10,
                                    pady=10)
        self.task_label = tk.Label(self.label_frame_tasks, text="Tasks")
        self.task_label.grid(column=0, row=0)
        self.done_label = tk.Label(self.label_frame_tasks, text="Done")
        self.done_label.grid(column=1, row=0)
        self.task_date_label = tk.Label(self.label_frame_tasks, text="Date")
        self.task_date_label.grid(column=2, row=0)
        self.task_date_must_label = tk.Label(self.label_frame_tasks,
                                             text="Must Date")
        self.task_date_must_label.grid(column=3, row=0)
        for i in range(0, length):
            entry = tk.Entry(self.label_frame_tasks, width="75")
            entry.grid(column=0, row=i + 1)

            check = tk.BooleanVar()
            check_button = tk.Checkbutton(self.label_frame_tasks, var=check)
            check_button.grid(column=1, row=i + 1)

            date = DateEntry(self.label_frame_tasks, width="25")
            date.grid(column=2, row=i + 1)
            date.configure(state="readonly")
            date_must = DateEntry(self.label_frame_tasks, width="25")
            date_must.grid(column=3, row=i + 1)
            date_must.configure(state="readonly")
            self.tasks.append([entry, check_button, date, check, date_must])

    def draw_notes(self, pos_x, pos_y, span_x, span_y):

        self.notes_frame = tk.LabelFrame(text="Notes")
        self.notes_frame.grid(column=pos_x,
                              row=pos_y,
                              columnspan=span_x,
                              rowspan=span_y,
                              sticky="NESW")
        self.notes = tk.Text(self.notes_frame,
                             height=9,
                             width=35,
                             font=ENTRYFONT)

        self.notes.grid(column=0, row=0)

    def update_customer_info(self, event):
        data = request_partner_info(CUSTOMER_DB,
                                    self.customer_info[1][0].get())
        if data is None:
            pass
        else:
            self.activate_info_entries(CUSTOMER)
            for n, d in data:
                self.customer_info[1][n + 1].delete(0, tk.END)
                self.customer_info[1][n + 1].insert(0, str(d))
            self.deactivate_info_entries(CUSTOMER, include=False)
            # return [[name_label, address_label, phone_label, contact_label],
            # [combobox, name, address, phone, contact]]

    def update_customer_combobox(self):
        """
        updates info on customer frame
        """
        tmp = []
        for i in request_partners(CUSTOMER_DB):
            tmp.append(i["name"])
        self.customer_info[1][0].configure(values=tmp)

    def update_vendor_combobox(self):
        tmp = []
        for i in request_partners(VENDOR_DB):
            tmp.append(i["name"])
        self.vendor_info[1][0].configure(values=tmp)

    def update_vendor_info(self, event):
        data = request_partner_info(VENDOR_DB, self.vendor_info[1][0].get())
        if data is None:
            pass
        else:
            self.activate_info_entries(VENDOR)
            for n, d in enumerate(data):
                self.vendor_info[1][n + 1].delete(0, tk.END)
                self.vendor_info[1][n + 1].insert(1, str(d))
            self.deactivate_info_entries(VENDOR, include=False)

    def update_by_docket(self, event, docket=None):
        # this method parses widget text because of the explained below
        """
            found intersting bug(probably just the thing that not all people know) in python
            if you bind label(may work with other widgets) in a loop(which uses range(0,somenumber))
            with the callback the last value of i or other iterator will be passed to function!
        """

        self.set_active()
        self.clear_tasks()

        # docket, customer, vendor, completed_tasks, date_client, date_require,
        # date_shipment, tasks, note, delivery address
        data = None
        if docket is None:
            docket = int(event.widget["text"].split("\n")[0].split(" ")[2])
            data = request_by_docket(docket)
        else:
            data = request_by_docket(docket)
        if data is None:
            # create a message that will say that something wrong was inputed
            self.clear_entries()
            self.clear_by_partner(CUSTOMER)
            self.clear_by_partner(VENDOR)
            self.clear_tasks()

        else:
            print(data)
            func = lambda: update_docket(docket, self.read_tasks())
            self.btn_submit.configure(command=func)
            # fields in dictionary are the same as fields in docket
            # update customer info
            self.customer_info[1][0].current(
                self.customer_info[1][0]["values"].index((data["customer"])))
            self.update_customer_info(None)
            # none instead of event as update does
            # not depend on event variables
            # update vendor info
            self.vendor_info[1][0].current(
                self.vendor_info[1][0]["values"].index((data["vendor"])))
            self.update_vendor_info(None)
            # update dates

            self.insert_dates([
                data["date_client"], data["date_request"], data["date_shipmet"]
            ])

            # update tasks dont forget that
            # at some point it should turn from bytes -> tuple -> string

            self.update_tasks(data["tasks"])
            # update notes
            self.update_notes(data["note"])
            # update delivery address
            self.update_delivery_address(data["delivery_address"])
        self.readonly_mode()

    def update_notes(self, text):
        self.notes.delete(1.0, tk.END)
        self.notes.insert(1.0, text)

    def update_delivery_address(self, text):
        self.entry_del_address.delete(0, tk.END)
        self.entry_del_address.insert(0, text)

    def readonly_mode(self):
        self.deactivate_info_entries(CUSTOMER)
        self.deactivate_info_entries(VENDOR)
        self.entry_client.configure(state="disabled")
        self.entry_del_address.configure(state="readonly")
        self.entry_required.configure(state="disabled")
        self.entry_ship.configure(state="disabled")
        for i in self.tasks:
            if not i[0].get() and not i[0].get().isspace() and i[0].get(
            ) is not None:
                i[0].configure(state="normal")
                i[2].configure(state="readonly")
                i[1].configure(state="normal")
            else:
                if i[1] == 1:
                    i[1].configure(state="disabled")
                else:
                    i[0].configure(state="normal")
                i[0].configure(state="disabled")
                i[2].configure(state="disabled")

        self.notes.configure(state="disabled")

    def read_tasks(self):
        done_tasks = True
        tasks = ""
        for task, done, date, check, date_must in self.tasks:

            if task.get() and not task.get().isspace() and not (task.get() is
                                                                None):

                if not check.get():
                    done_tasks = False

                if check.get():
                    check = 1
                else:
                    check = 0
                tasks = tasks + "" + task.get() + "|" + str(
                    check) + "|" + date.get() + "|" + date_must.get()
        return [tasks, done_tasks]

    def read_delivery_entries(self):
        # self.update_dockets_list()
        self.btn_submit.configure(command=None)
        self.set_active()
        data = []
        data.append(self.customer_info[1][0].get())
        data.append(self.vendor_info[1][0].get())
        tasks, done = self.read_tasks()
        data.append(done)
        data.append(time_format(self.entry_client.get()))
        data.append(time_format(self.entry_required.get()))
        data.append(time_format(self.entry_ship.get()))
        data.append(tasks)
        data.append(self.notes.get(1.0, tk.END))
        data.append(self.entry_del_address.get())
        self.readonly_mode()
        submit_delivery(data)

    def after_action_update(self):
        self.update_customer_combobox()
        self.update_vendor_combobox()

    def insert_dates(self, dates):
        self.entry_client.delete(0, tk.END)
        self.entry_ship.delete(0, tk.END)
        self.entry_required.delete(0, tk.END)

        self.entry_client.insert(0, dates[0])
        self.entry_required.insert(0, dates[1])
        self.entry_ship.insert(0, dates[2])

    def clear_tasks(self):
        for i in self.tasks:
            i[0].delete(0, tk.END)
            i[1].deselect()
            i[2].delete(0, tk.END)

    def clear_entries(self):
        self.insert_dates([0, 0, 0])
        self.entry_client.delete(0, tk.END)
        self.entry_del_address.delete(0, tk.END)
        self.entry_required.delete(0, tk.END)
        self.entry_ship.delete(0, tk.END)
        self.clear_tasks()
        self.notes.delete(1.0, tk.END)
        self.vendor_info[1][0].current(0)
        self.customer_info[1][0].current(0)

    def clear_by_partner(self, partner):
        if partner == CUSTOMER:
            for i in self.vendor_info[1]:
                i.delete(0, tk.END)
        if partner == VENDOR:
            for i in self.customer_info[1]:
                i.delete(0, tk.END)

    def set_active(self):
        self.activate_info_entries(CUSTOMER)
        self.activate_info_entries(VENDOR)
        self.entry_client.configure(state="readonly")
        self.entry_del_address.configure(state="normal")
        self.entry_required.configure(state="readonly")
        self.entry_ship.configure(state="readonly")
        for i in self.tasks:
            i[0].configure(state="normal")
            i[1].configure(state="normal")
            i[2].configure(state="readonly")
        self.notes.configure(state="normal")

    def activate_info_entries(self, partner):
        if partner == CUSTOMER:
            data = self.customer_info[1]
        elif partner == VENDOR:
            data = self.vendor_info[1]
        for i in data[1:]:
            i.configure(state="normal")
        data[0].configure(state="readonly")

    def deactivate_info_entries(self, partner, include=True):
        """
        CHANGE SIMILAR SSTATEMENTS ON THIS
        IF .... CUSOTMER:
            DATA = SELF.CUSTOMER
        FOR I IN DATA:
            ....
        """
        if include:
            if partner == CUSTOMER:
                data = self.customer_info[1]
            elif partner == VENDOR:
                data = self.vendor_info[1]
            for i in data[1:]:
                i.configure(state="disabled")

            data[0].configure(state="disabled")

    def update_tasks(self, text):
        if text is None:
            return None
        text = text.split("\n")
        #text.remove("")
        self.clear_tasks()
        for num, obj in enumerate(text):
            obj = obj.split("|")
            self.tasks[num][0].delete(0, tk.END)
            self.tasks[num][0].insert(0, obj[0])
            self.tasks[num][3].set(int(obj[1]))
            self.tasks[num][2].delete(0, tk.END)
            self.tasks[num][2].insert(0, obj[2])
            self.tasks[num][4].delete(0, tk.END)
            self.tasks[num][4].insert(0, obj[3])

    def read_partner(self, partner):
        self.btn_submit.configure(command=None)
        data = None
        if partner == CUSTOMER:
            data = self.customer_info[1]
        elif partner == VENDOR:
            data = self.vendor_info[1]
        submit_data = []
        for i in data[1:]:
            submit_data.append(str(i.get()))
        submit_partner(submit_data, partner)
        self.clear_entries()
        self.update_customer_combobox()
        self.update_vendor_combobox()

    def new_partner(self, partner):
        self.set_active()
        self.clear_entries()
        self.readonly_mode()
        self.activate_info_entries(VENDOR)
        self.activate_info_entries(CUSTOMER)

        self.clear_by_partner(VENDOR)
        self.clear_by_partner(CUSTOMER)
        if partner == VENDOR:
            self.deactivate_info_entries(CUSTOMER)
        elif partner == CUSTOMER:
            self.deactivate_info_entries(VENDOR)
        self.btn_submit.configure(command=lambda: self.read_partner(partner))
Пример #17
0
class ViewSalesForm(MainForm):
    def __init__(self):
        super().__init__()

        self.window.title("SS Fashion Tuty - View Sales")

        # variables
        self.selected_row = list()
        self.product_name_list = list()
        self.product_type_list = list()
        self.product_size_list = list()
        self.product_sell_price_list = list()
        self.billno_list = list()

        # widgets
        self.ety_filter_product_name = None
        self.ety_filter_product_type = None
        self.ety_filter_product_size = None
        self.ety_filter_product_sell_price = None
        self.ety_filter_bill_number = None
        self.ety_filter_product_code_1 = None
        self.ety_filter_product_code_2 = None
        self.ety_filter_product_code_3 = None
        self.ety_filter_product_code_4 = None
        self.sales_tree = None
        self.from_date = None
        self.to_date = None
        self.sales_from_date = None
        self.sales_to_date = None

        # widget variables
        self.var_sales_date = tk.StringVar()
        self.var_bill_number = tk.StringVar()
        self.var_product_code = tk.StringVar()
        self.var_product_name = tk.StringVar()
        self.var_product_type = tk.StringVar()
        self.var_product_size = tk.StringVar()
        self.var_selling_price = tk.DoubleVar()
        self.var_quantity = tk.IntVar()
        self.var_sold_quantity = tk.IntVar()
        self.var_sales_amount = tk.DoubleVar()
        self.var_search_product_code_1 = tk.StringVar()
        self.var_search_product_code_2 = tk.StringVar()
        self.var_search_product_code_3 = tk.StringVar()
        self.var_search_product_code_4 = tk.StringVar()
        self.var_chk_include_date = tk.IntVar()

        self.load_view_sales_form()

    def load_view_sales_form(self):
        for index in range(1, 9):
            self.menubar.entryconfig(index, state=tk.DISABLED)

        self.show_menu(MainForm.is_admin_user)
        self.update_username()

        products = Product.get_product_name_list()
        for product in products:
            self.product_name_list.append(product.product_name)

        products = Product.get_product_type_list()
        for product in products:
            self.product_type_list.append(product.product_type)

        products = Product.get_product_size_list()
        for product in products:
            self.product_size_list.append(product.product_size)

        products = Product.get_product_sell_price_list()
        for product in products:
            self.product_sell_price_list.append(
                str(round(product.selling_price, 2)))

        bills = Sales.get_bill_number_list()
        for bill in bills:
            self.billno_list.append(str(bill.bill_number))

        # ********** Sub Containers *********
        left_container = tk.Frame(self.content_container,
                                  bd=5,
                                  padx=2,
                                  pady=2,
                                  relief=tk.RIDGE,
                                  bg=self.clr_yellow)
        left_container.pack(fill='both', expand=True, side=tk.LEFT)

        right_container = tk.Frame(self.content_container,
                                   padx=2,
                                   relief=tk.RIDGE,
                                   bg=self.clr_yellow)
        right_container.pack(fill='both', expand=True, side=tk.RIGHT)

        # left_container main elements
        button_container = tk.Frame(left_container,
                                    padx=2,
                                    pady=2,
                                    relief=tk.RIDGE,
                                    bg=self.clr_yellow)
        button_container.pack(fill='both', expand=True, side=tk.TOP)

        sales_tree_container = tk.Frame(left_container,
                                        padx=2,
                                        pady=2,
                                        relief=tk.RIDGE,
                                        bg=self.clr_yellow)
        sales_tree_container.pack(fill='both', expand=True, side=tk.TOP)

        # button_container
        date_container = tk.Frame(button_container,
                                  bd=2,
                                  relief=tk.RIDGE,
                                  bg=self.clr_yellow)
        date_container.pack(fill='both', expand=True, anchor='w', side=tk.LEFT)

        name_filter_container = tk.Frame(button_container,
                                         bd=2,
                                         relief=tk.RIDGE,
                                         bg=self.clr_yellow)
        name_filter_container.pack(fill='both',
                                   expand=True,
                                   anchor='w',
                                   side=tk.TOP)

        code_filter_container = tk.Frame(button_container,
                                         bd=2,
                                         relief=tk.RIDGE,
                                         bg=self.clr_yellow)
        code_filter_container.pack(fill='both',
                                   expand=True,
                                   anchor='w',
                                   side=tk.LEFT)

        billno_filter_container = tk.Frame(button_container,
                                           bd=2,
                                           relief=tk.RIDGE,
                                           bg=self.clr_yellow)
        billno_filter_container.pack(fill='both',
                                     expand=True,
                                     anchor='w',
                                     side=tk.RIGHT)

        # ********** button_container elements *********
        date_container.grid_rowconfigure(0, weight=1)
        date_container.grid_rowconfigure(6, weight=1)

        date_container.grid_columnconfigure(0, weight=1)
        date_container.grid_columnconfigure(2, weight=1)

        lbl_from_date = tk.Label(date_container,
                                 text='From Date: ',
                                 bg=self.clr_yellow)
        lbl_from_date.grid(row=1, column=1, sticky="nw", padx=1, pady=1)
        self.from_date = DateEntry(date_container,
                                   date_pattern='yyyy-mm-dd',
                                   background='yellow',
                                   foreground='black',
                                   borderwidth=2,
                                   width=10)
        self.from_date.grid(row=2,
                            column=1,
                            sticky="sw",
                            padx=2,
                            pady=1,
                            ipady=3)

        lbl_to_date = tk.Label(date_container,
                               text='To Date: ',
                               bg=self.clr_yellow)
        lbl_to_date.grid(row=3, column=1, sticky="nw", padx=1, pady=1)
        self.to_date = DateEntry(date_container,
                                 date_pattern='yyyy-mm-dd',
                                 background='yellow',
                                 foreground='black',
                                 borderwidth=2,
                                 width=10)
        self.to_date.grid(row=4,
                          column=1,
                          sticky="sw",
                          padx=2,
                          pady=1,
                          ipady=3)

        include_date = tk.Checkbutton(date_container,
                                      text='Include Date',
                                      variable=self.var_chk_include_date,
                                      onvalue=1,
                                      offvalue=0,
                                      bg=self.clr_yellow)
        include_date.grid(row=5, column=1, sticky="sw", padx=2, pady=1)

        # name_filter_container elements
        name_filter_container.grid_rowconfigure(0, weight=1)
        name_filter_container.grid_rowconfigure(3, weight=1)

        name_filter_container.grid_columnconfigure(0, weight=1)
        name_filter_container.grid_columnconfigure(7, weight=1)

        filter_lbl_product_name = tk.Label(name_filter_container,
                                           text="Name: ",
                                           bg=self.clr_yellow)
        filter_lbl_product_name.grid(row=1,
                                     column=1,
                                     sticky="nw",
                                     padx=1,
                                     pady=1)
        self.ety_filter_product_name = AutocompleteEntry(
            name_filter_container,
            width=15,
            completevalues=self.product_name_list)
        self.ety_filter_product_name.grid(row=2,
                                          column=1,
                                          sticky="nw",
                                          padx=2,
                                          pady=1,
                                          ipady=6)
        self.ety_filter_product_name.bind(
            "<Return>", lambda event: self.filter_product(event))

        filter_lbl_product_type = tk.Label(name_filter_container,
                                           text="Type: ",
                                           bg=self.clr_yellow)
        filter_lbl_product_type.grid(row=1,
                                     column=2,
                                     sticky="nw",
                                     padx=1,
                                     pady=1)
        self.ety_filter_product_type = AutocompleteEntry(
            name_filter_container,
            width=20,
            completevalues=self.product_type_list)
        self.ety_filter_product_type.grid(row=2,
                                          column=2,
                                          sticky="nw",
                                          padx=2,
                                          pady=1,
                                          ipady=6)
        self.ety_filter_product_type.bind(
            "<Return>", lambda event: self.filter_product(event))

        filter_lbl_product_size = tk.Label(name_filter_container,
                                           text="Size: ",
                                           bg=self.clr_yellow)
        filter_lbl_product_size.grid(row=1,
                                     column=3,
                                     sticky="nw",
                                     padx=1,
                                     pady=1)
        self.ety_filter_product_size = AutocompleteEntry(
            name_filter_container,
            width=8,
            completevalues=self.product_size_list)
        self.ety_filter_product_size.grid(row=2,
                                          column=3,
                                          sticky="nw",
                                          padx=2,
                                          pady=1,
                                          ipady=6)
        self.ety_filter_product_size.bind(
            "<Return>", lambda event: self.filter_product(event))

        filter_lbl_product_price = tk.Label(name_filter_container,
                                            text="Price: ",
                                            bg=self.clr_yellow)
        filter_lbl_product_price.grid(row=1,
                                      column=4,
                                      sticky="nw",
                                      padx=1,
                                      pady=1)
        self.ety_filter_product_sell_price = AutocompleteEntry(
            name_filter_container,
            width=8,
            completevalues=self.product_sell_price_list)
        self.ety_filter_product_sell_price.grid(row=2,
                                                column=4,
                                                sticky="nw",
                                                padx=2,
                                                pady=1,
                                                ipady=6)
        self.ety_filter_product_sell_price.bind(
            "<Return>", lambda event: self.filter_product(event))

        btn_filter = tk.Button(name_filter_container,
                               text="Apply Filter",
                               bg=self.clr_fuchsia,
                               fg='white',
                               command=self.filter_product)
        btn_filter.grid(row=2, column=5, sticky="sw", padx=2, pady=1)

        btn_clear_filter = tk.Button(name_filter_container,
                                     text="Clear Filter",
                                     command=self.reload_sales)
        btn_clear_filter.grid(row=2, column=6, sticky="news", padx=2, pady=1)

        code_filter_container.grid_rowconfigure(0, weight=1)
        code_filter_container.grid_rowconfigure(3, weight=1)
        code_filter_container.grid_columnconfigure(0, weight=1)
        code_filter_container.grid_columnconfigure(7, weight=1)

        lbl_search_product_code = tk.Label(code_filter_container,
                                           text="Product Code: ",
                                           bg=self.clr_yellow)
        lbl_search_product_code.grid(row=1,
                                     column=1,
                                     columnspan=3,
                                     sticky="nw",
                                     padx=1,
                                     pady=1)

        self.ety_filter_product_code_1 = MaxLengthEntry(
            code_filter_container,
            maxlength=3,
            width=4,
            textvariable=self.var_search_product_code_1)
        self.ety_filter_product_code_1.grid(row=2,
                                            column=1,
                                            sticky="nw",
                                            padx=2,
                                            pady=2,
                                            ipady=5)
        self.ety_filter_product_code_1.bind(
            '<Return>', lambda event: self.validate_entry(event, 3))

        self.ety_filter_product_code_2 = MaxLengthEntry(
            code_filter_container,
            maxlength=3,
            width=4,
            textvariable=self.var_search_product_code_2)
        self.ety_filter_product_code_2.grid(row=2,
                                            column=2,
                                            sticky="nw",
                                            padx=2,
                                            pady=2,
                                            ipady=5)
        self.ety_filter_product_code_2.bind(
            '<Return>', lambda event: self.validate_entry(event, 3))

        self.ety_filter_product_code_3 = MaxLengthEntry(
            code_filter_container,
            maxlength=2,
            width=3,
            textvariable=self.var_search_product_code_3)
        self.ety_filter_product_code_3.grid(row=2,
                                            column=3,
                                            sticky="nw",
                                            padx=2,
                                            pady=2,
                                            ipady=5)
        self.ety_filter_product_code_3.bind(
            '<Return>', lambda event: self.validate_entry(event, 2))

        self.ety_filter_product_code_4 = MaxLengthEntry(
            code_filter_container,
            maxlength=4,
            width=5,
            textvariable=self.var_search_product_code_4)
        self.ety_filter_product_code_4.grid(row=2,
                                            column=4,
                                            sticky="nw",
                                            padx=2,
                                            pady=2,
                                            ipady=5)
        self.ety_filter_product_code_4.bind(
            '<Return>', lambda event: self.validate_entry(event, 4))

        btn_filter_product_code = tk.Button(code_filter_container,
                                            text="Apply Filter",
                                            bg=self.clr_fuchsia,
                                            fg='white',
                                            command=self.filter_product_code)
        btn_filter_product_code.grid(row=2,
                                     column=5,
                                     sticky="sw",
                                     padx=2,
                                     pady=1)
        btn_filter_product_code.bind(
            '<Return>', lambda event: self.filter_product_code(event))

        btn_clear_filter = tk.Button(code_filter_container,
                                     text="Clear Filter",
                                     command=self.reload_sales)
        btn_clear_filter.grid(row=2, column=6, sticky="news", padx=2, pady=1)

        # billno_filter_container elements
        billno_filter_container.grid_rowconfigure(0, weight=1)
        billno_filter_container.grid_rowconfigure(3, weight=1)
        billno_filter_container.grid_columnconfigure(0, weight=1)
        billno_filter_container.grid_columnconfigure(4, weight=1)

        filter_lbl_bill_number = tk.Label(billno_filter_container,
                                          text="Bill No: ",
                                          bg=self.clr_yellow)
        filter_lbl_bill_number.grid(row=1,
                                    column=1,
                                    sticky="nw",
                                    padx=1,
                                    pady=1)
        self.ety_filter_bill_number = AutocompleteEntry(
            billno_filter_container, width=8, completevalues=self.billno_list)
        self.ety_filter_bill_number.grid(row=2,
                                         column=1,
                                         sticky="nw",
                                         padx=2,
                                         pady=1,
                                         ipady=6)
        self.ety_filter_bill_number.bind(
            "<Return>", lambda event: self.filter_bill_number(event))

        btn_apply_filter = tk.Button(billno_filter_container,
                                     text="Apply Filter",
                                     bg=self.clr_fuchsia,
                                     fg='white',
                                     command=self.filter_bill_number)
        btn_apply_filter.grid(row=2, column=2, sticky="news", padx=2, pady=1)
        btn_apply_filter.bind('<Return>',
                              lambda event: self.filter_bill_number(event))

        btn_clear_filter = tk.Button(billno_filter_container,
                                     text="Clear Filter",
                                     command=self.reload_sales)
        btn_clear_filter.grid(row=2, column=3, sticky="news", padx=2, pady=1)

        # ********** tree_containers elements *********
        header = ('SALES_DATE', 'BILL_NO', 'PRODUCT_CODE', 'PRODUCT_NAME',
                  'PRODUCT_TYPE', 'SIZE', 'PRICE', 'QTY', '')
        self.sales_tree = ttk.Treeview(sales_tree_container,
                                       columns=header,
                                       height=20,
                                       show="headings",
                                       selectmode="browse")
        vsb = ttk.Scrollbar(sales_tree_container,
                            orient="vertical",
                            command=self.sales_tree.yview)
        hsb = ttk.Scrollbar(sales_tree_container,
                            orient="horizontal",
                            command=self.sales_tree.xview)

        self.sales_tree.configure(yscrollcommand=vsb.set,
                                  xscrollcommand=hsb.set)
        style = ttk.Style()
        style.configure("Treeview.Heading", font=('Calibri', 12))
        style.configure("Treeview", font=('Calibri', 12), rowheight=25)

        self.sales_tree.configure(yscrollcommand=vsb.set,
                                  xscrollcommand=hsb.set)
        self.sales_tree.grid(column=0,
                             row=0,
                             sticky='nsew',
                             in_=sales_tree_container)

        vsb.grid(column=1, row=0, sticky='ns', in_=sales_tree_container)
        hsb.grid(column=0, row=1, sticky='ew', in_=sales_tree_container)

        sales_tree_container.grid_columnconfigure(0, weight=1)
        sales_tree_container.grid_rowconfigure(0, weight=1)

        self.sales_tree.heading("0", text="SALES_DATE")
        self.sales_tree.heading("1", text="BILL_NO")
        self.sales_tree.heading("2", text="PRODUCT_CODE")
        self.sales_tree.heading("3", text="PRODUCT_NAME")
        self.sales_tree.heading("4", text="PRODUCT_TYPE")
        self.sales_tree.heading("5", text="SIZE")
        self.sales_tree.heading("6", text="PRICE")
        self.sales_tree.heading("7", text="QTY")

        self.sales_tree.column(0, anchor=tk.W, width="140")
        self.sales_tree.column(1, anchor=tk.W, width="80")
        self.sales_tree.column(2, anchor=tk.W, width="120")
        self.sales_tree.column(3, anchor=tk.W, width="140")
        self.sales_tree.column(4, anchor=tk.W, width="180")
        self.sales_tree.column(5, anchor='center', width="50")
        self.sales_tree.column(6, anchor=tk.E, width="80")
        self.sales_tree.column(7, anchor='center', width="50")
        self.sales_tree.column(8, anchor='center', width="2")

        self.reload_sales()

        numeric_cols = ['BILL_NO', 'PRICE', 'QTY']
        for col in header:
            if col in numeric_cols:
                self.sales_tree.heading(col,
                                        text=col,
                                        command=lambda _col=col: self.
                                        sort_treeview(self.sales_tree,
                                                      _col,
                                                      numeric_sort=True,
                                                      reverse=False))
            else:
                self.sales_tree.heading(col,
                                        text=col,
                                        command=lambda _col=col: self.
                                        sort_treeview(self.sales_tree,
                                                      _col,
                                                      numeric_sort=False,
                                                      reverse=False))

        self.sales_tree.tag_configure("evenrow", background='#fbefcc')
        self.sales_tree.tag_configure("oddrow",
                                      background='white',
                                      foreground='black')
        self.sales_tree.bind('<<TreeviewSelect>>', self.on_tree_select)

        # ********** Sales Details *********
        sales_details_container = tk.Frame(right_container,
                                           bd=5,
                                           pady=3,
                                           padx=10,
                                           relief=tk.RIDGE,
                                           bg=self.clr_yellow)
        sales_details_container.pack(fill='both', expand=True, side=tk.TOP)

        sales_stats_container = tk.Frame(right_container,
                                         bd=5,
                                         pady=3,
                                         padx=10,
                                         relief=tk.RIDGE,
                                         bg=self.clr_yellow)
        sales_stats_container.pack(fill='both',
                                   expand=True,
                                   side=tk.TOP,
                                   anchor='center')

        sales_details_container.grid_columnconfigure(0, weight=1)
        sales_details_container.grid_columnconfigure(3, weight=1)

        lbl_product_details = tk.Label(sales_details_container,
                                       text="Sales Details",
                                       bg=self.clr_blueiris,
                                       fg="white")
        lbl_product_details.grid(row=0,
                                 column=1,
                                 columnspan=2,
                                 sticky="news",
                                 padx=3,
                                 pady=3)
        lbl_product_details.config(font=("Calibri bold", 14))

        lbl_sales_date = tk.Label(sales_details_container,
                                  text="Sales Date: ",
                                  bg=self.clr_yellow)
        lbl_sales_date.grid(row=1, column=1, sticky="nw", padx=3, pady=1)
        ety_sales_date = tk.Entry(sales_details_container,
                                  textvariable=self.var_sales_date,
                                  state='disabled')
        ety_sales_date.grid(row=1, column=2, sticky="nw", padx=3, pady=1)

        lbl_bill_number = tk.Label(sales_details_container,
                                   text="Bill No: ",
                                   bg=self.clr_yellow)
        lbl_bill_number.grid(row=2, column=1, sticky="nw", padx=3, pady=1)
        ety_bill_number = tk.Entry(sales_details_container,
                                   width=8,
                                   textvariable=self.var_bill_number,
                                   state='disabled')
        ety_bill_number.grid(row=2,
                             column=2,
                             columnspan=2,
                             sticky="nw",
                             padx=3,
                             pady=1)

        lbl_product_code = tk.Label(sales_details_container,
                                    text="Product Code: ",
                                    bg=self.clr_yellow)
        lbl_product_code.grid(row=3, column=1, sticky="nw", padx=3, pady=1)
        ety_product_code = tk.Entry(sales_details_container,
                                    width=15,
                                    textvariable=self.var_product_code,
                                    state='disabled')
        ety_product_code.grid(row=3,
                              column=2,
                              columnspan=2,
                              sticky="nw",
                              padx=3,
                              pady=1)

        lbl_product_name = tk.Label(sales_details_container,
                                    text="Product Name: ",
                                    bg=self.clr_yellow)
        lbl_product_name.grid(row=4, column=1, sticky="nw", padx=3, pady=1)
        ety_product_name = tk.Entry(sales_details_container,
                                    textvariable=self.var_product_name,
                                    state='disabled')
        ety_product_name.grid(row=4,
                              column=2,
                              columnspan=2,
                              sticky="nw",
                              padx=3,
                              pady=1)

        lbl_product_type = tk.Label(sales_details_container,
                                    text="Product Type: ",
                                    bg=self.clr_yellow)
        lbl_product_type.grid(row=5, column=1, sticky="nw", padx=3, pady=1)
        ety_product_type = tk.Entry(sales_details_container,
                                    textvariable=self.var_product_type,
                                    state='disabled')
        ety_product_type.grid(row=5,
                              column=2,
                              columnspan=2,
                              sticky="nw",
                              padx=3,
                              pady=1)

        lbl_product_size = tk.Label(sales_details_container,
                                    text="Size: ",
                                    bg=self.clr_yellow)
        lbl_product_size.grid(row=6, column=1, sticky="nw", padx=3, pady=1)
        ety_product_size = tk.Entry(sales_details_container,
                                    width=12,
                                    textvariable=self.var_product_size,
                                    state='disabled')
        ety_product_size.grid(row=6,
                              column=2,
                              columnspan=2,
                              sticky="nw",
                              padx=3,
                              pady=1)

        lbl_selling_price = tk.Label(sales_details_container,
                                     text="Price: ",
                                     bg=self.clr_yellow)
        lbl_selling_price.grid(row=7, column=1, sticky="nw", padx=3, pady=1)
        ety_selling_price = tk.Entry(sales_details_container,
                                     width=8,
                                     textvariable=self.var_selling_price,
                                     state='disabled')
        ety_selling_price.grid(row=7, column=2, sticky="nw", padx=3, pady=1)

        lbl_quantity = tk.Label(sales_details_container,
                                text="Quantity: ",
                                bg=self.clr_yellow)
        lbl_quantity.grid(row=8, column=1, sticky="nw", padx=3, pady=1)
        ety_quantity = tk.Entry(sales_details_container,
                                width=5,
                                textvariable=self.var_quantity,
                                state='disabled')
        ety_quantity.grid(row=8, column=2, sticky="nw", padx=3, pady=1)

        # sales_stats_container element
        sales_stats_container.grid_columnconfigure(0, weight=1)
        sales_stats_container.grid_columnconfigure(3, weight=1)

        lbl_sales_stats = tk.Label(sales_stats_container,
                                   text="Sales Stats",
                                   bg=self.clr_blueiris,
                                   fg="white")
        lbl_sales_stats.grid(row=0,
                             column=1,
                             columnspan=2,
                             sticky="news",
                             padx=3,
                             pady=5)
        lbl_sales_stats.config(font=("Calibri bold", 14))

        lbl_from_date = tk.Label(sales_stats_container,
                                 text='From Date: ',
                                 bg=self.clr_yellow)
        lbl_from_date.grid(row=1, column=1, sticky="nw", padx=1, pady=5)
        self.sales_from_date = DateEntry(sales_stats_container,
                                         date_pattern='yyyy-mm-dd',
                                         background='yellow',
                                         foreground='black',
                                         borderwidth=2,
                                         width=10)
        self.sales_from_date.grid(row=1,
                                  column=2,
                                  sticky="sw",
                                  padx=2,
                                  pady=5,
                                  ipady=3)

        lbl_to_date = tk.Label(sales_stats_container,
                               text='To Date: ',
                               bg=self.clr_yellow)
        lbl_to_date.grid(row=2, column=1, sticky="nw", padx=1, pady=5)
        self.sales_to_date = DateEntry(sales_stats_container,
                                       date_pattern='yyyy-mm-dd',
                                       background='yellow',
                                       foreground='back',
                                       borderwidth=2,
                                       width=10)
        self.sales_to_date.grid(row=2,
                                column=2,
                                sticky="sw",
                                padx=2,
                                pady=5,
                                ipady=3)

        lbl_sold_quantity = tk.Label(sales_stats_container,
                                     text="Quantity: ",
                                     bg=self.clr_yellow)
        lbl_sold_quantity.grid(row=3, column=1, sticky="nw", padx=3, pady=5)
        ety_sold_quantity = tk.Entry(sales_stats_container,
                                     width=5,
                                     textvariable=self.var_sold_quantity,
                                     state='disabled')
        ety_sold_quantity.grid(row=3, column=2, sticky="nw", padx=3, pady=5)

        lbl_sales_amount = tk.Label(sales_stats_container,
                                    text="Amount: ",
                                    bg=self.clr_yellow)
        lbl_sales_amount.grid(row=4, column=1, sticky="nw", padx=3, pady=5)
        ety_sales_amount = tk.Entry(sales_stats_container,
                                    width=10,
                                    textvariable=self.var_sales_amount,
                                    state='disabled')
        ety_sales_amount.grid(row=4, column=2, sticky="nw", padx=3, pady=5)

        btn_get_sales_data = tk.Button(sales_stats_container,
                                       text="Get Sales Data",
                                       bg=self.clr_fuchsia,
                                       fg='white',
                                       command=self.get_sales_data)
        btn_get_sales_data.grid(row=5,
                                column=1,
                                columnspan=2,
                                sticky="news",
                                padx=2,
                                pady=5)
        btn_get_sales_data.bind('<Return>',
                                lambda event: self.get_sales_data(event))

    def get_sales_data(self, event=None):
        from_date = self.sales_from_date.get()
        to_date = self.sales_to_date.get()

        sold_quantity, total_sales_amount = Sales.get_sales_data(
            from_date=from_date, to_date=to_date)
        if sold_quantity is None:
            sold_quantity = 0

        if total_sales_amount is None:
            total_sales_amount = 0

        self.var_sold_quantity.set(sold_quantity)
        self.var_sales_amount.set(
            format_currency(total_sales_amount, 'INR', locale='en_IN'))

    @staticmethod
    def validate_entry(event=None, length=0):
        if len(event.widget.get().strip()) == length:
            event.widget.tk_focusNext().focus()

    def filter_product(self, event=None):
        product_name = self.ety_filter_product_name.get().strip()
        product_type = self.ety_filter_product_type.get().strip()
        product_size = self.ety_filter_product_size.get().strip()
        selling_price = str(self.ety_filter_product_sell_price.get().strip())
        if selling_price:
            selling_price = float(selling_price)
        else:
            selling_price = 0.0

        if self.var_chk_include_date.get():
            rows = Sales.search_sales(from_date=self.from_date.get(),
                                      to_date=self.to_date.get(),
                                      product_name=product_name,
                                      product_type=product_type,
                                      product_size=product_size,
                                      selling_price=selling_price)
        else:
            rows = Sales.search_sales(product_name=product_name,
                                      product_type=product_type,
                                      product_size=product_size,
                                      selling_price=selling_price)

        self.sales_tree.delete(*self.sales_tree.get_children())

        sl_no = 0
        for row in rows:
            product = row.Product
            sale = row.Sales

            sl_no = sl_no + 1
            rw = (datetime.strftime(sale.sales_date, '%d-%b-%Y %H:%M:%S'),
                  sale.bill_number, sale.product_code, product.product_name,
                  product.product_type, product.product_size,
                  round(product.selling_price, 2), sale.quantity)

            if sl_no % 2 == 0:
                self.sales_tree.insert("",
                                       tk.END,
                                       values=rw,
                                       tags=('evenrow', sale.product_code))
            else:
                self.sales_tree.insert("",
                                       tk.END,
                                       values=rw,
                                       tags=('oddrow', sale.product_code))

    def filter_bill_number(self, event=None):
        bill_number = self.ety_filter_bill_number.get().strip()
        if bill_number and bill_number != "":
            rows = Sales.search_bill_number(bill_number=bill_number)

            if len(rows) == 0:
                messagebox.showerror("SS Fashion Tuty",
                                     f"Bill_number: {bill_number} not found!")
                print(f"Bill_number: {bill_number} not found!")
            else:
                self.sales_tree.delete(*self.sales_tree.get_children())

                sl_no = 0
                for row in rows:
                    product = row.Product
                    sale = row.Sales

                    sl_no = sl_no + 1
                    rw = (datetime.strftime(sale.sales_date,
                                            '%d-%b-%Y %H:%M:%S'),
                          sale.bill_number, sale.product_code,
                          product.product_name, product.product_type,
                          product.product_size, round(product.selling_price,
                                                      2), sale.quantity)

                    if sl_no % 2 == 0:
                        self.sales_tree.insert("",
                                               tk.END,
                                               values=rw,
                                               tags=('evenrow',
                                                     sale.product_code))
                    else:
                        self.sales_tree.insert("",
                                               tk.END,
                                               values=rw,
                                               tags=('oddrow',
                                                     sale.product_code))
        else:
            self.reload_sales()

    def filter_product_code(self, event=None):
        product_code = f"{self.ety_filter_product_code_1.get().strip()}" \
                       f"-{self.ety_filter_product_code_2.get().strip()}" \
                       f"-{self.ety_filter_product_code_3.get().strip()}" \
                       f"-{self.ety_filter_product_code_4.get().strip()}"

        if product_code != "---":
            if self.var_chk_include_date.get():
                rows = Sales.search_product_code(
                    product_code=product_code,
                    from_date=self.from_date.get(),
                    to_date=self.to_date.get(),
                )
            else:
                rows = Sales.search_product_code(product_code=product_code)

            if rows is None:
                messagebox.showerror(
                    "SS Fashion Tuty",
                    f"Product_code: {product_code} not found!")
                print(f"Product_code: {product_code} not found!")
            else:
                self.sales_tree.delete(*self.sales_tree.get_children())

                sl_no = 0
                for row in rows:
                    product = row.Product
                    sale = row.Sales

                    sl_no = sl_no + 1
                    rw = (datetime.strftime(sale.sales_date,
                                            '%d-%b-%Y %H:%M:%S'),
                          sale.bill_number, sale.product_code,
                          product.product_name, product.product_type,
                          product.product_size, round(product.selling_price,
                                                      2), sale.quantity)

                    if sl_no % 2 == 0:
                        self.sales_tree.insert("",
                                               tk.END,
                                               values=rw,
                                               tags=('evenrow',
                                                     sale.product_code))
                    else:
                        self.sales_tree.insert("",
                                               tk.END,
                                               values=rw,
                                               tags=('oddrow',
                                                     sale.product_code))

    def reload_sales(self):
        self.ety_filter_product_name.delete(0, tk.END)
        self.ety_filter_product_type.delete(0, tk.END)
        self.ety_filter_product_size.delete(0, tk.END)
        self.ety_filter_product_sell_price.delete(0, tk.END)

        self.ety_filter_product_code_1.delete(0, tk.END)
        self.ety_filter_product_code_2.delete(0, tk.END)
        self.ety_filter_product_code_3.delete(0, tk.END)
        self.ety_filter_product_code_4.delete(0, tk.END)

        self.ety_filter_bill_number.delete(0, tk.END)

        self.sales_tree.delete(*self.sales_tree.get_children())

        rows = Sales.get_all_sales()
        sl_no = 0
        for row in rows:
            product = row.Product
            sale = row.Sales

            sl_no = sl_no + 1
            rw = (datetime.strftime(sale.sales_date, '%d-%b-%Y %H:%M:%S'),
                  sale.bill_number, sale.product_code, product.product_name,
                  product.product_type, product.product_size,
                  round(product.selling_price, 2), sale.quantity)

            if sl_no % 2 == 0:
                self.sales_tree.insert("",
                                       tk.END,
                                       values=rw,
                                       tags=('evenrow', sale.product_code))
            else:
                self.sales_tree.insert("",
                                       tk.END,
                                       values=rw,
                                       tags=('oddrow', sale.product_code))

    def on_tree_select(self, event):
        self.selected_row = event.widget.selection()

        sales = self.sales_tree.item(self.selected_row)['values']

        if sales:
            self.var_sales_date.set(sales[0])
            self.var_bill_number.set(sales[1])
            self.var_product_code.set(sales[2])
            self.var_product_name.set(sales[3])
            self.var_product_type.set(sales[4])
            self.var_product_size.set(sales[5])
            self.var_selling_price.set(sales[6])
            self.var_quantity.set(sales[7])
Пример #18
0
class oneway:
    def __init__(self, user, window):

        self.search_by = StringVar()

        self.search_txt = StringVar()
        self.list2 = [{
            'name': 'Select',
            'price': []
        }, {
            'name': 'Economy',
            'price': 3000
        }, {
            'name': 'Premium Economy',
            'price': 4000
        }, {
            'name': 'Business Class',
            'price': 5000
        }, {
            'name': 'First Class',
            'price': 6000
        }]
        # Get the names of the all flights name

        self.names = list(map(lambda x: x.get('name'), self.list2))

        print(self.names)

        self.window = window
        self.user_id = user
        self.item_index = []
        self.user = user
        self.window.title('User Form')
        self.window.geometry('1100x650+90+40')

        self.frame1 = Frame(self.window, bg='#37474F')
        self.frame1.place(x=0, y=0, height=650, width=1100)
        self.frame2 = Frame(self.frame1, bg='white', bd=1, relief=RIDGE)
        self.frame2.place(x=390, y=130, height=360, width=630)
        self.label_name = Label(self.frame1,
                                text="One Way Flight",
                                font=('Impact', 20, 'bold'),
                                fg="white",
                                bg='#37474F')
        self.label_name.place(x=300, y=15)
        time1 = StringVar()
        time1.set(time.strftime('%H:%M:%S:%p'))
        self.ent_where = Label(self.frame1,
                               font=('times new roman', 25),
                               fg='white',
                               bg='#37474F',
                               textvariable=time1)
        self.ent_where.place(x=60, y=5)

        self.label_name = Label(self.frame1,
                                text="Where From:",
                                font=('Goudy old style', 12, 'bold'),
                                fg='white',
                                bg='#37474F')
        self.label_name.place(x=50, y=90)
        self.ent_where = Entry(self.frame1,
                               font=('times new roman', 9),
                               bg='lightgray')
        self.ent_where.place(x=170, y=90, width=200, height=30)
        self.label_name = Label(self.frame1,
                                text="Where To:",
                                font=('Goudy old style', 12, 'bold'),
                                fg='white',
                                bg='#37474F')
        self.label_name.place(x=50, y=140)
        self.ent_to = Entry(self.frame1,
                            font=('times new roman', 9),
                            bg='lightgray')
        self.ent_to.place(x=170, y=140, width=200, height=30)
        self.label_name = Label(self.frame1,
                                text="Departure Date:",
                                font=('Goudy old style', 12, 'bold'),
                                fg='white',
                                bg='#37474F')
        self.label_name.place(x=50, y=190)
        self.ent_dpt = DateEntry(self.frame1,
                                 width=12,
                                 background='darkblue',
                                 foreground='white',
                                 borderwidth=2)
        self.ent_dpt.place(x=170, y=190, width=200)
        ttk.Button(self.frame1, text="ok")

        self.combo = Label(self.frame1,
                           text="Age Selection:",
                           font=('Goudy old style', 12, 'bold'),
                           fg='white',
                           bg='#37474F').place(x=50, y=240)
        self.txt_combo = ttk.Combobox(self.frame1,
                                      font=('times new roman', 9),
                                      state='readonly',
                                      justify=CENTER)
        self.txt_combo['values'] = ('select', 'Adult', 'Children', 'Infant',
                                    'Old age')

        self.txt_combo.place(x=170, y=240)
        self.txt_combo.current(0)

        self.label_name = Label(self.frame1,
                                text="Count:",
                                font=('Goudy old style', 12, 'bold'),
                                fg='white',
                                bg='#37474F')
        self.label_name.place(x=50, y=290)
        self.ent_count = Entry(self.frame1,
                               font=('times new roman', 9),
                               bg='lightgray')
        self.ent_count.place(x=170, y=290, width=200, height=30)
        self.classcombo = Label(self.frame1,
                                text="Class Selection:",
                                font=('Goudy old style', 12, 'bold'),
                                fg='white',
                                bg='#37474F').place(x=50, y=340)
        self.txt_classcombo = ttk.Combobox(self.frame1,
                                           font=('times new roman', 9),
                                           state='readonly',
                                           justify=CENTER,
                                           values=self.names)
        # self.txt_classcombo['values'] = ('Economy', 'Premium Economy', 'Business Class', 'First Class')
        self.txt_classcombo.bind('<<ComboboxSelected>>', self.fetch_data)

        self.txt_classcombo.place(x=170, y=340)
        self.txt_classcombo.current(0)
        self.label_price = Label(self.frame1,
                                 text="Price:",
                                 font=('Goudy old style', 12, 'bold'),
                                 fg='white',
                                 bg='#37474F')
        self.label_price.place(x=50, y=390)
        self.ent_price = Entry(self.frame1,
                               font=('times new roman', 9),
                               bg='lightgray')
        self.ent_price.place(x=170, y=390, width=200, height=30)
        self.ent_price.insert(0, '')
        self.flight = Label(self.frame1,
                            text="Flight Selection:",
                            font=('Goudy old style', 12, 'bold'),
                            fg='white',
                            bg='#37474F').place(x=50, y=440)
        self.txt_flight = ttk.Combobox(self.frame1,
                                       font=('times new roman', 9),
                                       state='readonly',
                                       justify=CENTER)
        self.txt_flight['values'] = ('select', 'Buddha Air', 'Yeti Airlines',
                                     'Surya Airline', 'Nepal Airlines',
                                     'Tara Airlines')

        self.txt_flight.place(x=170, y=440)
        self.txt_flight.current(0)

        self.item_entry = Entry(self.window, textvariable=self.search_txt)
        self.item_entry.place(x=400, y=90)
        self.txt_combo_1 = ttk.Combobox(self.frame1,
                                        textvariable=self.search_by,
                                        font=('times new roman', 9),
                                        state='readonly',
                                        justify=CENTER)
        self.txt_combo_1['values'] = ('flight_name', 'destination',
                                      'class_selection')

        self.txt_combo_1.place(x=600, y=90)
        self.txt_combo_1.current(0)

        self.btn_add = Button(self.window,
                              text="Search",
                              command=self.Search_items)
        self.btn_add.place(x=800, y=90)

        self.btn_book = Button(self.frame1,
                               text="Book Flight",
                               relief=RAISED,
                               bg='#001C55',
                               font=('arial', 14, 'bold'),
                               fg='white',
                               command=self.book_flight)
        self.btn_book.place(x=100, y=550)
        self.btn_book = Button(self.frame1,
                               text="Cancel Flight",
                               relief=RAISED,
                               bg='#00072D',
                               font=('arial', 14, 'bold'),
                               fg='white',
                               command=self.delete_item)
        self.btn_book.place(x=540, y=550)
        self.btn_book = Button(self.frame1,
                               text="Bill",
                               relief=RAISED,
                               bg='#00072D',
                               font=('arial', 14, 'bold'),
                               fg='white',
                               command=self.generate_bill)
        self.btn_book.place(x=700, y=550)
        self.btn_book = Button(self.frame1,
                               text="Update",
                               relief=RAISED,
                               bg='#00072D',
                               font=('arial', 14, 'bold'),
                               fg='white',
                               command=self.update)
        self.btn_book.place(x=800, y=550)
        scroll_x = Scrollbar(self.frame2, orient=HORIZONTAL)
        self.bg1 = ImageTk.PhotoImage(
            file=
            'C:\\Users\\Dell\\PycharmProjects\\untitled3\\project\\Webp.net-resizeimage (3).png'
        )
        self.btn4 = Button(self.window,
                           image=self.bg1,
                           text='Logout',
                           relief=RAISED,
                           bg='#37474F',
                           font=('arial', 14, 'bold'),
                           fg='white',
                           bd=0,
                           command=exit)
        self.btn4.place(x=1000, y=7, width=90)

        self.item_tree = ttk.Treeview(
            self.frame2,
            selectmode='browse',
            columns=('ID', 'Where from', 'Where to', 'Departure Date',
                     'Age Selection', 'Count', 'Class Selection', 'User_id',
                     'Flight_Name', 'Price'),
            xscrollcommand=scroll_x.set)
        self.item_tree.pack(fill=BOTH, expand=1)
        #self.item_tree.place(x=390,y=120)
        scroll_x.pack(side=BOTTOM, fill=X)
        scroll_x.config(command=self.item_tree.xview)

        self.item_tree['show'] = 'headings'
        self.item_tree.column('ID', width=90, anchor='center')
        self.item_tree.column('Where from', width=90, anchor='center')
        self.item_tree.column('Where to', width=90, anchor='center')
        self.item_tree.column('Departure Date', width=90, anchor='center')

        self.item_tree.column('Age Selection', width=90, anchor='center')
        self.item_tree.column('Count', width=90, anchor='center')
        self.item_tree.column('Class Selection', width=90, anchor='center')
        self.item_tree.column('User_id', width=90, anchor='center')

        self.item_tree.column('Flight_Name', width=90, anchor='center')

        self.item_tree.column('Price', width=90, anchor='center')
        self.item_tree.heading('ID', text="ID")
        self.item_tree.heading('Where from', text="Where from")
        self.item_tree.heading('Where to', text="Where to")
        self.item_tree.heading('Departure Date', text="Departure Date")

        self.item_tree.heading('Age Selection', text="Age Selection")
        self.item_tree.heading('Count', text="Count")
        self.item_tree.heading('Class Selection', text="Class Selection")
        self.item_tree.heading('User_id', text="User ID")
        self.item_tree.heading('Flight_Name', text="Flight_Name")
        self.item_tree.heading('Price', text="Price")

        # scroll_x = Scrollbar(manage_teacher_frame2_1, orient=HORIZONTAL)
        #
        # scroll_x.pack(side=BOTTOM, fill=X)
        # scroll_x.config(command=self.teacher_tree.xview)
        # scroll_y.pack(side=RIGHT, fill=Y)

        # self.item_treeScrollbar=ttk.Scrollbar(self.window,orient='horizontal',command=self.item_tree.xview)
        # self.item_tree.configure(xscroll=self.item_treeScrollbar.set)
        # self.item_treeScrollbar.pack(side=BOTTOM,fill=X)
        self.show_in_treeview()

    def clear(self):
        self.ent_where.delete(0, END)
        self.ent_to.delete(0, END)
        self.ent_dpt.delete(0, END)
        self.txt_combo.set('')
        self.ent_count.delete(0, END)
        self.txt_classcombo.set('')

    # def logout(self):
    #     messagebox.showinfo('Message','Do you want to log out')
    #     import login2
    #     self.window.withdraw()
    #     dd = Toplevel(self.window)
    #
    #     login2.Login(dd)

    def update(self):
        selected_item = self.item_tree.selection()[0]
        self.item_index = self.item_tree.item(selected_item, 'text')
        item_data = self.item_tree.item(selected_item, 'values')

        if item_data[0] == '':
            messagebox.showerror('error', 'select a row')
        else:
            if form2.Item_dlt().update_items(item_data[0],
                                             self.ent_where.get(),
                                             self.ent_to.get(),
                                             self.ent_dpt.get_date(),
                                             self.txt_combo.get(),
                                             self.ent_count.get(),
                                             self.txt_classcombo.get(),
                                             self.txt_flight.get(),
                                             self.ent_price.get(),
                                             self.user_id):
                messagebox.showinfo("Item", "Booking Updated")
                self.show_in_treeview()

            else:
                messagebox.showerror("Error",
                                     "Booking Details cannot be added")

    def book_flight(self):
        if self.ent_where.get() == "" or self.ent_to.get(
        ) == "" or self.ent_dpt.get() == "" or self.txt_combo.get(
        ) == "" or self.ent_count.get() == "" or self.txt_classcombo.get(
        ) == "":
            messagebox.showerror('Error', 'please enter all required fields')

        else:

            try:

                form2.oneway_flight().oneway_reg(self.ent_where.get(),
                                                 self.ent_to.get(),
                                                 self.ent_dpt.get_date(),
                                                 self.txt_combo.get(),
                                                 self.ent_count.get(),
                                                 self.txt_classcombo.get(),
                                                 self.user_id,
                                                 self.txt_flight.get(),
                                                 self.ent_price.get())

                messagebox.showinfo('success',
                                    'Register successfull',
                                    parent=self.window)
                self.show_in_treeview()

                #self.clear()
            except Exception as e:
                messagebox.showerror('error',
                                     f'error:{str(e)}',
                                     parent=self.window)

    def fetch_data(self, *args):

        va = filter(lambda x: x.get('name') == self.txt_classcombo.get(),
                    self.list2)

        self.ent_price.delete(0, END)
        self.ent_price.insert(0, next(va).get('price'))

    def select_item(self, event):
        selected_item = self.item_tree.selection()[0]
        self.item_index = self.item_tree.item(selected_item, 'text')
        item_data = self.item_tree.item(selected_item, 'values')

        self.ent_where.delete(0, END)
        self.ent_where.insert(0, item_data[1])
        self.ent_to.delete(0, END)
        self.ent_to.insert(0, item_data[2])

        #dpt_date_f=datetime.datetime.strptime(int(item_data[2]/3), '%Y-%m-%d').strftime('%m/%d/%y')

        dpt_date = datetime.datetime(int(item_data[3][0:4]),
                                     int(item_data[3][5:7]),
                                     int(item_data[3][8:10]))
        dpt_date_f = dpt_date.strftime('%m/%d/%y')

        self.ent_dpt.set_date(dpt_date_f)

        self.txt_combo.set(item_data[4])
        self.txt_combo.current()

        self.ent_count.delete(0, END)
        self.ent_count.insert(0, item_data[5])
        self.txt_classcombo.set(item_data[6])
        self.txt_classcombo.current()

        self.txt_flight.set(item_data[8])
        self.txt_flight.current()
        self.ent_price.delete(0, END)
        self.ent_price.insert(0, item_data[9])

    def show_in_treeview(self):
        #
        # qry = 'select * from oneway where user_id=%s'
        # self.my_cursor.execute(qry,(self.user_id))
        row = form2.show_flight().show_in_treeview(self.user_id)
        # spot_marker = 0
        # while spot_marker < len(row):
        #     for num in range(spot_marker, len(row)):
        #         if row[num] < row[spot_marker]:
        #             row[spot_marker], row[num] = row[num], row[spot_marker]
        #     spot_marker += 1
        #     print(row)
        if row:

            self.item_tree.delete(*self.item_tree.get_children())

            for i in row:
                #self.tree.item(idx)['text']

                self.item_tree.insert("",
                                      "end",
                                      text=i[0],
                                      value=(i[0], i[1], i[2], i[3], i[4],
                                             i[5], i[6], i[7], i[8], i[9]))
            # self.my_connection.commit()
        self.item_tree.bind('<Double-1>', self.select_item)

    def Search_items(self):
        con = mysql.connector.connect(host='localhost',
                                      user='******',
                                      password='',
                                      database='register')
        cur = con.cursor()
        values = (
            str(self.search_by.get()),
            '"{}"'.format(str(self.search_txt.get() + '%')),
        )
        qry = (
            f"SELECT ID,destination,source,dpt,combo,count_no,class_selection,user_id,flight_name,price FROM oneway WHERE user_id={self.user_id} AND {values[0]} LIKE {values[1]}  "
        )

        cur.execute(qry)
        rows = cur.fetchall()

        if len(rows) != 0:
            self.item_tree.delete(*self.item_tree.get_children())

            for row in rows:
                self.item_tree.insert("", END, values=row)
            con.commit()

    def valid(self):

        if self.ent_where.get() == "" or self.ent_to.get(
        ) == "" or self.ent_dpt.get() == "" or self.txt_combo.get(
        ) == "" or self.ent_count.get() == "" or self.txt_classcombo.get(
        ) == "":
            messagebox.showerror('Error', 'please enter all required fields')

            return False

        else:
            return True

    def delete_item(self):
        selected_item = self.item_tree.selection()[0]

        item_data = self.item_tree.item(selected_item, 'text')

        index = item_data
        if form2.Item_dlt().delete_items(index):
            messagebox.showinfo('Item', 'Item Deleted')
            self.show_in_treeview()

            # selected_item = self.item_tree.selection()
            # self.item_tree.delete(selected_item)

        else:
            messagebox.showerror("Error",
                                 "Item cannot be deleted",
                                 parent=self.window)

    def generate_bill(self):
        all_orders = self.item_tree.get_children()
        bill_list = []
        total = 0
        # tbl=self.order_tree.item(all_orders[0],'values')[0]
        # name=self.order_tree.item(all_orders[1],'values')[1]
        for i in all_orders:
            order = self.item_tree.item(i, 'values')
            amt = float(order[5]) * float(order[9])
            bill_list.append((order[2], order[3], order[4], order[5], order[6],
                              order[8], order[9], amt))
            total += amt
        BillView(bill_list, total, self.user)
Пример #19
0
class BudgetPlaner():
    def __init__(self):
        self.PATH = r'E:Python\Projects\03_Budget_Planner'
        #self.bg = '#E64D2C'
        self.bg = '#0294A5'
        self.fg = 'white'
        #self.fg = '#A79C93'

    def create_main_window(self):

        window = tk.Tk()
        window.title('Budget Planner')
        window.geometry('530x680')
        window.resizable(width=False, height=False)
        window.config(bg=self.bg)

        fontStyle = tk.font.Font(size=20)
        lb_main = tk.Label(window,
                           text='BUDGET PLANNER',
                           fg=self.fg,
                           bg=self.bg,
                           font=fontStyle)
        lb_main.pack()

        frame1 = tk.Frame(window, bg=self.bg)
        self.frame2 = tk.Frame(window, bg=self.bg)
        frame3 = tk.Frame(window, bg=self.bg)
        frame4 = tk.Frame(window, bg=self.bg)
        frame5 = tk.Frame(window, bg=self.bg)
        frame6 = tk.Frame(window, bg=self.bg)

        frame1.pack(fill='both', padx=10, pady=5)
        self.frame2.pack()
        frame3.pack(fill='both', padx=10, pady=5)
        frame4.pack(fill='both', padx=10, pady=5)
        frame5.pack(fill='both', expand='yes', padx=10, pady=5)
        frame6.pack(fill='both', padx=10, pady=5)

        lf_create = tk.LabelFrame(frame1,
                                  text='CREATE NEW FILE',
                                  fg=self.fg,
                                  bg=self.bg)
        lf_load = tk.LabelFrame(frame1,
                                text='LOAD FILE',
                                fg=self.fg,
                                bg=self.bg)
        lf_view = tk.LabelFrame(frame3,
                                text='PROJECT DATA',
                                fg=self.fg,
                                bg=self.bg)
        lf_add = tk.LabelFrame(frame4, text='ADD DATA', fg=self.fg, bg=self.bg)
        self.lf_info = tk.LabelFrame(frame4,
                                     text='BUDGET INFORMATION',
                                     fg=self.fg,
                                     bg=self.bg)
        lf_budget = tk.LabelFrame(frame6,
                                  text='MODIFY BUDGET',
                                  fg=self.fg,
                                  bg=self.bg)

        lf_create.pack(side=tk.LEFT, padx=10)
        lf_load.pack(side=tk.RIGHT, padx=10)
        lf_view.pack(fill='both', padx=10, pady=5)
        lf_add.pack(side=tk.LEFT, padx=10)
        self.lf_info.pack(side=tk.RIGHT, padx=10)
        lf_budget.pack(pady=5)

        # Create file area
        lb_create = tk.Label(lf_create, text='ENTER FILE NAME', width=15)
        lb_create.grid(row=0, column=0, padx=5, pady=5)

        ent_create = tk.Entry(lf_create, width=15)
        ent_create.grid(row=0, column=1, padx=5)

        # Create new file
        def create_file(filename):

            # Check if file with same name exists
            if os.path.exists(self.PATH + '\\' + '02_Input' + '\\' + filename +
                              '.xlsx'):
                messagebox.showwarning('Warning',
                                       'A file with same name exist.')
            elif len(filename) == 0:
                messagebox.showerror('Error', 'Provide a file name.')
            else:
                infile = self.PATH + '\\' + '02_Input' + '\\' + 'template.xlsx'
                outfile = self.PATH + '\\' + '02_Input' + '\\' + filename + '.xlsx'
                shutil.copy(infile, outfile)
                ent_create.delete(0, tk.END)
                messagebox.showinfo('Info', 'New file created.')

        but_create = tk.Button(lf_create,
                               text='CREATE',
                               width=10,
                               command=lambda: create_file(ent_create.get()))
        but_create.grid(row=1, column=0, columnspan=2, pady=5)

        # Load file area
        lb_load = tk.Label(lf_load, text='ENTER FILE NAME', width=15)
        lb_load.grid(row=0, column=0, padx=5, pady=5)

        ent_load = tk.Entry(lf_load, width=15)
        ent_load.grid(row=0, column=1, padx=5)

        # Load the file and display data
        def load_file(filename):

            self.fn = filename
            if os.path.exists(self.PATH + '\\' + '02_Input' + '\\' + filename +
                              '.xlsx'):
                self.read_file(filename)
                self.close_file()
                ent_load.delete(0, tk.END)
                messagebox.showinfo('Info', 'File loaded.')
            elif len(filename) == 0:
                messagebox.showerror('Error', 'Provide a file name.')
            else:
                messagebox.showerror('Error', 'File does not exist.')

        but_load = tk.Button(lf_load,
                             text='LOAD',
                             width=10,
                             command=lambda: load_file(ent_load.get()))
        but_load.grid(row=1, column=0, columnspan=2, pady=5)

        # Project data area
        lb_fileinfo = tk.Label(self.frame2, text='Current File Name', width=30)
        lb_fileinfo.grid(row=0, column=0, padx=10, pady=5)
        #lb_fileinfo.place(x=10)

        self.lb_filename = tk.Label(self.frame2,
                                    text='NO FILES LOADED',
                                    width=30)
        self.lb_filename.grid(row=0, column=1, padx=10, pady=5)
        #lb_filename.place(x=20, y=25)

        col_dict = {
            0: ['Sl No', 50],
            1: ['Date', 95],
            2: ['Activity', 240],
            3: ['Cost', 80]
        }
        self.trv = tk.ttk.Treeview(lf_view,
                                   columns=col_dict.keys(),
                                   show='headings',
                                   height=8)
        #self.trv.pack(fill='both', padx=10, pady=10)
        self.trv.grid(row=1, columnspan=5, column=0, padx=10, pady=10)

        for c in range(4):
            self.trv.heading(c, text=col_dict[c][0])
            self.trv.column(c, width=col_dict[c][1])

        # Bind for single click, action is defined by single_click() function.
        self.trv.bind('<ButtonRelease-1>', self.single_click)

        # Bind for double click, action is defined by self.select_item function.
        self.trv.bind('<Double-1>', self.double_click)

        # New data area
        lb1 = tk.Label(lf_add, text='Sl No', width=10)
        lb1.grid(row=0, column=0, padx=5, pady=5)
        self.entar1 = tk.Entry(lf_add, width=20)
        self.entar1.grid(row=0, column=1, padx=5, pady=5)

        lb2 = tk.Label(lf_add, text='Date', width=10)
        lb2.grid(row=1, column=0, padx=5, pady=5)
        self.entar2 = DateEntry(lf_add, width=17, date_pattern='dd.mm.yyyy')
        self.entar2.grid(row=1, column=1)

        lb3 = tk.Label(lf_add, text='Activity', width=10)
        lb3.grid(row=2, column=0, padx=5, pady=5)
        self.entar3 = tk.Entry(lf_add, width=20)
        self.entar3.grid(row=2, column=1, padx=5, pady=5)

        lb4 = tk.Label(lf_add, text='Cost', width=10)
        lb4.grid(row=4, column=0, padx=5, pady=5)
        self.entar4 = tk.Entry(lf_add, width=20)
        self.entar4.grid(row=4, column=1, padx=5, pady=5)
        self.entar4.insert(0, '0.0')

        self.info_area()

        # Create various buttons
        def add_data():

            self.read_file(self.fn)
            # get all the sl_no from the file
            slno_range = 'A5:' + 'A' + str(self.nrows)
            slno_list = self.sheet.range(slno_range).value
            # Convert 'slno_list' to datatype list if there is only one row in the file
            if type(slno_list) == float:
                slno_list = [slno_list]

            new_row = self.nrows + 1
            self.close_file()

            try:
                int(self.entar1.get())
                float(self.entar4.get())
            except ValueError:
                messagebox.showerror('Error',
                                     'Sl No or Cost not a valid value.')
                return

            if self.entar1.get() == '' or self.entar2.get(
            ) == '' or self.entar3.get() == '' or self.entar4.get() == '':
                messagebox.showerror('Error', 'Missing mandatory values.')
            elif float(self.entar1.get()) in slno_list:
                messagebox.showerror('Error', 'Sl No should be unique.')
            else:
                self.read_file(self.fn)
                self.sheet.range(new_row, 1).value = self.entar1.get()
                self.sheet.range(new_row, 2).value = self.entar2.get()
                self.sheet.range(new_row, 3).value = self.entar3.get()
                self.sheet.range(new_row, 4).value = self.entar4.get()

                self.close_file(param='write')
                clear_entry()
                messagebox.showinfo('Info', 'Data added.')

        but_add = tk.Button(frame5, text='ADD', width=12, command=add_data)
        but_add.place(x=10, y=8)

        def update_data():

            self.read_file(self.fn)
            # get all the sl_no from the file
            slno_range = 'A5:' + 'A' + str(self.nrows)
            slno_list = self.sheet.range(slno_range).value
            # Convert 'slno_list' to datatype list if there is only one row in the file
            if type(slno_list) == float:
                slno_list = [slno_list]

            sl_idx = 0
            self.close_file()

            try:
                int(self.entar1.get())
                float(self.entar4.get())
            except ValueError:
                messagebox.showerror('Error',
                                     'Sl No or Cost not a valid value.')
                return

            if self.entar1.get() == '' or self.entar2.get(
            ) == '' or self.entar3.get() == '' or self.entar4.get() == '':
                messagebox.showerror('Error', 'Missing mandatory values')
            elif float(self.entar1.get()) not in slno_list:
                messagebox.showerror('Error', 'Sl No does not exist.')
            else:
                for r in range(5, self.nrows + 1):
                    if float(self.entar1.get()) == slno_list[sl_idx]:
                        self.read_file(self.fn)
                        self.sheet.range(r, 2).value = self.entar2.get()
                        self.sheet.range(r, 3).value = self.entar3.get()
                        self.sheet.range(r, 4).value = self.entar4.get()
                        self.close_file(param='write')
                        clear_entry()
                        messagebox.showinfo('Info', 'Data updated.')
                        break
                    else:
                        sl_idx += 1

        but_update = tk.Button(frame5,
                               text='UPDATE',
                               width=12,
                               command=update_data)
        but_update.place(x=142, y=8)

        def delete_data():
            self.read_file(self.fn)
            sl_idx = 0
            slno_range = 'A5:' + 'A' + str(self.nrows)
            slno_list = self.sheet.range(slno_range).value
            slno_to_delete = self.item['values'][0]
            if float(slno_to_delete) in slno_list:
                for r in range(5, self.nrows + 1):
                    if float(slno_to_delete) == slno_list[sl_idx]:
                        del_range = 'A' + str(r) + ':' + 'D' + str(r)
                        self.sheet.range(del_range).api.Delete(
                            constants.DeleteShiftDirection.xlShiftUp)
                        self.close_file(param='write')
                        clear_entry()
                        messagebox.showinfo('Info', 'Selected row deleted.')
                        break
                    else:
                        sl_idx += 1
            else:
                self.close_file()
                messagebox.showerror('Error', 'Invalid Sl No.')

        but_delete = tk.Button(frame5,
                               text='DELETE',
                               width=12,
                               command=delete_data)
        but_delete.place(x=274, y=8)

        # Clear entry field / set it to defaul value
        def clear_entry():
            self.entar1.delete(0, tk.END)
            self.entar2.set_date(datetime.today())
            self.entar3.delete(0, tk.END)
            self.entar4.delete(0, tk.END)
            self.entar4.insert(0, '0.0')

        but_clear = tk.Button(frame5,
                              text='CLEAR',
                              width=12,
                              command=clear_entry)
        but_clear.place(x=406, y=8)

        # Create budget update area
        def modify_budget():

            self.read_file(self.fn)
            self.sheet.range(1, 2).value = ent_budget.get()
            self.close_file('write')
            ent_budget.delete(0, tk.END)
            ent_budget.insert(0, '0.0')
            messagebox.showinfo('Info', 'Budget amount updated.')

        lb_budget = tk.Label(lf_budget, text='Budget Amount', width=20)
        lb_budget.grid(row=0, column=0, padx=10, pady=5)

        ent_budget = tk.Entry(lf_budget, width=10)
        ent_budget.grid(row=0, column=1, padx=10)
        ent_budget.insert(0, '0.0')

        bt_budget = tk.Button(lf_budget,
                              text='ADD / UPDATE',
                              width=12,
                              command=modify_budget)
        bt_budget.grid(row=0, column=2, padx=10)

        window.mainloop()

    # Information area
    def info_area(self, budget_amt=0, total_spent=0, balance=0, status='Good'):

        lb_info1 = tk.Label(self.lf_info, text='Budget allocated', width=20)
        lb_info1.grid(row=0, column=0, padx=5, pady=5)
        lb_amt = tk.Label(self.lf_info, text=budget_amt, width=10)
        lb_amt.grid(row=0, column=1, padx=5, pady=5)

        lb_info2 = tk.Label(self.lf_info, text='Total Spent', width=20)
        lb_info2.grid(row=1, column=0, padx=5, pady=5)
        lb_tot = tk.Label(self.lf_info, text=total_spent, width=10)
        lb_tot.grid(row=1, column=1, padx=5, pady=5)

        lb_info3 = tk.Label(self.lf_info, text='Balance Available', width=20)
        lb_info3.grid(row=2, column=0, padx=5, pady=5)
        lb_bal = tk.Label(self.lf_info, text=balance, width=10)
        lb_bal.grid(row=2, column=1, padx=5, pady=5)

        lb_info4 = tk.Label(self.lf_info, text='Budget Status', width=20)
        lb_info4.grid(row=3, column=0, padx=5, pady=5)
        lb_stat = tk.Label(self.lf_info, text=status, width=10)
        lb_stat.grid(row=3, column=1, padx=5, pady=5)

    # Read file
    def read_file(self, filename):

        self.app = xw.App(visible=False, add_book=False)
        self.file = self.app.books.open(self.PATH + '\\' + '02_Input' + '\\' +
                                        self.fn + '.xlsx')
        self.sheet = self.file.sheets['data']
        self.nrows = self.sheet.range(1, 1).end('down').row

    # Save and close file
    def close_file(self, param='read'):

        if param == 'write':
            self.file.save()
            self.nrows = self.sheet.range(1, 1).end('down').row

        self.get_amt_data()
        self.display_data()
        self.file.close()
        self.app.quit()

    # Get data to populate information area
    def get_amt_data(self):

        budget_amt = self.sheet.range('B1').value
        total_spent = self.sheet.range('B2').value
        balance = self.sheet.range('B3').value
        status = self.sheet.range('E1').value

        self.info_area(budget_amt, total_spent, balance, status)

    # Display data in treeview area
    def display_data(self):

        self.lb_filename = tk.Label(self.frame2, text=self.fn, width=30)
        self.lb_filename.grid(row=0, column=1, padx=10, pady=5)

        self.trv.delete(*self.trv.get_children())
        data = []
        for r in range(5, self.nrows + 1):
            sl_no = int(self.sheet.range(r, 1).value)
            date = self.sheet.range(r, 2).value
            activity = self.sheet.range(r, 3).value
            cost = self.sheet.range(r, 4).value
            data = [sl_no, date, activity, cost]
            self.trv.insert('', tk.END, values=data)

    # Function for tree view bind single click.
    def single_click(self, event):
        self.item = self.trv.item(self.trv.focus())

    # Function for tree view bind double click.
    def double_click(self, event):
        try:
            self.item = self.trv.item(self.trv.focus())
            self.entar1.delete(0, tk.END)
            self.entar1.insert(0, self.item['values'][0])
            self.entar2.set_date(self.item['values'][1])
            self.entar3.delete(0, tk.END)
            self.entar3.insert(0, self.item['values'][2])
            self.entar4.delete(0, tk.END)
            self.entar4.insert(0, self.item['values'][3])
        except IndexError:
            pass
Пример #20
0
class Table(tk.Frame):
    def __init__(self, parent, controller):
        global all_subject
        Frame.__init__(self, parent)
        table_frame = tk.Frame(self)
        self.go_back = Button(table_frame,
                              text="Go Back",
                              width=15,
                              command=lambda: controller.show_frame(StartPage))
        self.go_back.pack(padx=10, pady=10, side="left")
        text = tk.Text()
        self.date_label = tk.Label(table_frame, text="Date :",
                                   font=LARGE_FONT).pack(side="left",
                                                         padx=5,
                                                         pady=5)
        self.cal = DateEntry(table_frame,
                             width=12,
                             year=int(strftime("%Y", gmtime())),
                             month=int(strftime("%m", gmtime())),
                             day=int(strftime("%d", gmtime())),
                             background='black',
                             foreground='white',
                             borderwidth=2)
        self.cal.pack(side="left", padx=10, pady=10)
        self.date_label = tk.Label(table_frame,
                                   text="Select Class :",
                                   font=LARGE_FONT).pack(side="left",
                                                         padx=5,
                                                         pady=5)
        self.variable1 = tk.StringVar(table_frame)
        w1 = OptionMenu(
            table_frame, self.variable1, "ALL",
            *list(
                map(lambda x: x.split(".")[0].upper(),
                    os.listdir("csv//classes")))).pack(side="left",
                                                       padx=10,
                                                       pady=10)
        self.subject = tk.Label(table_frame, text="Subject :", font=LARGE_FONT)
        self.subject.pack(side="left", padx=10, pady=10)
        self.variable2 = tk.StringVar(table_frame)
        subject1 = [""]
        subject1.extend(all_subject)
        self.enter_sub = OptionMenu(table_frame, self.variable2, *subject1)
        self.enter_sub.pack(side="left", padx=10, pady=10)
        self.btn_submit = Button(table_frame,
                                 text="Submit",
                                 width=15,
                                 command=self.LoadTable)
        self.btn_submit.pack(padx=10, pady=10, side="left")
        self.to_csv_ = Button(table_frame,
                              text="To Csv",
                              width=15,
                              command=self.file_save)
        self.to_csv_.pack(padx=10, pady=10)
        table_frame.pack(expand=True, anchor=tk.CENTER, pady=1)
        self.CreateUI()
        self.LoadTable()

    def CreateUI(self):
        tv = Treeview(self, height=40)
        # vsb = Scrollbar(self, orient="vertical", command=tv.yview)
        #  vsb.place(x=400, y=400, height=20)
        # tv.configure(yscrollcommand=vsb.set)
        tv['columns'] = ('Enrollment', "Date", 'Time', "Day", "class",
                         "Subject")
        tv.heading("#0", text='Name', anchor='w')
        tv.column("#0", anchor="w")
        tv.heading('Enrollment', text=' Enrollment No.')
        tv.column('Enrollment', anchor='center', width=150)
        tv.heading('Time', text='Time')
        tv.column('Time', anchor='center', width=150)
        tv.heading('class', text='class')
        tv.heading('Date', text='Date')
        tv.column('Date', anchor='center', width=150)
        tv.column('class', anchor='center', width=150)
        tv.heading('Day', text='Day')
        tv.column('Day', anchor='center', width=150)
        tv.heading('Subject', text='Subject')
        tv.column('Subject', anchor='center', width=150)
        tv.pack(anchor=tk.CENTER)
        self.treeview = tv

    def LoadTable(self):
        clss = self.variable1.get().lower()
        sub = self.variable2.get().strip().lower()
        month, day, year = self.cal.get().split("/")
        self.treeview.delete(*self.treeview.get_children())
        try:
            csv = "all-20{}-{}-{}".format(year.zfill(2), month.zfill(2),
                                          day.zfill(2))
            df = pd.read_csv("records/{}.csv".format(csv))
            if clss != "" and clss != "all":
                df = df.loc[df['class'] == clss]
            if sub != "" and sub != "":
                df = df.loc[df['subject'] == sub]
            self.tf = df.copy()
            df = df.values
            for i in range(len(df)):
                self.treeview.insert('',
                                     'end',
                                     text=df[i, 0],
                                     values=(df[i, 1].upper(), df[i, 2],
                                             df[i, 3], df[i, 4],
                                             df[i, 5].upper(), df[i,
                                                                  6].upper()))
        except Exception:
            print("no data")

    def file_save(self):
        dir_name = asksaveasfilename(defaultextension=".csv")
        if dir_name != "":
            self.tf.to_csv(dir_name, index=False)
Пример #21
0
def open_new_rule_dialog():
    # Toplevel object which will
    # be treated as a new window
    global rule_dialog
    rule_dialog = Toplevel(root)

    # sets the title of the
    # Toplevel widget
    rule_dialog.title("Portfolio App - Sukurti naują taisyklę")

    rule_dialog.iconbitmap(
        'C:\PythonPrograms\Bakalauro Baigiamasis Darbas\LSTM stock price prediction\money.ico'
    )
    # sets the geometry of toplevel
    rule_dialog.geometry("450x400")

    # A Label widget to show in toplevel
    Label(rule_dialog, text="Pasirinkta įmonė: ").grid(sticky="w",
                                                       row=0,
                                                       column=0,
                                                       padx=10,
                                                       pady=10)
    global company_name
    company_name = Entry(rule_dialog, width=30, borderwidth=2)
    company_name.insert(0, get_selected_company())
    company_name.grid(sticky="w", row=0, column=1, padx=(0, 10), pady=10)
    Label(rule_dialog,
          text="Pasirinkta investavimo strategija: ").grid(sticky="w",
                                                           row=1,
                                                           column=0,
                                                           padx=10,
                                                           pady=10)
    options = [
        "LSTM Rekurentinis Neuroninis Tinklas", "Fibonacci Retracement Lygiai",
        "Vėžlių Prekyba", "Ilgalaikė investicija"
    ]

    global clicked
    clicked = StringVar()
    clicked.set(options[0])

    drop = OptionMenu(rule_dialog, clicked, *options)
    drop.grid(sticky="w", row=1, column=1, padx=(0, 10), pady=10)

    Label(rule_dialog, text="Data nuo: ").grid(sticky="w",
                                               row=2,
                                               column=0,
                                               padx=10,
                                               pady=10)
    start_date = DateEntry(rule_dialog,
                           width=12,
                           background='darkblue',
                           foreground='white',
                           borderwidth=2,
                           date_pattern='yyyy-mm-dd')
    start_date.grid(sticky="w", row=2, column=1, padx=(0, 10), pady=10)
    start_date.delete(0, END)
    start_date.insert(0, '2012-01-01')
    Label(rule_dialog, text="Data iki: ").grid(sticky="w",
                                               row=3,
                                               column=0,
                                               padx=10,
                                               pady=10)
    end_date = DateEntry(rule_dialog,
                         width=12,
                         background='darkblue',
                         foreground='white',
                         borderwidth=2,
                         date_pattern='yyyy-mm-dd')
    end_date.grid(sticky="w", row=3, column=1, padx=(0, 10), pady=10)
    end_date.delete(0, END)
    end_date.insert(0, '2021-05-21')

    chooseStrategyButton = Button(
        rule_dialog,
        text="Įtraukti taisyklę",
        command=lambda: select_rule(company_name.get(), clicked.get(),
                                    start_date.get(), end_date.get()))
    chooseStrategyButton.grid(row=4, column=0, columnspan=2, padx=10, pady=10)
Пример #22
0
class Roxana():
    def __init__(self):

        self.backcolor = "#141454"
        self.fgcolor = "white"
        self.salida = []
        """
        Preferencias:
        Nombre:
        Nacimiento:
        Tema:
        Idioma:
        Lugar:
        """
        with open('./preferencias.txt', 'r') as f:
            # with open('./preferencias.txt', 'r') as f:
            lineas = [linea.split() for linea in f]
        for linea in lineas:
            self.salida.append(linea)
        i = 0
        self.temas = [[
            'Claro', 'Oscuro (por defecto)', 'Verde', 'Rojo', 'Cielo', 'Morado'
        ], ["#ffffff", "#141454", "#34B677", "#FB2929", "#31DFE8", "#340A3C"],
                      [
                          "#000000", "#ffffff", "#ffffff", "#ffffff",
                          "#000000", "#ffffff"
                      ]]

        self.elementos = self.salida
        tam = len(self.salida)
        if tam == 0:
            self.encuesta()
        else:
            for i in range(len(self.temas[0])):
                print(str(self.salida[2]))
                print("0", self.temas[0][i])
                if self.temas[0][i] in self.salida[2]:

                    print("1", self.temas[1][i])
                    print("2", self.temas[2][i])
                    self.backcolor = self.temas[1][i]
                    self.fgcolor = self.temas[2][i]
            self.ventana()

    def encuesta(self):
        self.root = them.ThemedTk(theme="arc")
        #self.root.overrideredirect(True)
        ax = them.THEMES
        print(ax)
        # ['adapta', 'aquativo', 'arc', 'black', 'blue', 'breeze',
        # 'clearlooks', 'elegance', 'equilux', 'itft1', 'keramik',
        # 'kroc', 'plastik', 'radiance', 'scidblue', 'scidgreen',
        # 'scidgrey', 'scidmint', 'scidpink', 'scidpurple', 'scidsand',
        # 'smog', 'ubuntu', 'winxpblue', 'yaru']

        ancho_ventana = 720
        alto_ventana = 480
        x_ventana = self.root.winfo_screenwidth() // 2 - ancho_ventana // 2
        y_ventana = self.root.winfo_screenheight() // 2 - alto_ventana // 2
        posicion = str(ancho_ventana) + "x" + str(alto_ventana) + "+" + str(
            x_ventana) + "+" + str(y_ventana)
        self.root.geometry(posicion)
        self.root.config(bg=self.backcolor)
        self.root.wm_attributes('-topmost', False)
        self.root.iconbitmap('./images/icon.ico')
        #self.root.overrideredirect(False)
        self.root.resizable(0, 0)
        imagen = ("./images/64x64.png")
        imagen02 = ("./images/256x256.png")
        self.imagen2 = ImageTk.PhotoImage(image=Image.open(imagen02))
        # imagen = ("./images/64x64.png")
        self.imagen = ImageTk.PhotoImage(image=Image.open(imagen))
        self.logo = Label(self.root, image=self.imagen, bg=self.backcolor)
        self.logo.place(x=15, y=5)
        self.lbl1 = Label(
            self.root,
            text="Te realizaré una encuesta para conocerte un poco mas",
            font=("Arial", 16),
            bg=self.backcolor,
            fg=self.fgcolor)
        self.lbl1.place(x=125, y=20)
        self.lbl2 = Label(
            self.root,
            text="La siguiente información será solo utilizada para que Roxana\n"
            "te conozca un poco mas, no se utilizará de otra manera,\n"
            "pero es totalmente obligatoria para mejorar tu experiencia.\n"
            "Al presionar Acepto, aceptarás nuestros terminos no estaticos\n"
            "si presionas No Acepto, el programa se cerrará.",
            font=("Arial", 12),
            bg=self.backcolor,
            fg=self.fgcolor)
        self.lbl2.place(x=150, y=60)

        self.btn1 = Button(self.root,
                           text="Acepto",
                           command=self.aceptar,
                           font=("Arial", 11),
                           bg="#139134",
                           fg=self.fgcolor,
                           highlightthickness=0,
                           highlightcolor="green",
                           relief="flat",
                           activeforeground=self.fgcolor,
                           activebackground="green")
        self.btn1.place(x=540, y=170)
        self.btn2 = Button(self.root,
                           text="No Acepto",
                           command=self.declinar,
                           font=("Arial", 11),
                           bg="#FB2929",
                           fg=self.fgcolor,
                           highlightthickness=0,
                           highlightcolor="red",
                           relief="flat",
                           activeforeground=self.fgcolor,
                           activebackground="red")
        self.btn2.place(x=440, y=170)
        self.root.mainloop()

    def aceptar(self):
        self.logo.config(image=self.imagen2)
        self.logo.place(x=420, y=55)
        self.btn1.destroy()
        self.btn2.destroy()
        self.lbl1.config(text="Contesta por favor con la verdad",
                         font=("Arial", 18))
        self.lbl1.place(x=20, y=10)

        self.lbl2.config(text="¿Cómo te llamas?")
        self.lbl2.place(x=28, y=50)
        self.ent1 = Entry(self.root, font=("Arial", 10), fg="black", width=44)
        self.ent1.place(x=20, y=80)
        self.lbl3 = Label(self.root,
                          text="¿Cuál es tu fecha de nacimiento?",
                          font=("Arial", 12),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl3.place(x=23, y=110)
        now = datetime.now()
        anio = now.year
        mes = now.month
        dia = now.day
        self.de = DateEntry(self.root,
                            locale='es_MX',
                            date_pattern='dd/mm/y',
                            year=anio,
                            month=mes,
                            day=dia,
                            width=26,
                            selectmode='day',
                            cursor="hand1",
                            font="Arial 14",
                            highlightthickness=0,
                            selectbackground='gray80',
                            selectforeground='black',
                            normalbackground='white',
                            normalforeground='black',
                            background='gray90',
                            foreground='black',
                            bordercolor='gray90',
                            othermonthforeground='gray50',
                            othermonthbackground='white',
                            othermonthweforeground='gray50',
                            othermonthwebackground='white',
                            weekendbackground='white',
                            weekendforeground='black',
                            headersbackground='white',
                            headersforeground='gray70')
        self.de.place(x=20, y=140)
        self.lbl4 = Label(self.root,
                          text="Selecciona un tema",
                          font=("Arial", 12),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl4.place(x=28, y=170)
        tema = StringVar()
        self.temas = ttk.Combobox(self.root,
                                  width=47,
                                  textvariable=tema,
                                  state="readonly")
        self.temas.set("Oscuro (por defecto)")
        self.temas['values'] = ('Claro', 'Oscuro (por defecto)', 'Verde',
                                'Rojo', 'Cielo', 'Morado')
        self.temas.place(x=20, y=200)
        self.temas.bind("<<ComboboxSelected>>", self.detecta_cambio)

        self.lbl5 = Label(self.root,
                          text="Selecciona un idioma",
                          font=("Arial", 12),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl5.place(x=27, y=230)
        idiomas = StringVar()
        self.idioma = ttk.Combobox(self.root,
                                   width=47,
                                   textvariable=idiomas,
                                   state="readonly")
        self.idioma['values'] = ('Español', 'Ingles', 'Chino', 'Ruso',
                                 'Francés', 'portugués')
        self.idioma.place(x=20, y=260)
        self.idioma.bind("<<ComboboxSelected>>", self.detecta_idioma)

        self.lbl6 = Label(self.root,
                          text="Datos geograficos",
                          font=("Arial", 12),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl6.place(x=27, y=290)

        place2 = "CP"
        self.ent3 = Entry(self.root, font=("Arial", 12), width=10, fg='Grey')
        self.ent3.insert(0, place2)
        self.ent3.bind("<FocusIn>", lambda args: self.entradabox(self.ent3))
        self.ent3.bind("<FocusOut>",
                       lambda args: self.salidabox(place2, self.ent3))
        self.ent3.bind('<KeyRelease>',
                       lambda e: self.verifica(self.ent3, '0123456789'))
        self.ent3.place(x=20, y=320)

        place1 = "Ciudad"
        self.ent2 = Entry(self.root, font=("Arial", 12), fg='Grey', width=20)
        self.ent2.insert(0, place1)
        self.ent2.bind("<FocusIn>", lambda args: self.entradabox(self.ent2))
        self.ent2.bind("<FocusOut>",
                       lambda args: self.salidabox(place1, self.ent2))
        self.ent2.place(x=150, y=320)

        self.lbl7 = Label(self.root,
                          text="Estado",
                          font=("Arial", 12),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl7.place(x=20, y=350)

        estado = StringVar()
        self.estados = ttk.Combobox(self.root,
                                    width=48,
                                    textvariable=estado,
                                    state="readonly")
        self.estados['values'] = ("Aguascalientes", "Baja California",
                                  "Baja California Sur", "Campeche",
                                  "Coahuila de Zaragoza", "Colima", "Chiapas",
                                  "Chihuahua", "Distrito Federal", "Durango",
                                  "Guanajuato", "Guerrero", "Hidalgo",
                                  "Jalisco", "México", "Michoacán de Ocampo",
                                  "Morelos", "Nayarit", "Nuevo León", "Oaxaca",
                                  "Puebla", "Querétaro", "Quintana Roo",
                                  "San Luis Potosí", "Sinaloa", "Sonora",
                                  "Tabasco", "Tamaulipas", "Tlaxcala",
                                  "Veracruz de Ignacio de la Llave", "Yucatán",
                                  "Zacatecas")
        self.estados.place(x=20, y=380)

        self.btn3 = Button(self.root,
                           text="Confirmar",
                           width=22,
                           height=1,
                           command=self.llena,
                           font=("Arial", 18),
                           bg="#139134",
                           fg=self.fgcolor,
                           highlightthickness=0,
                           highlightcolor="green",
                           relief="flat",
                           activeforeground=self.fgcolor,
                           activebackground="green")
        self.btn3.place(x=20, y=410)

        self.idioma.update()

    def declinar(self):
        exit()

    def salidabox(self, text, elem):
        place1 = text
        if elem['fg'] == 'Black' and len(elem.get()) == 0:
            elem.delete(0, END)
            elem['fg'] = 'Grey'
            elem.insert(0, place1)

    def entradabox(self, elem):
        if elem['fg'] == 'Grey':
            elem['fg'] = 'Black'
            elem.delete(0, END)

    def verifica(self, elem, cadena):
        valor = elem.get()
        for i in valor:
            if i not in cadena:
                elem.delete(valor.index(i), valor.index(i) + 1)

    def llena(self):
        name = self.ent1.get()
        fecha = self.de.get()
        tema = self.temas.get()
        idioma = self.idioma.get()
        cp = self.ent3.get()
        city = self.ent2.get()

        state = self.estados.get()
        print(name)
        print(fecha)
        print(tema)
        print(idioma)
        print(cp)
        print(city)
        print(state)
        if name != "" and tema != "" and idioma != "" and cp != "" and city != "" and state != "":
            text = name + "\n" + fecha + "\n" + tema + "\n" + idioma + "\n" + cp + "\n" + city + "\n" + state
            print(text)
            f = open('./preferencias.txt', 'w')
            f.write(text)
            f.close()

            messagebox.showinfo(
                message="Tus datos han sido generados correctamente",
                title="Transacción satisfactoria")
            self.btn3.config(state=DISABLED)
            self.root.destroy()
            a = Roxana()

        else:
            messagebox.showwarning(
                message="Algúl campo se encuentra vacio, verifique y llenelo",
                title="Alerta")

    def detecta_cambio(self, event):
        seleccionado = self.temas.get()
        print("Nuevo elemento seleccionado:", seleccionado)

        temas = [[
            'Claro', 'Oscuro (por defecto)', 'Verde', 'Rojo', 'Cielo', 'Morado'
        ], ["#ffffff", "#141454", "#34B677", "#FB2929", "#31DFE8", "#340A3C"],
                 [
                     "#000000", "#ffffff", "#ffffff", "#ffffff", "#000000",
                     "#ffffff"
                 ]]

        for i in range(len(temas[0])):
            if temas[0][i] in seleccionado:
                print("1", temas[1][i])
                print("2", temas[2][i])
                self.backcolor = temas[1][i]
                self.fgcolor = temas[2][i]

        self.root.config(bg=self.backcolor)
        self.root.wm_attributes('-topmost', False)
        self.root.iconbitmap('./images/icon.ico')
        self.lbl1.config(bg=self.backcolor, fg=self.fgcolor)
        self.lbl2.config(bg=self.backcolor, fg=self.fgcolor)
        self.lbl3.config(bg=self.backcolor, fg=self.fgcolor)
        self.lbl4.config(bg=self.backcolor, fg=self.fgcolor)
        self.lbl5.config(bg=self.backcolor, fg=self.fgcolor)
        self.logo.config(bg=self.backcolor, fg=self.fgcolor)
        self.lbl6.config(bg=self.backcolor, fg=self.fgcolor)
        self.lbl7.config(bg=self.backcolor, fg=self.fgcolor)

        self.root.update()

    def detecta_cambio2(self, event):
        seleccionado = self.temas.get()
        print("Nuevo elemento seleccionado:", seleccionado)

        temas = [[
            'Claro', 'Oscuro (por defecto)', 'Verde', 'Rojo', 'Cielo', 'Morado'
        ], ["#ffffff", "#141454", "#34B677", "#FB2929", "#31DFE8", "#340A3C"],
                 [
                     "#000000", "#ffffff", "#ffffff", "#ffffff", "#000000",
                     "#ffffff"
                 ]]

        for i in range(len(temas[0])):
            if temas[0][i] in seleccionado:
                print("1", temas[1][i])
                print("2", temas[2][i])
                self.backcolor = temas[1][i]
                self.fgcolor = temas[2][i]

        self.win.config(bg=self.backcolor)
        self.win.wm_attributes('-topmost', False)
        self.win.iconbitmap('./images/icon.ico')
        self.lbl1.config(bg=self.backcolor, fg=self.fgcolor)
        self.lbl2.config(bg=self.backcolor, fg=self.fgcolor)
        self.lbl3.config(bg=self.backcolor, fg=self.fgcolor)
        self.lbl4.config(bg=self.backcolor, fg=self.fgcolor)
        self.lbl5.config(bg=self.backcolor, fg=self.fgcolor)
        self.logo.config(bg=self.backcolor, fg=self.fgcolor)
        self.lbl6.config(bg=self.backcolor, fg=self.fgcolor)
        self.lbl7.config(bg=self.backcolor, fg=self.fgcolor)

        self.win.update()

    def detecta_idioma(self, event):
        seleccionado = self.idioma.get()
        print("Nuevo idioma seleccionado:", seleccionado)

    def ventana(self):
        name0 = self.elementos[0]
        self.name = ""
        for i in (name0):
            self.name += (i + " ")
        print(self.name)
        print(self.salida)
        print(self.elementos)

        self.root = them.ThemedTk(theme="arc")
        ax = them.THEMES
        print(ax)
        # ['adapta', 'aquativo', 'arc', 'black', 'blue', 'breeze',
        # 'clearlooks', 'elegance', 'equilux', 'itft1', 'keramik',
        # 'kroc', 'plastik', 'radiance', 'scidblue', 'scidgreen',
        # 'scidgrey', 'scidmint', 'scidpink', 'scidpurple', 'scidsand',
        # 'smog', 'ubuntu', 'winxpblue', 'yaru']

        ancho_ventana = 720
        alto_ventana = 480
        x_ventana = self.root.winfo_screenwidth() // 2 - ancho_ventana // 2
        y_ventana = self.root.winfo_screenheight() // 2 - alto_ventana // 2
        posicion = str(ancho_ventana) + "x" + str(alto_ventana) + "+" + str(
            x_ventana) + "+" + str(y_ventana)
        self.root.geometry(posicion)
        self.root.config(bg=self.backcolor)
        self.root.wm_attributes('-topmost', False)
        self.root.iconbitmap('./images/icon.ico')
        #self.root.overrideredirect(True)
        self.root.resizable(0, 0)
        imagen = ("./images/64x64.png")
        imagen02 = ("./images/256x256.png")
        imagen03 = ("./images/256x256_i.png")
        self.imagen2 = ImageTk.PhotoImage(image=Image.open(imagen02))
        # imagen = ("./images/64x64.png")
        self.imagen = ImageTk.PhotoImage(image=Image.open(imagen))
        self.micro = ImageTk.PhotoImage(image=Image.open(imagen03))
        self.logo = Label(self.root, image=self.imagen, bg=self.backcolor)
        self.logo.place(x=15, y=5)
        self.lbl1 = Label(self.root,
                          text=("Bienvenido " + self.name),
                          anchor="n",
                          justify=RIGHT,
                          width=33,
                          font=("Arial", 22),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl1.place(x=95, y=20)
        self.btnmic = Button(self.root,
                             text="",
                             image=self.micro,
                             command=self.escuchando,
                             bg=self.backcolor,
                             fg=self.fgcolor,
                             highlightthickness=0,
                             highlightcolor=self.backcolor,
                             activebackground=self.backcolor,
                             relief="flat")
        self.btnmic.place(x=232, y=80)
        """self.btn1 = Button(self.root, text="Acepto", command=self.aceptar, font=("Arial", 11), bg="#139134",
                           fg=self.fgcolor, highlightthickness=0, highlightcolor="green", relief="flat",
                           activeforeground=self.fgcolor, activebackground="green")
        self.btn1.place(x=540, y=170)
        self.btn2 = Button(self.root, text="No Acepto", command=self.declinar, font=("Arial", 11), bg="#FB2929",
                           fg=self.fgcolor, highlightthickness=0, highlightcolor="red", relief="flat",
                           activeforeground=self.fgcolor, activebackground="red")
        self.btn2.place(x=440, y=170)"""

        self.console = Label(self.root,
                             text="Presiona para escucharte",
                             width=39,
                             anchor="n",
                             justify=RIGHT,
                             font=("Arial", 22),
                             bg=self.backcolor,
                             fg=self.fgcolor)
        self.console.place(x=20, y=380)
        btnfoto = PhotoImage(file="./images/user.png")
        self.btn1 = Button(self.root,
                           text="Perfil",
                           image=btnfoto,
                           compound=LEFT,
                           command=self.aceptar2,
                           font=("Arial", 11),
                           bg="#139134",
                           fg=self.fgcolor,
                           highlightthickness=0,
                           highlightcolor="green",
                           relief="flat",
                           activeforeground=self.fgcolor,
                           activebackground="green")
        self.btn1.place(x=640, y=10)

        self.root.mainloop()

    def escuchando(self):
        t = threading.Thread(target=self.llama)
        t.start()

    def mensaje(self, texto, componente):
        componente.config(text=texto)

    def mic(self, r, source):

        self.audio = r.listen(source)

    def llama(self):

        r = sr.Recognizer()
        with sr.Microphone() as source:

            r.pause_threshold = 1
            r.adjust_for_ambient_noise(source)
            ta = threading.Thread(name="self.talk",
                                  target=self.talk2("Escuchando"),
                                  daemon=True)
            wr = threading.Thread(target=self.mensaje("Escuchando",
                                                      self.console),
                                  daemon=True)
            au = threading.Thread(name="self.mic", target=self.mic(r, source))
            print(self.audio)
            wr2 = threading.Thread(
                target=self.mensaje("Procesando", self.console))

        try:
            query = r.recognize_google(self.audio, language='es-MX')
            respuesta = query.lower()
            if "roxana" in respuesta:
                respuesta = respuesta.replace("roxana ", "")
                print("Estoy tratando de entender...")

                wr2 = threading.Thread(target=self.mensaje(
                    "Estoy tratando de entender", self.console))
                ta2 = threading.Thread(
                    target=self.talk("estoy tratando de entender"))
                wr2.start()
                ta2.start()
                print(f"Dijiste: {respuesta}\n")

                wr3 = threading.Thread(target=self.mensaje((
                    f"Dijiste: {respuesta}\n"), self.console))
                wr3.start()
                ta3 = threading.Thread(
                    target=self.talk(f"Dijiste: {respuesta}\n"))
                ta3.start()

                if "facebook" in (respuesta):
                    self.talk2("Abriendo Facebook")
                    wr4 = threading.Thread(
                        target=self.mensaje("Abriendo Facebook", self.console))
                    wr4.start()
                    webbrowser.open('https://www.facebook.com')
                if "whatsapp" in (respuesta):
                    res2 = respuesta.replace(" ", "")
                    subcadena = res2[-10:]
                    self.talk("Enviando mensaje al ", subcadena)
                    now = datetime.now()
                    num = "+52" + subcadena
                    hora = now.hour
                    min = now.minute
                    min2 = min + 1
                    print(hora, min)
                    print(num)
                    pywhatkit.sendwhatmsg(
                        num,
                        "Este mensaje fue enviado desde el asistente de voz, este mensaje se envió a las: "
                        + str(hora) + ":" + str(min2) + "horas", hora, min2)
                    # 4371095941
                    self.talk("El mensaje ya fué enviado")
                if "chiste" in (respuesta) or "broma" in (respuesta):
                    broma = (pyjokes.get_joke('es'))
                    print(broma)
                    self.talk(broma)
                if "traduce" in respuesta:
                    respuesta = respuesta.replace("traduce ", "")
                    traductor = Translator()
                    tradu = traductor.translate(str(respuesta), dest='en')

                    comp = "La traduccion es: " + str(tradu.text)
                    comp2 = "La traduccion es: " + str(tradu.pronunciation)
                    print(comp)
                    self.talk(comp2)
                if "qué hora es" in respuesta:
                    now = datetime.now()
                    hora = now.hour
                    tip = ""
                    tip2 = ""
                    if hora > 12:
                        hora = hora - 12
                        tip = "P.M"
                        tip2 = "PM"
                    else:
                        tip = "A.M"
                        tip2 = "AM"
                    min = now.minute
                    if hora == 1:
                        if min == 1:
                            frase = "es la " + str(hora) + " " + str(
                                tip2) + " con " + str(min) + " minuto"
                            frase2 = "Es la " + str(hora) + " " + str(
                                tip) + " con " + str(min) + " minuto"
                        else:
                            frase2 = "Es la " + str(hora) + " " + str(
                                tip) + " con " + str(min) + " minutos"
                            frase = "es la " + str(hora) + " " + str(
                                tip2) + " con " + str(min) + " minutos"
                    else:
                        if min == 1:
                            frase2 = "Son las " + str(hora) + " " + str(
                                tip) + " con " + str(min) + " minuto"
                            frase = "son las " + str(hora) + " " + str(
                                tip2) + " con " + str(min) + " minuto"
                        else:
                            frase2 = "Son las " + str(hora) + " " + str(
                                tip) + " con " + str(min) + " minutos"
                            frase = "son las " + str(hora) + " " + str(
                                tip2) + " con " + str(min) + " minutos"

                    threading.Thread(target=self.mensaje(frase2, self.console))
                    threading.Thread(target=self.talk(frase))
            self.reload()

        except Exception as e:
            print("No te entendi", e)
            self.talk("No comprendo lo que dijiste")
            self.reload()

    def talk(self, text):
        self.engine = pyttsx3.init()

        self.voices = self.engine.getProperty('voices')

        self.engine.setProperty('voice', self.voices[1].id)
        self.engine.setProperty('rate', 200)
        self.engine.setProperty('volume', 1)
        self.engine.say(text)
        #self.engine.save_to_file(text,"voz.mp3")
        self.engine.runAndWait()

    def talk2(self, text):
        #tts=gTTS(text=text,lang="es",tld="com.mx")
        #filename="voz.mp3"
        #tts.save(filename)
        filename = "voz.wav"
        playsound._playsoundWin(filename)

    def reload(self):
        pass

    def aceptar2(self):
        self.win = Toplevel()
        ancho_ventana = 720
        alto_ventana = 480
        x_ventana = self.win.winfo_screenwidth() // 2 - ancho_ventana // 2
        y_ventana = self.win.winfo_screenheight() // 2 - alto_ventana // 2
        posicion = str(ancho_ventana) + "x" + str(alto_ventana) + "+" + str(
            x_ventana) + "+" + str(y_ventana)
        self.win.geometry(posicion)
        self.win.config(bg=self.backcolor)
        self.win.wm_attributes('-topmost', False)
        self.win.iconbitmap('./images/icon.ico')
        # self.root.overrideredirect(False)
        self.win.resizable(0, 0)

        self.logo = Label(self.win, image=self.imagen2, bg=self.backcolor)
        self.logo.place(x=420, y=55)
        self.lbl1 = Label(self.win,
                          text=("Bienvenido " + self.name),
                          anchor="n",
                          justify=RIGHT,
                          width=33,
                          font=("Arial", 22),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl1.config(text="Contesta por favor con la verdad",
                         font=("Arial", 18))
        self.lbl1.place(x=20, y=10)
        self.lbl2 = Label(self.win,
                          text="La siguiente",
                          font=("Arial", 12),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl2.config(text="¿Cómo te llamas?")
        self.lbl2.place(x=28, y=50)
        self.ent1 = Entry(self.win, font=("Arial", 10), fg="black", width=44)
        self.ent1.place(x=20, y=80)
        self.lbl3 = Label(self.win,
                          text="¿Cuál es tu fecha de nacimiento?",
                          font=("Arial", 12),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl3.place(x=23, y=110)
        now = datetime.now()
        anio = now.year
        mes = now.month
        dia = now.day
        self.de = DateEntry(self.win,
                            locale='es_MX',
                            date_pattern='dd/mm/y',
                            year=anio,
                            month=mes,
                            day=dia,
                            width=26,
                            selectmode='day',
                            cursor="hand1",
                            font="Arial 14",
                            highlightthickness=0,
                            selectbackground='gray80',
                            selectforeground='black',
                            normalbackground='white',
                            normalforeground='black',
                            background='gray90',
                            foreground='black',
                            bordercolor='gray90',
                            othermonthforeground='gray50',
                            othermonthbackground='white',
                            othermonthweforeground='gray50',
                            othermonthwebackground='white',
                            weekendbackground='white',
                            weekendforeground='black',
                            headersbackground='white',
                            headersforeground='gray70')
        self.de.place(x=20, y=140)
        self.lbl4 = Label(self.win,
                          text="Selecciona un tema",
                          font=("Arial", 12),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl4.place(x=28, y=170)
        tema = StringVar()
        self.temas = ttk.Combobox(self.win,
                                  width=47,
                                  textvariable=tema,
                                  state="readonly")
        self.temas.set("Oscuro (por defecto)")
        self.temas['values'] = ('Claro', 'Oscuro (por defecto)', 'Verde',
                                'Rojo', 'Cielo', 'Morado')
        self.temas.place(x=20, y=200)
        self.temas.bind("<<ComboboxSelected>>", self.detecta_cambio2)

        self.lbl5 = Label(self.win,
                          text="Selecciona un idioma",
                          font=("Arial", 12),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl5.place(x=27, y=230)
        idiomas = StringVar()
        self.idioma = ttk.Combobox(self.win,
                                   width=47,
                                   textvariable=idiomas,
                                   state="readonly")
        self.idioma['values'] = ('Español', 'Ingles', 'Chino', 'Ruso',
                                 'Francés', 'portugués')
        self.idioma.place(x=20, y=260)
        self.idioma.bind("<<ComboboxSelected>>", self.detecta_idioma)

        self.lbl6 = Label(self.win,
                          text="Datos geograficos",
                          font=("Arial", 12),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl6.place(x=27, y=290)

        place2 = "CP"
        self.ent3 = Entry(self.win, font=("Arial", 12), width=10, fg='Grey')
        self.ent3.insert(0, place2)
        self.ent3.bind("<FocusIn>", lambda args: self.entradabox(self.ent3))
        self.ent3.bind("<FocusOut>",
                       lambda args: self.salidabox(place2, self.ent3))
        self.ent3.bind('<KeyRelease>',
                       lambda e: self.verifica(self.ent3, '0123456789'))
        self.ent3.place(x=20, y=320)

        place1 = "Ciudad"
        self.ent2 = Entry(self.win, font=("Arial", 12), fg='Grey', width=20)
        self.ent2.insert(0, place1)
        self.ent2.bind("<FocusIn>", lambda args: self.entradabox(self.ent2))
        self.ent2.bind("<FocusOut>",
                       lambda args: self.salidabox(place1, self.ent2))
        self.ent2.place(x=150, y=320)

        self.lbl7 = Label(self.win,
                          text="Estado",
                          font=("Arial", 12),
                          bg=self.backcolor,
                          fg=self.fgcolor)
        self.lbl7.place(x=20, y=350)

        estado = StringVar()
        self.estados = ttk.Combobox(self.win,
                                    width=48,
                                    textvariable=estado,
                                    state="readonly")
        self.estados['values'] = ("Aguascalientes", "Baja California",
                                  "Baja California Sur", "Campeche",
                                  "Coahuila de Zaragoza", "Colima", "Chiapas",
                                  "Chihuahua", "Distrito Federal", "Durango",
                                  "Guanajuato", "Guerrero", "Hidalgo",
                                  "Jalisco", "México", "Michoacán de Ocampo",
                                  "Morelos", "Nayarit", "Nuevo León", "Oaxaca",
                                  "Puebla", "Querétaro", "Quintana Roo",
                                  "San Luis Potosí", "Sinaloa", "Sonora",
                                  "Tabasco", "Tamaulipas", "Tlaxcala",
                                  "Veracruz de Ignacio de la Llave", "Yucatán",
                                  "Zacatecas")
        self.estados.place(x=20, y=380)

        self.btn3 = Button(self.win,
                           text="Confirmar",
                           width=22,
                           height=1,
                           command=self.llena,
                           font=("Arial", 18),
                           bg="#139134",
                           fg=self.fgcolor,
                           highlightthickness=0,
                           highlightcolor="green",
                           relief="flat",
                           activeforeground=self.fgcolor,
                           activebackground="green")
        self.btn3.place(x=20, y=410)

        self.idioma.update()
        self.win.mainloop()
Пример #23
0
class bookingpage(tk.Tk):
    def __init__(self,id, *args, **kwargs):
        # __init__ function for class Tk
        tk.Tk.__init__(self, *args, **kwargs)
        self.title("Booking")
        self.geometry("900x500")
        self.config(background="black", pady=10)

        lbs = tk.Label(self, text="Booking", bg="black", fg="white", font=20)
        lbs.place(x=110, y=5)
        self.id=id
        self.details()
    def details(self):
        lb2_name = tk.Label(self, text="Name - ", bg="black", fg="white")
        self.name = tk.Entry(self)
        lb2_name.place(x=10, y=40)
        self.name.place(x=110, y=40)

        lb2_guest = tk.Label(self, text="No of Guest ", bg="black", fg="white")
        self.guest = tk.Entry(self)
        lb2_guest.place(x=10, y=80)
        self.guest.place(x=110, y=80)

        self.tkvar = tk.StringVar(self)

        # Dictionary with options

        choice = {'Standard', 'Deluxe', 'Luxury'}
        self.tkvar.set('Select')  # set the default option

        popupMenu = tk.OptionMenu(self, self.tkvar, *choice,command=self.check_acc)
        tk.Label(self, text="Room Type",bg="black", fg="white").place(x=10, y=120)
        popupMenu.place(x=110, y=120)

        lb2_room = tk.Label(self, text="No Of Room - ", bg="black", fg="white")
        self.room = tk.Entry(self)
        lb2_room.place(x=10, y=160)
        self.room.place(x=110, y=160)

        # lb2_s = tk.Label(self, text="Email - ", bg="black", fg="white")
        # self.lb2_s2 = tk.Entry(self)
        # lb2_s.place(x=10, y=200)
        # self.lb2_s2.place(x=110, y=200)

        current_date = date.today()
        self.cur_date=current_date
        tomorrow = date.today() + timedelta(1)
        label1 = tk.Label(self, text='Check In Date',bg="black", fg="white")
        label1.place(x='10', y='200')
        self.cal = DateEntry(self, width=12, year=current_date.year, month=current_date.month, day=current_date.day,
                             mindate=current_date, date_pattern='y-mm-dd',
                             background='darkblue', foreground='white', borderwidth=2)
        self.cal.place(x='110', y='200')
        label2 = tk.Label(self, text='Check out Date',bg="black", fg="white")
        label2.place(x='240', y='200')
        self.cal.bind("<<DateEntrySelected>>", self.callback)
        date_time_obj = datetime.datetime.strptime(self.cal.get(), '%Y-%m-%d')
        # print(type(date_time_obj))
        # if self.cal.get():
        #     min_date=self.cal.get()
        # else:
        #    min_date=tomorrow
        lb2_s = tk.Label(self, text="Price - ", bg="black", fg="white")
        self.price = tk.Label(self,bg="black", fg="white")
        lb2_s.place(x=10, y=240)
        self.price.place(x=110, y=240)
        self.cal1 = DateEntry(self, width=12, year=tomorrow.year, month=tomorrow.month, day=tomorrow.day,
                              mindate=tomorrow, date_pattern='y-mm-dd',
                              background='darkblue', foreground='white', borderwidth=2)
        self.cal1.place(x='380', y='200')
        # reg = self.register(self.callback)
        #
        # self.cal1.config(validate="key",
        #          validatecommand=(reg, '% P'))
        # button = tk.Button(self, text='Search', command=self.search)
        # button.place(x='150', y='120')
        try:

            mycursor = mydb.cursor()

            mycursor.execute("SELECT * FROM hotel_name where id=%s"%self.id)

            self.myresult = mycursor.fetchall()
            print(self.myresult)
            im = Image.open(r"%s" % self.myresult[0][5])
            image = im
            self.background_image = ImageTk.PhotoImage(im)
            lb_hotel = tk.Label(self, text=self.myresult[0][1], bg="black", fg="white", font=20)
            lb_hotel.place(x=400, y=40)
            row = 50
            lb_img = tk.Label(self,image=self.background_image,height=50,width=50)
            lb_img.place(x=400, y=80)
            lb_img.photo=self.background_image



        except:
           print("No result")
        button = tk.Button(self, text="book", command=self.book)
        button.place(x='120', y='280')

    def callback(self,input):
        w = input.widget
        date = w.get_date()+timedelta(1)
        self.cal1.config(mindate=date)

    def book(self):
        try:
            mycursor = mydb.cursor()

            sql = "INSERT INTO booking (name,no_guest,room_type,checkin,checkout,hot_name,book_date,total) VALUES (%s, %s,%s,%s,%s,%s,%s,%s)"
            val = (
                self.name.get(), self.guest.get(), self.tkvar.get(), self.cal.get(), self.cal1.get(), self.myresult[0][1],self.cur_date,(self.p*int(self.room.get())))
            mycursor.execute(sql, val)

            mydb.commit()

            print(mycursor.rowcount, "record inserted.")
            self.display=tk.Label(self)
            self.display2.config(bg="green", fg="white", text="Saved Success")

            self.display2.place(x=20, y=1)
        except:
            self.display = tk.Label(self)
            self.display2.config(bg="red", fg="white", text="Not Saved")

            self.display2.place(x=20, y=1)



    def check_acc(self,event):
        selected = self.tkvar.get()
        self.dic={'Standard':7,'Deluxe':8,'Luxury':9}
        self.dic2 = {'Standard': 2, 'Deluxe': 3, 'Luxury': 4}
        if(self.myresult[0][self.dic2[selected]]==0):
            lab=tk.Label(self,text="Room Full")
            lab.place(x=200,y=120)
        else:
            if (len(selected) != 0):
                self.price.config(text=self.myresult[0][self.dic[selected]], bg="black", fg="white")
                self.p=self.myresult[0][self.dic[selected]]
Пример #24
0
class Frequencia(object):

    IMGDIR = os.path.join(os.path.dirname(__file__), 'imagens')

    def __init__(self, root, model):
        self.toplevel = root
        self.toplevel.title('Controle de Frequência')
        self.modelo = model()

        self.operacao = 'Browse'
        self.info_label = StringVar()
        """Configuração inicial dos radiobutton"""
        self.presenca = StringVar()
        self.PRESENCA = [("Presente", "P"), ("Ausente", "F"),
                         ("Justificada", "J")]
        self.presenca.set("P")

        self.ANO = [2019, 2020, 2021, 2022]
        """Estilos"""
        style = ttk.Style()
        style.configure("BW.TLabel",
                        padding=6,
                        foreground="white",
                        background="brown",
                        font=('helvetica', 9, 'bold'))
        style.configure("BW.TEntry",
                        padding=6,
                        background="#ccc",
                        relief="flat")
        #opcoes combobox -column, -columnspan, -in, -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky
        style.configure("BW.TCombo", ipady=5, relief="flat")
        style.configure("BW.TButton",
                        padding=6,
                        relief="flat",
                        background="#ccc")
        style.configure('BW.Treeview',
                        highlightthickness=0,
                        bd=0,
                        font=('Calibri', 11))
        style.configure("BW.Treeview.Heading",
                        background="blue",
                        foreground="brown",
                        relief="flat")
        style.configure("BW.TDataentry",
                        fieldbackground='light green',
                        background='dark green',
                        foreground='dark blue',
                        arrowcolor='white')
        """Imagens para os botões"""
        self.btnNewImage = PhotoImage(file=self.IMGDIR +
                                      '\\new.png').subsample(3, 3)
        self.btnDelImage = PhotoImage(file=self.IMGDIR +
                                      '\\del.png').subsample(3, 3)
        self.btnSaveImage = PhotoImage(file=self.IMGDIR +
                                       '\\disk_save.png').subsample(3, 3)
        self.btnCancelImage = PhotoImage(file=self.IMGDIR +
                                         '\\cancel.png').subsample(3, 3)
        self.btnLoopImage = PhotoImage(
            file=self.IMGDIR + '\\iconfinder_refresh_326679.png').subsample(
                3, 3)
        self.btnCloseImage = PhotoImage(
            file=self.IMGDIR +
            '\\iconfinder_icons_exit2_1564506.png').subsample(3, 3)

        self.searchFrame = ttk.Frame(self.toplevel)
        self.searchFrame.grid(column=0, row=0, padx=10, pady=10, columnspan=2)
        self.tableFrame = ttk.Frame(self.toplevel)
        self.tableFrame.grid(column=0, row=1, padx=10, pady=10)
        self.formFrame = ttk.LabelFrame(self.toplevel, text='Informações')
        self.formFrame.grid(column=1, row=1, padx=10, pady=10)

        self.statusFrame = ttk.Frame(self.toplevel, border=1, relief=FLAT)
        self.statusFrame.grid(column=0, row=2, padx=10, pady=10, columnspan=2)

        root.grid_rowconfigure(2, weight=1)
        root.grid_columnconfigure(1, weight=1)

        self.createtable()
        self.createsearch()
        self.createform()
        self.createBarraStatus()
        self.estadoBotoes()

    def createform(self):
        self.container1 = Frame(self.formFrame)
        self.container1['pady'] = 10
        self.container1.grid(row=1, column=0)
        self.lblCadastro = ttk.Label(self.container1,
                                     style="BW.TLabel",
                                     text="Cadastro:",
                                     width=12)
        self.lblCadastro.pack(side=LEFT)
        self.txtCadastro = ttk.Entry(self.container1, style="BW.TEntry")
        self.txtCadastro['state'] = DISABLED
        self.txtCadastro['width'] = 20
        self.txtCadastro.pack(side=LEFT, padx=(10, 5))

        self.container2 = Frame(self.formFrame)
        self.container2['pady'] = 10
        self.container2.grid(row=2, column=0)
        self.lblReuniao = ttk.Label(self.container2,
                                    style="BW.TLabel",
                                    text="Data Reunião:",
                                    width=12)
        self.lblReuniao.pack(side=LEFT)
        # self.txtReuniao = ttk.Entry(self.container2, style="BW.TEntry")
        # self.txtReuniao['width'] = 20
        # self.txtReuniao['state'] = DISABLED
        # self.txtReuniao.pack(side=LEFT, padx=(10, 5))
        # self.txtReuniao.bind("<FocusOut>", self.formatadata)
        self.txtReuniao = DateEntry(self.container2,
                                    width=11,
                                    background='darkblue',
                                    foreground='white',
                                    borderwidth=2,
                                    year=2019,
                                    locale='pt_BR',
                                    date_pattern='yyyy-MM-dd')
        self.txtReuniao.pack(side=LEFT, ipadx=25, padx=(10, 5))

        self.container3 = Frame(self.formFrame)
        self.container3['pady'] = 10
        self.container3.grid(row=3, column=0)
        for text, mode in self.PRESENCA:
            self.rdbPresenca = Radiobutton(self.container3,
                                           text=text,
                                           variable=self.presenca,
                                           value=mode)
            self.rdbPresenca.pack(anchor=W, side=LEFT, expand=1)
        """ Cria os botões de ações """
        self.container4 = ttk.Frame(self.formFrame)
        self.container4.grid(row=4, column=0, pady=10)
        self.btnNew = ttk.Button(self.container4,
                                 style="BW.TButton",
                                 compound=LEFT)
        self.btnNew['text'] = 'Nova'
        self.btnNew['width'] = 5
        self.btnNew['command'] = self.cadastraFrequencia
        self.btnNew['image'] = self.btnNewImage
        self.btnNew.pack(side=LEFT, padx=10, pady=10)

        self.btnExcluir = ttk.Button(self.container4,
                                     style="BW.TButton",
                                     compound=LEFT)
        self.btnExcluir['text'] = 'Excluir'
        self.btnExcluir['width'] = 6
        self.btnExcluir['command'] = self.excluirFrequencia
        self.btnExcluir['image'] = self.btnDelImage
        self.btnExcluir.pack(side=LEFT, padx=10, pady=10)

        self.btnSave = ttk.Button(self.container4,
                                  style="BW.TButton",
                                  compound=LEFT)
        self.btnSave['text'] = 'Salvar'
        self.btnSave['width'] = 6
        self.btnSave['command'] = self.saveFrequencia
        self.btnSave['image'] = self.btnSaveImage
        self.btnSave.pack(side=LEFT, padx=10, pady=10)

        self.btnCancel = ttk.Button(self.container4,
                                    style="BW.TButton",
                                    compound=LEFT)
        self.btnCancel['text'] = 'Cancelar'
        self.btnCancel['width'] = 8
        self.btnCancel['command'] = self.cancelaFrequencia
        self.btnCancel['image'] = self.btnCancelImage
        self.btnCancel.pack(side=LEFT, padx=10, pady=10)

    def createtable(self):
        self.tree = ttk.Treeview(self.tableFrame,
                                 column=(1, 2, 3),
                                 show="headings",
                                 selectmode='browse')
        self.tree['style'] = "BW.Treeview"
        self.tree.grid(row=0, column=0, columnspan=2, sticky='nsew')
        self.tree.heading(1, text='#')
        self.tree.heading(2, text='Data')
        self.tree.heading(3, text='Frequência')
        self.tree.column(1, width=50, anchor='center')
        self.tree.column(2, width=100, anchor='center')
        self.tree.column(3, width=150, anchor='center')
        self.tree.bind('<Double-Button-1>', self.EditMember)  #clique duplo
        self.tree.bind('<Button-1>', self.navega)
        self.scroll = ttk.Scrollbar(self.tableFrame, orient=VERTICAL)
        self.scroll.grid(row=0, column=3, sticky='ns')
        self.tree.config(yscrollcommand=self.scroll.set)
        self.scroll.config(command=self.tree.yview)

    def createsearch(self):
        self.label = ttk.Label(self.searchFrame,
                               text='Pesquisa: ',
                               style='BW.TLabel',
                               compound=LEFT)
        self.label.grid(column=0, row=0, padx=(5, 5))
        self.cbxData = ttk.Combobox(self.searchFrame, values=self.ANO)
        self.cbxData.current(0)
        self.cbxData.grid(row=0, column=1, ipady=5)
        self.txtSearch = ttk.Entry(self.searchFrame, style="BW.TEntry")
        self.txtSearch.focus_set()
        self.txtSearch.grid(row=0,
                            column=2,
                            columnspan=4,
                            sticky=W,
                            ipadx=50,
                            padx=(10, 5))
        #fazer o bind para a statusbar
        self.txtSearch.bind(
            "<FocusIn>", lambda event: self.statuscommand(
                'Entre com o número do cadastro.'))
        self.btnSearch = ttk.Button(self.searchFrame,
                                    style="BW.TButton",
                                    compound=LEFT)
        self.btnSearch['text'] = 'Localizar'
        self.btnSearch['width'] = 10
        self.btnSearch['command'] = self.localizarmember
        self.btnSearch.grid(row=0, column=6, padx=(10, 5))

    def createBarraStatus(self):
        self.lblMessage = ttk.Label(self.statusFrame,
                                    textvar=self.info_label,
                                    relief=SUNKEN)
        self.lblMessage.pack(expand=1, fill=X, pady=10, padx=5)

    def statuscommand(self, texto):
        self.info_label.set(texto)

    def localizarmember(self):
        md = self.modelo
        valor = self.txtSearch.get()
        md.num_cadastro = valor
        md.ano = self.cbxData.get()
        lista = md.getmember()
        try:
            if len(lista) == 0:
                items = self.tree.get_children()
                self.operacao = 'Browse'
                for item in items:
                    self.tree.delete(item)
            else:
                items = self.tree.get_children()
                for item in items:
                    self.tree.delete(item)
                for row in lista:
                    self.tree.insert('',
                                     'end',
                                     values=(row[0], row[1], row[2]))
                self.txtCadastro.insert(0, self.txtSearch.get())
                self.operacao = 'Insert'
                self.estadoBotoes()

        except:
            self.mensagem(
                'Aviso',
                'O registro de cadastro nº{} não foi localizado.\nOu não há registro para o ano informado.'
                .format(valor))

    def reloadTable(self):
        md = self.modelo
        md.num_cadastro = self.txtSearch.get()
        md.ano = self.cbxData.get()
        lista = md.getmember()
        items = self.tree.get_children()
        for item in items:
            self.tree.delete(item)
        for row in lista:
            self.tree.insert('', 'end', values=(row[0], row[1], row[2]))

    def navega(self, event):
        self.operacao = 'Delete'
        self.estadoBotoes()

    def EditMember(self, event):
        selection = self.tree.selection()
        for selection in self.tree.selection():
            currentItem = self.tree.set(selection, "#1")
            if currentItem:
                lista = self.modelo.getById(currentItem)
                for row in lista:
                    self.id = row[0]
                    self.txtReuniao['state'] = NORMAL
                    self.txtCadastro.delete(0, END)
                    self.txtCadastro.insert(0, row[1])
                    self.txtReuniao.delete(0, END)
                    self.txtReuniao.insert(0, row[2])
                    self.presenca.set(row[3])
                    self.operacao = 'Edit'
                    self.estadoBotoes()
        return

    """Outras funções"""

    def saveFrequencia(self):
        md = self.modelo
        selection = self.tree.selection()
        for selection in self.tree.selection():
            currentItem = self.tree.set(selection, "#1")
            if currentItem:
                md.id = currentItem
        if self.txtCadastro.get() == '':
            md.num_cadastro = self.txtSearch.get()
        else:
            md.num_cadastro = self.txtCadastro.get()
        md.data_reuniao = self.txtReuniao.get()
        md.presenca = self.presenca.get()
        md.ano = self.pegaano(self.txtReuniao.get())
        self.mensagem('Incluir/Alterar', md.savefrequencia(self.operacao))
        self.txtReuniao.delete(0, END)
        self.txtReuniao['state'] = DISABLED
        self.operacao = 'Insert'
        self.estadoBotoes()
        self.reloadTable()

    def excluirFrequencia(self):
        selection = self.tree.selection()
        for selection in self.tree.selection():
            currentItem = self.tree.set(selection, "#1")
            if currentItem:
                lista = self.modelo.delete(currentItem)
                self.mensagem('Delete', lista)
                #self.createtable()
                self.reloadTable()
                self.operacao = 'Delete'
                self.estadoBotoes()
                break
        else:
            self.error('Aviso', 'Você deve selecionar um item primeiro.')

    def cancelaFrequencia(self):
        self.operacao = 'Delete'
        self.estadoBotoes()

    def cadastraFrequencia(self):
        #limpa as caixas de texto
        self.txtReuniao.delete(0, END)
        self.txtReuniao['state'] = NORMAL
        self.operacao = 'Novo'
        self.estadoBotoes()

    def estadoBotoes(self):
        if self.operacao == 'Browse':
            self.btnNew['state'] = DISABLED
            self.btnExcluir['state'] = DISABLED
            self.btnSave['state'] = DISABLED
            self.btnCancel['state'] = DISABLED
        elif self.operacao == 'Insert':
            self.btnNew['state'] = NORMAL
            self.btnExcluir['state'] = DISABLED
            self.btnSave['state'] = DISABLED
            self.btnCancel['state'] = DISABLED
        elif self.operacao == 'Novo':
            self.btnNew['state'] = DISABLED
            self.btnExcluir['state'] = DISABLED
            self.btnSave['state'] = NORMAL
            self.btnCancel['state'] = NORMAL
        elif self.operacao == 'Delete':
            self.btnNew['state'] = NORMAL
            self.btnExcluir['state'] = NORMAL
            self.btnSave['state'] = DISABLED
            self.btnCancel['state'] = DISABLED
        elif self.operacao == 'Edit':
            self.btnNew['state'] = DISABLED
            self.btnExcluir['state'] = DISABLED
            self.btnSave['state'] = NORMAL
            self.btnCancel['state'] = NORMAL

    def exitForm(self):
        self.toplevel.destroy()

    def mensagem(self, tipo, msg):
        messagebox.showinfo(tipo, msg)

    def error(self, tipo, msg):
        messagebox.showwarning(tipo, msg)

    def validate_text(self, texto):
        if len(texto) == 0:
            return False
        else:
            return True

    def pegaano(self, ano):
        ano = ano.split('-')
        return ano[0]
Пример #25
0
class PaginaResumen(tk.Frame):
    def __init__(self, padre,  controlador):

        #####################################
        #CARGA INICIAL DEL OBJETO PÁGINA#
        #####################################
        tk.Frame.__init__(self, padre)
        ##setup para archivos excel
        self.controlador =  controlador
        self.ruta=controlador.ruta
        self.archivo="Asesor.xlsx"
        self.salida = os.path.join(self.ruta,self.archivo)
        #####################################
        #GRÁFICOS#
        #####################################
        label = tk.Label(self, text="Resumen de Facturas", font=controlador.fuente_titulo)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Ir al principio",
                           command=lambda:  controlador.mostrar_marco("PaginaInicial"))
        self.etiqueta_fecha_inicio = tk.Label(self, text="Fecha inicial para el EXCEL")
        self.cal_inicio = DateEntry(self, width=12, background='darkblue',
                        foreground='white', borderwidth=2, locale='es_ES')
        self.cal_inicio.set_date(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),1,1))

        self.etiqueta_fecha_final = tk.Label(self, text="Fecha final para el EXCEL")
        self.cal_fin = DateEntry(self, width=12, background='darkblue',
                        foreground='white', borderwidth=2, locale='es_ES')
        self.cal_fin.set_date(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),12,31))
     
        button2 = tk.Button(self, text="Facturado entre fechas",
                           command=lambda: self.trimestral(self.cal_inicio.get(),self.cal_fin.get()))
        button3 = tk.Button(self, text="Facturado anual",
                           command=lambda: self.trimestral(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),1,1),datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),12,31)))
        
        button4 = tk.Button(self, text="Facturado 1T",
                           command=lambda: self.trimestral(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),1,1),datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),3,31)))
        button5 = tk.Button(self, text="Facturado 2T",
                           command=lambda: self.trimestral(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),4,1),datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),6,30)))
        button6 = tk.Button(self, text="Facturado 3T",
                           command=lambda: self.trimestral(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),6,30),datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),9,30)))
        button7 = tk.Button(self, text="Facturado 4T",
                           command=lambda: self.trimestral(datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),10,1),datetime(2000+int(self.controlador.marcos["PaginaInicial"].configuracion["año"]),12,31)))
        
        button.pack()
        self.etiqueta_fecha_inicio.pack()
        self.cal_inicio.pack()
        
        self.etiqueta_fecha_final.pack()
        self.cal_fin.pack()

        button2.pack()
        button3.pack()
        button4.pack()
        button5.pack()
        button6.pack()
        button7.pack()
        datos_cliente_inicial=[('','Clientes contado','','','','','','','')]


        try:
            crearCliente(datos_cliente_inicial)
        except:
            print('Cliente ya creado')
        try:
            self.controlador.marcos['PaginaInicial'].actualizar()#hasta que no están todas las páginas creadas no puedo asignar la numeración automática, esta es la última página en inicializarse, por eso lo pongo aquí
        except:
            print('Sin id_factura')

        #####################################
        #FUNCIONES#
        #####################################
    def trimestral(self, fecha_inicial, fecha_final):
        #facturas = leerTodo("FACTURA")
        #clientes = leerTodo("CLIENTE")

        consulta = todoFacturasClientes("CODIGO_FACTURA", "FECHA_FACTURA", fecha_inicial, fecha_final)
        
        print ("Esta es la consulta que recibe antes de pasar a excel: \n",consulta)
        excel = Workbook()
        hoja= excel.active
        hoja.title = "Facturado"
       

        fila_ptr = 1 #los utilizo a modo de punteros
        columna_ptr = 1
        #1ª fila
        hoja.cell(column=columna_ptr, row=fila_ptr, value=f"Declarado entre {fecha_inicial} y {fecha_final}")
        fila_ptr +=1
        #2ª fila
        hoja.cell(column=columna_ptr, row=fila_ptr, value="Factura")
        columna_ptr +=1
        hoja.cell(column=columna_ptr, row=fila_ptr, value="Fecha")
        columna_ptr +=1
        hoja.cell(column=columna_ptr, row=fila_ptr, value="Cliente")
        columna_ptr +=1
        hoja.cell(column=columna_ptr, row=fila_ptr, value="DNI")
        columna_ptr +=1
        hoja.cell(column=columna_ptr, row=fila_ptr, value="Fecha Factura")
        columna_ptr +=1
        hoja.cell(column=columna_ptr, row=fila_ptr, value="Servicios realizados")
        columna_ptr +=1
        hoja.cell(column=columna_ptr, row=fila_ptr, value="€")
        columna_ptr +=1
        hoja.cell(column=columna_ptr, row=fila_ptr, value="IVA %")
        columna_ptr +=1
        hoja.cell(column=columna_ptr, row=fila_ptr, value="Descuento % ")
        columna_ptr +=1
        hoja.cell(column=columna_ptr, row=fila_ptr, value="Total facturado €(Impuestos y descuentos incluidos")
        columna_ptr =1
        fila_ptr +=1
        #3ª fila
        factura_leida = "ninguna"
        
        acumulado = 0
        servicios_contados=1
        for info in consulta:
            if factura_leida == info[1]:

                servicios_contados+=1
                acumulado +=info[-2]

                print ("se tiene en cuenta ", acumulado)
                hoja.cell(column=columna_ptr+5, row=fila_ptr-1, value=f"{servicios_contados} Tratamientos")
                hoja.cell(column=columna_ptr+6, row=fila_ptr-1, value=acumulado)
                hoja.cell(column=columna_ptr+9, row=fila_ptr-1, value=round((acumulado*(1+info[3]/100))*(1-info[4]/100),2))
                continue
            else:
                acumulado = 0
                servicios_contados=1
                

            
            factura_leida = info[1]
            hoja.cell(column=columna_ptr, row=fila_ptr, value=factura_leida)#codigo
            columna_ptr +=1
            hoja.cell(column=columna_ptr, row=fila_ptr, value=info[2])#fecha
            columna_ptr +=1
            hoja.cell(column=columna_ptr, row=fila_ptr, value=info[9]+' '+info[10]) #nombre
            columna_ptr +=1
            hoja.cell(column=columna_ptr, row=fila_ptr, value=info[8])#DNI
            columna_ptr +=1
            hoja.cell(column=columna_ptr, row=fila_ptr, value=info[-4])#fecha último servicio
            columna_ptr +=1
            hoja.cell(column=columna_ptr, row=fila_ptr, value=info[-3])#tratamiento
            columna_ptr +=1
            hoja.cell(column=columna_ptr, row=fila_ptr, value=info[-2])#Precio del tratamiento
            columna_ptr +=1
            hoja.cell(column=columna_ptr, row=fila_ptr, value=info[3])#IVA
            columna_ptr +=1
            hoja.cell(column=columna_ptr, row=fila_ptr, value=info[4])#Descuento
            columna_ptr +=1
            acumulado += info[-2]*(1+float(info[3])/100)*(1-float(info[4])/100)
            acumulado = round(acumulado, 2)
            hoja.cell(column=columna_ptr, row=fila_ptr, value=acumulado)
            columna_ptr =1
            fila_ptr +=1
            
            print(info)

        #Grabar el archivo
        excel.save(filename=self.salida)
        comando = "start excel.exe "+"\""+ self.salida +"\""+" &"
        os.system(comando)
Пример #26
0
class StudySessionEntryScreen(tk.Frame):
    '''This class populates the window with study session entry screen stuff.'''
    def __init__(self, master, ids):
        tk.Frame.__init__(self, master)

        [self.emp_id, self.student_id] = ids.split(",")
        self.configure(bg="white")

        font10 = "-family {Noto Sans} -size 18"
        font9 = "-family {Noto Sans} -size 24"

        master.title("Dolphin Dollars Study Session Entry")

        label_1 = tk.Label(self)
        label_1.place(relx=0.5, rely=0.067, anchor="center")
        label_1.configure(background="#ffffff",
                          cursor="fleur",
                          disabledforeground="#ffffff",
                          font=font9,
                          foreground="#ed1c24",
                          text='''Dolphin Dollars''')

        label_2 = tk.Label(self)
        label_2.place(relx=0.5, rely=0.178, anchor="center")
        label_2.configure(background="#ffffff",
                          cursor="fleur",
                          font=font10,
                          text='''Study Session Submission''')

        label_3 = tk.Label(self)
        label_3.place(relx=0.25, rely=0.333, anchor="e")
        label_3.configure(background="#ffffff",
                          justify='right',
                          text='''Study Session Date:''')

        self.cal = DateEntry(self,
                             background='#ed1c24',
                             foreground='white',
                             borderwidth=2)
        self.cal.place(relx=0.4, rely=0.333, anchor="center")

        submit_button = tk.Button(self)
        submit_button.place(relx=0.4,
                            rely=0.875,
                            height=50,
                            width=150,
                            anchor="center")
        submit_button.configure(background="#ed1c24",
                                foreground="#ffffff",
                                text='''Submit''',
                                command=self.submit)

        cancel_button = tk.Button(self)
        cancel_button.place(relx=0.8,
                            rely=0.875,
                            height=50,
                            width=150,
                            anchor="center")
        cancel_button.configure(background="#ed1c24",
                                foreground="#ffffff",
                                text='''Cancel''',
                                command=self.go_back)

    def submit(self):
        '''Contacts the database to authenticate the employee.'''
        date = self.cal.get()
        self.master.execute(
            "CALL studySessionAssignmentDeposit(STR_TO_DATE('{}', '%m/%d/%Y'),{}, {})"
            .format(date, self.student_id, self.emp_id))

    def go_back(self):
        '''Returns to the student home screen.'''
        self.master.switch_frame(student_home_screen.StudentHomeScreen,
                                 "{},{}".format(self.emp_id, self.student_id))
Пример #27
0
class PerDayAccountingWidgetsBox(Frame):
    def __init__(self,
                 parent,
                 input_client_vacancy_list=None,
                 input_clients_info_list=None):
        Frame.__init__(self, parent)
        self.config(bg="light green")
        self.input_client_vacancy_list = copy.deepcopy(
            input_client_vacancy_list)
        self.input_clients_info_list = copy.deepcopy(input_clients_info_list)

        self.border_color = "#dbdbdb"
        self.bg_color_light = "light gray"

        self.another_frame_color = "#bfffa3"
        self.fg_color = "black"

        self.create_widgets()

    def create_widgets(self):
        self.current_dir = os.getcwd()

        self.top_frame = Frame(self, bg="blue")
        self.top_frame.pack(side=TOP, fill=BOTH, expand=NO)

        self.top_frame_top_half_frame = CustomFrame(self.top_frame)
        self.top_frame_top_half_frame.set_bg("light blue")
        self.top_frame_top_half_frame.pack(side=TOP, fill=BOTH, expand=YES)

        self.date_lbl = CustomLabel(self.top_frame_top_half_frame, fill=BOTH)
        self.date_lbl.set_bg_color(self.border_color)
        self.date_lbl.set_fg_color("black")
        self.date_lbl.set_text(text="Дата", font=("Ubuntu", 14))
        self.date_lbl.pack(side=LEFT, fill=BOTH, expand=YES)

        self.calendar_widget = DateEntry(self.top_frame_top_half_frame,
                                         width=12,
                                         font=("Ubuntu", 12),
                                         background='blue',
                                         foreground='white',
                                         borderwidth=2)
        self.calendar_widget.pack(side=LEFT, fill=BOTH, expand=YES)

        self.save_button = CustomButton(
            self.top_frame_top_half_frame,
            background=self.border_color,
            foreground="green",
            activebackground=self.another_frame_color,
            height=1,
            relief=FLAT,
            overrelief=SOLID,
            font=("Ubuntu", 12, "bold"),
            justify=CENTER,
            text="Сохранить",
            command=self.save_data,
        )
        self.save_button.pack(side=LEFT, fill=BOTH, expand=YES)

        self.top_frame_bottom_half_frame = Frame(self.top_frame,
                                                 bg="light gray")
        self.top_frame_bottom_half_frame.pack(side=TOP, fill=X, expand=NO)

        self.create_label_frames(self.top_frame_bottom_half_frame,
                                 self.fg_color)

        self.middle_frame = VerticalScrollFrame(self)
        self.middle_frame.pack(side=TOP, fill=BOTH, expand=YES)

        self.clients_box = WidgetsBox(self.middle_frame.interior)
        self.clients_box.pack(side=TOP, fill=BOTH, expand=YES)
        self.clients_box.set_bg_color("RED")

        self.bottom_frame = Frame(self, bg="yellow")
        self.bottom_frame.pack(side=TOP, fill=BOTH, expand=NO)

        self.fill_widgets()

    def fill_widgets(self):
        self.in_box_widgets = []
        self.in_widget_clients = self.input_clients_info_list

        for gg in range(len(self.in_widget_clients)):

            client_shift_widget = self.clients_box.create_widget_inside(
                "Shift")
            client_shift_widget.name_frame.create_label(
                self.in_widget_clients[gg], self.bg_color_light, 13,
                self.fg_color)
            self.label_1.assign_another_widget(client_shift_widget.name_frame)
            self.label_2.assign_another_widget(
                client_shift_widget.shift_type_frame)
            self.label_3.assign_another_widget(
                client_shift_widget.shift_duration_frame)
            self.label_4.assign_another_widget(
                client_shift_widget.food_cost_frame)
            self.label_5.assign_another_widget(
                client_shift_widget.residence_frame)
            self.label_6.assign_another_widget(
                client_shift_widget.penalty_frame)
            self.label_7.assign_another_widget(
                client_shift_widget.prepayment_frame)

            client_shift_widget.pack(side=TOP, fill=BOTH, expand=YES)
            self.in_box_widgets.append([
                client_shift_widget, self.in_widget_clients[gg][0],
                self.input_client_vacancy_list[gg]
            ])

        self.client_shift_widget_additional = ShiftWidget(self.bottom_frame,
                                                          font=("Ubuntu", 13),
                                                          state="additional")
        self.client_shift_widget_additional.name_frame.create_button(
            "Добавить", self.bg_color_light, 13, self.fg_color,
            self.add_another_client)
        self.client_shift_widget_additional.pack(side=TOP,
                                                 fill=BOTH,
                                                 expand=YES)

    def add_another_client(self):
        self.find_client_window()
        print("waiting for func return ...")

    def create_widget_on_adding(self):

        adding_client_info_list = self.find_client_dialog_returned_value[
            'values']
        print(adding_client_info_list)
        print(adding_client_info_list[1])

        client_shift_widget = self.clients_box.create_widget_inside("Shift")
        client_shift_widget.name_frame.create_label(adding_client_info_list,
                                                    self.bg_color_light, 13,
                                                    self.fg_color)
        self.label_1.assign_another_widget(client_shift_widget.name_frame)
        self.label_2.assign_another_widget(
            client_shift_widget.shift_type_frame)
        self.label_3.assign_another_widget(
            client_shift_widget.shift_duration_frame)
        self.label_4.assign_another_widget(client_shift_widget.food_cost_frame)
        self.label_5.assign_another_widget(client_shift_widget.residence_frame)
        self.label_6.assign_another_widget(client_shift_widget.penalty_frame)
        self.label_7.assign_another_widget(
            client_shift_widget.prepayment_frame)

        self.client_shift_widget_additional.pack_forget()
        client_shift_widget.pack(side=TOP, fill=BOTH, expand=YES)
        self.client_shift_widget_additional.pack(side=TOP,
                                                 fill=BOTH,
                                                 expand=YES)
        self.middle_frame.force_update()

        self.in_box_widgets.append(
            [client_shift_widget, self.in_widget_clients[0]])

    def find_client_window(self):
        self.finded_client_info = ''
        find_client_window = FindClientScript.FindWindowUI(
            self.bg_color_light, self.border_color, self.border_color,
            self.border_color, 14, self.current_dir, 5,
            self.finded_client_info, self.return_value_from_find_client_dialog,
            self)

    def return_value_from_find_client_dialog(self, client_info_list):
        self.find_client_dialog_returned_value = copy.deepcopy(
            client_info_list)
        self.create_widget_on_adding()

    def save_data(self):
        info_list = []
        for gg in range(len(self.in_box_widgets)):
            info_list.append(self.in_box_widgets[gg][0].give_away_shift_info())
        date = self.calendar_widget.get()
        path = self.current_dir + "\\clients_reports"
        if os.path.exists(path):
            pass
        else:
            os.mkdir(path)
        all_client_dicts = []

        for wp in range(len(info_list)):
            client_dict = {
                "client_id": self.in_box_widgets[wp][1],
                "client_vacancy_id": self.in_box_widgets[wp][2],
                "client_name": info_list[wp][0],
                "shift_type": info_list[wp][1],
                "shift_hours": info_list[wp][2],
                "shift_food_cost": info_list[wp][3],
                "shift_residence_cost": info_list[wp][4],
                "shift_penalty_cost": info_list[wp][5],
                "shift_prepayments_cost": info_list[wp][6],
                "shift_paid_state": [False, [0, 0]],
            }
            all_client_dicts.append(client_dict)

        data = {"clients_shifts_reports": all_client_dicts}
        with open(path + '\\date_' + str(date) + '.json',
                  "w",
                  encoding='utf-8') as write_file:
            json.dump(data, write_file, ensure_ascii=False)

    def create_label_frames(self, parent, fg_color):
        self.label_1 = CustomLabelWithBorder(parent, height=2)
        self.label_1.set_bg_color(self.bg_color_light)
        self.label_1.set_fg_color(fg_color)
        self.label_1.set_text("Имя сотрудника", ("Ubuntu", 14))
        self.label_1.pack(side=LEFT, expand=YES, fill=X)

        self.label_2 = CustomLabelWithBorder(parent, height=2)
        self.label_2.set_bg_color(self.bg_color_light)
        self.label_2.set_fg_color(fg_color)
        self.label_2.set_text("Тип смены", ("Ubuntu", 14))
        self.label_2.pack(side=LEFT, expand=YES, fill=X)

        self.label_3 = CustomLabelWithBorder(parent, height=2)
        self.label_3.set_bg_color(self.bg_color_light)
        self.label_3.set_fg_color(fg_color)
        self.label_3.set_text("Часов", ("Ubuntu", 14))
        self.label_3.pack(side=LEFT, expand=YES, fill=X)

        self.label_4 = CustomLabelWithBorder(parent, height=2)
        self.label_4.set_bg_color(self.bg_color_light)
        self.label_4.set_fg_color(fg_color)
        self.label_4.set_text("Питание", ("Ubuntu", 14))
        self.label_4.pack(side=LEFT, expand=YES, fill=X)

        self.label_5 = CustomLabelWithBorder(parent, height=2)
        self.label_5.set_bg_color(self.bg_color_light)
        self.label_5.set_fg_color(fg_color)
        self.label_5.set_text("Проживание", ("Ubuntu", 14))
        self.label_5.pack(side=LEFT, expand=YES, fill=X)

        self.label_6 = CustomLabelWithBorder(parent, height=2)
        self.label_6.set_bg_color(self.bg_color_light)
        self.label_6.set_fg_color(fg_color)
        self.label_6.set_text("Штрафы", ("Ubuntu", 14))
        self.label_6.pack(side=LEFT, expand=YES, fill=X)

        self.label_7 = CustomLabelWithBorder(parent, height=2)
        self.label_7.set_bg_color(self.bg_color_light)
        self.label_7.set_fg_color(fg_color)
        self.label_7.set_text("Авансы", ("Ubuntu", 14))
        self.label_7.pack(side=LEFT, expand=YES, fill=X)

        self.label_empty = CustomLabelWithBorder(parent,
                                                 height=2,
                                                 font=("Ubuntu", 14),
                                                 width=1)
        self.label_empty.set_bg_color(self.bg_color_light)
        self.label_empty.disable_border()
        self.label_empty.pack(side=LEFT, expand=NO, fill=X)
Пример #28
0
class InvoicesInterface:
    db_name = "invoices_database.db"

    db_services = 'database.db'

    db_invoices_search = "invoices_search.db"

    db_invoices_in_dollars = "invoices_dollars.db"

    listCombo = []

    def __init__(self, window):
        """Con sqlite"""
        self.windowInvoices = window
        self.windowInvoices.title("Invoices Window")

        # Creating a Frame Container
        frame = LabelFrame(self.windowInvoices, text="Create an invoice")
        frame.grid(row=0, column=0, columnspan=3, pady=20)

        # Name imput
        Label(frame, text="Name: ").grid(row=1, column=0)
        self.name = Entry(frame)
        self.name.focus()
        self.name.grid(row=1, column=1)

        # Address Input
        Label(frame, text="Address: ").grid(row=2, column=0)
        self.address = Entry(frame)
        self.address.grid(row=2, column=1)

        # ID input
        Label(frame, text="ID: ").grid(row=3, column=0)
        self.ID_ = Entry(frame)
        self.ID_.grid(row=3, column=1)

        # Email input
        Label(frame, text="Email: ").grid(row=4, column=0)
        self.email = Entry(frame)
        self.email.grid(row=4, column=1)

        # Date input
        Label(frame, text="Date: ").grid(row=5, column=0)
        self.date = DateEntry(frame,
                              width=12,
                              background='darkblue',
                              foreground='white',
                              borderwidth=2,
                              date_pattern='YYYY-MM-DD')
        self.date.grid(row=5, column=1)

        # Service input
        # ***** Change to a combobox ****

        Label(frame, text="Service").grid(row=6, column=0)
        # n = StringVar()
        # self.service = ttk.Combobox(frame)
        # self.service["values"] = self.get_services()
        # self.service.set(self.get_services()[0])
        # self.service.grid(row=6, column=1)

        Button(frame, text="Select services",
               command=self.services_window).grid(row=6, column=1)

        Label(frame, text="TAX").grid(row=7, column=0)
        self.discount = Entry(frame)
        self.discount.grid(row=7, column=1)

        # Button create invoice
        Button(frame, text="Create Invoice",
               command=self.add_invoice).grid(row=8,
                                              columnspan=2,
                                              sticky=W + E)

        Button(frame,
               text="See invoices in dollars",
               command=self.invoices_dollars_window).grid(row=9,
                                                          columnspan=2,
                                                          sticky=W + E)

        # Output messages
        self.message = Label(frame, text="", fg='red')
        self.message.grid(row=10, column=0, columnspan=2, sticky=W + E)

        self.tree = ttk.Treeview(self.windowInvoices,
                                 height=10,
                                 columns=("#0", "#1", "#2", "#3", "#4", "#5",
                                          "#6", "#7", "#8", "#9"))
        self.tree.grid(row=11, column=0, columnspan=3)
        self.tree.heading("#0", text="Name", anchor=CENTER)
        self.tree.heading("#1", text="ID", anchor=CENTER)
        self.tree.heading("#2", text="Email", anchor=CENTER)
        self.tree.heading("#3", text="Date", anchor=CENTER)
        self.tree.heading("#4", text="Due Date", anchor=CENTER)
        self.tree.heading("#5", text="Service", anchor=CENTER)
        self.tree.heading("#6", text="Price (₡)", anchor=CENTER)
        self.tree.heading("#7", text="Discount", anchor=CENTER)

        # Buttons
        Button(self.windowInvoices, text="DELETE",
               command=self.delete_invoice).grid(row=12,
                                                 column=0,
                                                 sticky=W + E)
        Button(self.windowInvoices,
               text="Search invoices by date",
               command=self.search_invoices_interface).grid(row=12,
                                                            column=1,
                                                            sticky=W + E)

        # Filling rows of table
        self.get_invoices()

    def search_invoices_interface(self):
        self.windowSearchByDate = Toplevel()
        self.windowSearchByDate.title("Search Invoices By Date")

        # Creating a frame container
        frame = LabelFrame(self.windowSearchByDate,
                           text="Search Invoices By Date")
        frame.grid(row=0, column=0, columnspan=3, pady=20)

        Label(frame, text="Select initial date").grid(row=1, column=0)
        self.initialDate = DateEntry(frame,
                                     width=12,
                                     background='darkblue',
                                     foreground='white',
                                     borderwidth=2,
                                     date_pattern='YYYY-MM-DD')
        self.initialDate.grid(row=1, column=1)

        Label(frame, text="Select final date").grid(row=2, column=0)
        self.finalDate = DateEntry(frame,
                                   width=12,
                                   background='darkblue',
                                   foreground='white',
                                   borderwidth=2,
                                   date_pattern='YYYY-MM-DD')
        self.finalDate.grid(row=2, column=1)

        # Button create invoice
        Button(frame, text="See Invoices",
               command=self.get_invoices_search).grid(row=3,
                                                      columnspan=2,
                                                      sticky=W + E)

        # Output messages
        self.message_search_invoices = Label(frame, text="", fg='red')
        self.message_search_invoices.grid(row=4,
                                          column=0,
                                          columnspan=2,
                                          sticky=W + E)

        self.searchtree = ttk.Treeview(self.windowSearchByDate,
                                       height=10,
                                       columns=("#0", "#1", "#2", "#3", "#4",
                                                "#5"))
        self.searchtree.grid(row=7, column=0, columnspan=3)
        self.searchtree.heading("#0", text="Invoice Number", anchor=CENTER)
        self.searchtree.heading("#1", text="Name", anchor=CENTER)
        self.searchtree.heading("#2", text="Price (₡)", anchor=CENTER)
        self.searchtree.heading("#3", text="Due Date", anchor=CENTER)
        self.searchtree.heading("#4", text="Total", anchor=CENTER)

        Button(self.windowSearchByDate,
               text="Show Invoice as a PDF file",
               command=self.get_data_to_show_pdf).grid(row=8,
                                                       column=0,
                                                       sticky=W + E)
        Button(self.windowSearchByDate,
               text="Send Invoice to Email",
               command=self.search_for_email).grid(row=8,
                                                   column=1,
                                                   sticky=W + E)

    def services_window(self):
        self.services_wind = Toplevel()
        self.services_wind.title("Select one or more services")
        self.services_wind.minsize(width=100, height=100)
        # Creating a Frame Container
        frame = LabelFrame(self.services_wind, text="Select services")
        frame.grid(row=0, column=0, columnspan=3, pady=20)

        self.serviceCombo = ttk.Combobox(frame)
        self.serviceCombo["values"] = self.get_services()
        self.serviceCombo.set(self.get_services()[0])
        self.serviceCombo.grid(row=6, column=1)

        # Output messages
        self.message_combobox_list = Label(frame, text="", fg='red')
        self.message_combobox_list.grid(row=7,
                                        column=0,
                                        columnspan=2,
                                        sticky=W + E)

        Button(frame, text="Add service",
               command=self.get_services_list).grid(row=8,
                                                    column=1,
                                                    sticky=W + E)

    def invoices_dollars_window(self):
        self.dollars_window = Toplevel()
        self.dollars_window.title("Invoices in dollars")

        # Creating a Frame Container
        frame = LabelFrame(self.dollars_window, text="Invoices in dollars")
        frame.grid(row=0, column=0, columnspan=3, pady=20)

        Button(frame,
               text="See all invoices",
               command=self.get_invoices_in_dollars).grid(row=1, column=1)

        self.message_convert_dollars = Label(frame, text="", fg='red')
        self.message_convert_dollars.grid(row=10,
                                          column=0,
                                          columnspan=2,
                                          sticky=W + E)

        self.tree_dollars = ttk.Treeview(self.dollars_window,
                                         height=10,
                                         columns=("#0", "#1", "#2", "#3",
                                                  "#4"))
        self.tree_dollars.grid(row=11, column=0, columnspan=3)
        self.tree_dollars.heading("#0", text="Name", anchor=CENTER)
        self.tree_dollars.heading("#1", text="Service", anchor=CENTER)
        self.tree_dollars.heading("#2", text="Price ($)", anchor=CENTER)
        self.tree_dollars.heading("#3", text="Total", anchor=CENTER)
        self.tree_dollars.heading("#4", text="Due Date", anchor=CENTER)

        Button(self.dollars_window,
               text="Convert ALL invoices to dollars",
               command=self.convert_all_invoices_to_dollars).grid(row=12,
                                                                  column=0,
                                                                  sticky=W + E)
        Button(self.dollars_window,
               text="Convert selected invoice to dollars",
               command=self.convert_single_invoice_to_dollars).grid(row=12,
                                                                    column=1,
                                                                    sticky=W +
                                                                    E)

    def get_services_list(self):
        comboboxContent = self.serviceCombo.get()
        servicesString = ""
        priceString = ""
        service = comboboxContent.replace(" - ₡", "")
        for i in service:
            if i.isalpha():
                servicesString += i
            else:
                priceString += i
        self.listCombo.append((servicesString, priceString))

        self.message_combobox_list['text'] = servicesString + " has been added"
        self.message_combobox_list['fg'] = "blue"

        print(self.listCombo)
        return self.listCombo

    def dates_validation(self):
        return self.initialDate.get() != "" and self.finalDate.get() != ""

    def run_query_search_invoices(self, query, parameters=()):
        with sqlite3.connect(self.db_invoices_search) as conn:
            cursor = conn.cursor()
            result = cursor.execute(query, parameters)
            conn.commit()
        return result

    def run_query_invoices_dollars(self, query, parameters=()):
        with sqlite3.connect(self.db_invoices_in_dollars) as conn:
            cursor = conn.cursor()
            result = cursor.execute(query, parameters)
            conn.commit()
        return result

    def run_query(self, query, parameters=()):
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            result = cursor.execute(query, parameters)
            conn.commit()
        return result

    def run_query_to_delete_invoices(self, query, parameters=()):
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            result = cursor.execute(query, parameters)
            conn.commit()
        return result

    def run_query_services(self, query, parameters=()):
        with sqlite3.connect(self.db_services) as conn:
            cursor = conn.cursor()
            result = cursor.execute(query, parameters)
            conn.commit()
        return result

    def get_services(self):
        list = []
        # getting data
        query = 'SELECT * FROM product ORDER BY name DESC'
        db_rows = self.run_query_services(query)
        # filling data
        for row in db_rows:
            # print(row)
            itemNum, service, price = row
            list += [service + " - " + "₡" + str(price)]

        return list

    def get_invoices(self):
        # cleaning table everytime it runs
        records = self.tree.get_children()
        for element in records:
            self.tree.delete(element)

        # quering data
        query = 'SELECT * FROM invoices ORDER BY name DESC'
        db_rows = self.run_query(query)
        # filling data
        for row in db_rows:
            # print(row)
            # print(row[2:5])
            self.tree.insert("", 0, text=row[1], values=row[2:])

    def get_invoices_in_dollars(self):
        # cleaning table each time it runs
        records = self.tree_dollars.get_children()
        for element in records:
            self.tree_dollars.delete(element)

        # quering data
        query = "SELECT * FROM invoices_dollars ORDER BY name DESC"
        db_rows = self.run_query_invoices_dollars(query)
        # filling rows of treeview
        for row in db_rows:
            self.tree_dollars.insert("", 0, text=row[1], values=row[2:6])

    def get_invoices_search(self):
        initialDate = self.initialDate.get_date()
        finalDate = self.finalDate.get_date()
        if self.dates_validation():
            # cleaning table
            records = self.searchtree.get_children()
            for element in records:
                self.searchtree.delete(element)

            # Getting data from database
            query = 'SELECT * FROM invoices_search ORDER BY name DESC'
            db_rows = self.run_query_search_invoices(query)
            # filling data
            for row in db_rows:
                # print(row)
                # format_str = '%d/%m/%Y'  # The format
                format_str = "%Y-%m-%d"
                datetime_obj = datetime.strptime(row[6], format_str)
                print(datetime_obj)
                if datetime.date(
                        datetime_obj) >= initialDate and datetime.date(
                            datetime_obj) <= finalDate:
                    self.message_search_invoices['text'] = ""
                    self.searchtree.insert("", 1, text=row[1], values=row[2:6])

        else:
            self.message_search_invoices[
                'text'] = "Can't show information, please check the date entries"

    def validation(self):
        return len(self.name.get()) != 0 and len(self.date.get()) != 0 and len(
            self.address.get()) != 0 and len(self.ID_.get()) != 0 and len(
                self.email.get()) != 0

        # len(self.get_services_list) != 0

    def add_invoice(self):
        if self.validation():
            query = "INSERT INTO invoices VALUES(NULL,?,?,?,?,?,?,?,?,?)"
            query_dollars_database = "INSERT INTO invoices_dollars VALUES(NULL,?,?,?,?,?,?,?,?,?,?)"
            # service_text = self.service.get()
            # service_textCopy = service_text.replace(" - ₡","")
            # print(service_text)

            stringOfServices = ""
            stringOfPrices = ""
            stringPricesInDollars = ""
            totalDollars = 0

            for i in self.listCombo:
                print(i)
                service2, price2 = i
                stringOfServices += service2 + ","
                stringOfPrices += price2 + ","

            stringOfServices = stringOfServices[:-1]
            stringOfPrices = stringOfPrices[:-1]
            print("String of Services " + stringOfServices)
            print("String of Prices " + stringOfPrices)

            stringOfPricesCopy = stringOfPrices
            listToDollars = stringOfPricesCopy.split(",")
            print(listToDollars)

            for i in listToDollars:
                newExchangeRate = GetBankInformation()
                newCurrency = newExchangeRate.ColonToDollar(i)
                totalDollars += float(newCurrency)
                stringPricesInDollars += str(newCurrency) + ","

            stringPricesInDollars = stringPricesInDollars[:-1]

            print("Dollars: " + stringPricesInDollars)
            print("Total In Dollars " + str(totalDollars))

            # parameters = (self.name.get(),self.date.get(),self.date.get_date()+timedelta(days=3),self.email.get(),self.address.get(),service,float(price),self.discount.get(),self.ID_.get())
            parameters = (self.name.get(), self.ID_.get(), self.email.get(),
                          self.date.get(), self.date.get_date() +
                          timedelta(days=3), stringOfServices, stringOfPrices,
                          self.discount.get(), self.address.get())
            parameters_dollars = (self.name.get(), stringOfServices,
                                  stringPricesInDollars, str(totalDollars),
                                  self.date.get_date() + timedelta(days=3),
                                  self.email.get(), self.ID_.get(),
                                  self.date.get(), self.discount.get(),
                                  self.address.get())
            self.run_query(query, parameters)
            self.run_query_invoices_dollars(query_dollars_database,
                                            parameters_dollars)
            nameForSearch = self.name.get()
            nameForInvoice = self.name.get()
            self.message['text'] = "{}'s invoice added succesfully".format(
                self.name.get())
            self.message['fg'] = "green"
            self.name.delete(0, END)
            self.address.delete(0, END)
            self.ID_.delete(0, END)
            self.email.delete(0, END)
            # self.service.delete(0,END)
            self.discount.delete(0, END)
        else:
            self.message['text'] = "All spaces must be filled"
            self.message['fg'] = "red"
        self.get_invoices()
        self.get_data_for_search_database(nameForSearch)
        self.get_single_data(nameForInvoice)

    def delete_invoice(self):
        self.message['text'] = ""
        try:
            # self.tree.item(self.tree.selection())['text'][0]
            self.tree.item(self.tree.selection())['text'][0]
            # print(self.tree.item(self.tree.selection())['text'][0])
            # print(self.tree.item(self.tree.selection())['text'])
            # print(self.tree.item(self.tree.selection())['values'][4])
        except IndexError as e:
            self.message['text'] = "Please select a record"
            return
        self.message['text'] = ""
        name = self.tree.item(self.tree.selection())['text']
        query = 'DELETE FROM invoices WHERE name = ?'
        query2 = 'DELETE FROM invoices_search WHERE name = ?'
        query3 = 'DELETE FROM invoices_dollars WHERE name = ?'
        self.get_info_to_delete_pdf(name)
        self.run_query_search_invoices(query2, (name, ))
        self.run_query_invoices_dollars(query3, (name, ))
        self.run_query(query, (name, ))
        self.message['text'] = "Invoice deleted successfully"
        self.message['fg'] = "blue"
        self.get_invoices()

    def convert_single_invoice_to_dollars(self):
        try:
            self.tree_dollars.item(self.tree_dollars.selection())['text'][0]
        except IndexError as e:
            self.message_convert_dollars['text'] = "Please Select a Record"
            return
        self.message_convert_dollars['text'] = ""
        name = self.tree_dollars.item(self.tree_dollars.selection())['text']
        file_to_search = name + ".pdf"
        self.delete_PDF(file_to_search)
        self.get_single_invoice_in_dollars(name)
        self.message_convert_dollars[
            'text'] = name + "'s invoice has changed the currency to dollars ($)"

    def get_single_invoice_in_dollars(self, name):
        # getting data
        query = 'SELECT * FROM invoices_dollars ORDER BY name DESC'
        db_rows = self.run_query_invoices_dollars(query)
        # filling data
        for row in db_rows:
            print(row)
            if row[1] == name:
                invoiceNumber, invoiceToName, invoiceService, servicePrice, total, invoiceExpiringDate, invoiceEmail, invoiceID, invoiceDate, serviceDiscount, invoiceAddress = row
                self.generateInvoice(invoiceNumber, invoiceToName, invoiceID,
                                     invoiceEmail, invoiceDate,
                                     invoiceExpiringDate, invoiceService,
                                     servicePrice, serviceDiscount,
                                     invoiceAddress)

    def get_info_to_delete_pdf(self, invoiceNameToDelete):
        # getting data
        query = 'SELECT * FROM invoices ORDER BY name DESC'
        db_rows = self.run_query(query)
        # filling data
        for row in db_rows:
            # print(row)
            if row[1] == invoiceNameToDelete:
                print("Printing...")
                print(row[1])
                print(row)
                PDF_file_name = row[1] + " - " + str(row[0]) + ".pdf"
                print(PDF_file_name)
                self.delete_PDF(PDF_file_name)

    def delete_PDF(self, pdf_file):
        for subdir, dirs, files in os.walk(
                r'C:\Users\Michael\Desktop\PROYECTO 3 - Company System With Face Recognition To Log - 1S - 2020\PROYECTO-3-Company-System-With-Face-Recognition-To-Log---1S---2020\invoices'
        ):
            for filename in files:
                filepath = subdir + os.sep + filename

                if filename == pdf_file:
                    if filename:
                        os.remove(filepath)
                        # os.startfile(r"C:\Users\Michael\Desktop\PROYECTO 3 - Company System With Face Recognition To Log - 1S - 2020\PROYECTO-3-Company-System-With-Face-Recognition-To-Log---1S---2020\invoices\CRISTOPHER - 63.pdf")
                        print("PDF DELETED")
                    else:
                        messagebox.showerror("Error", "Can't delete PDF file")

    def delete_all_invoices(self):
        for subdir, dirs, files in os.walk(
                r'C:\Users\Michael\Desktop\PROYECTO 3 - Company System With Face Recognition To Log - 1S - 2020\PROYECTO-3-Company-System-With-Face-Recognition-To-Log---1S---2020\invoices'
        ):
            for filename in files:
                filepath = subdir + os.sep + filename
                if filename.endswith(".pdf"):
                    if filename:
                        os.remove(filepath)
                        print("PDF deleted ___deleting all invoices___")
                    else:
                        messagebox.showerror("Error", "Can't delete PDF file")

    def convert_all_invoices_to_dollars(self):
        self.delete_all_invoices()
        self.generate_all_invoices_in_dollars()
        self.message_convert_dollars[
            'text'] = "ALL invoices have changed the currency to dollars ($)"

    def generate_all_invoices_in_dollars(self):
        listData = []
        # getting data
        query = 'SELECT * FROM invoices_dollars ORDER BY name DESC'
        db_rows = self.run_query_invoices_dollars(query)
        # filling data
        for row in db_rows:
            print(row)
            listData.append(row)
            print(listData)
            # row_data #= row
            invoiceNumber, invoiceToName, invoiceService, servicePrice, total, invoiceExpiringDate, invoiceEmail, invoiceID, invoiceDate, serviceDiscount, invoiceAddress = row
            # self.generateInvoice(invoiceNumber,invoiceToName, invoiceID,invoiceEmail,invoiceDate,invoiceExpiringDate, invoiceService, servicePrice, serviceDiscount, invoiceAddress)

            # print("Generating pdf")
            # row_data = ()

        for data in listData:
            invoiceNumber, invoiceToName, invoiceService, servicePrice, total, invoiceExpiringDate, invoiceEmail, invoiceID, invoiceDate, serviceDiscount, invoiceAddress = data
            newDoc = Invoice(invoiceNumber, invoiceToName, invoiceID,
                             invoiceEmail, invoiceDate, invoiceExpiringDate,
                             invoiceService, servicePrice, serviceDiscount,
                             invoiceAddress)
            newDoc.generateInvoice()

        self.move_pdfs()

    def move_pdfs(self):
        for subdir, dirs, files in os.walk(
                r'C:\Users\Michael\Desktop\PROYECTO 3 - Company System With Face Recognition To Log - 1S - 2020\PROYECTO-3-Company-System-With-Face-Recognition-To-Log---1S---2020'
        ):
            for filename in files:
                filepath = subdir + os.sep + filename
                if filepath.endswith(".pdf"):
                    print(filename)
                    destination = "invoices"
                    shutil.move(filepath, destination)
                    print("Invoices moved")

    def get_single_data(self, invoiceName):
        # getting data
        query = 'SELECT * FROM invoices ORDER BY name DESC'
        db_rows = self.run_query(query)
        # filling data
        for row in db_rows:
            print(row[1])
            if row[1] == invoiceName:
                print(row)
                invoiceNumber, invoiceToName, invoiceID, invoiceEmail, invoiceDate, invoiceExpiringDate, invoiceService, servicePrice, serviceDiscount, invoiceAddress = row
                self.generateInvoice(invoiceNumber, invoiceToName, invoiceID,
                                     invoiceEmail, invoiceDate,
                                     invoiceExpiringDate, invoiceService,
                                     servicePrice, serviceDiscount,
                                     invoiceAddress)

    def generateInvoice(self, invoiceNumber, invoiceToName, invoiceID,
                        invoiceEmail, invoiceDate, invoiceExpiringDate,
                        invoiceService, servicePrice, serviceDiscount,
                        invoiceAddress):
        newInvoice = Invoice(invoiceNumber, invoiceToName, invoiceID,
                             invoiceEmail, invoiceDate, invoiceExpiringDate,
                             invoiceService, servicePrice, serviceDiscount,
                             invoiceAddress)
        newInvoice.generateInvoice()
        newInvoice.moveInvoices()

    def get_data_for_search_database(self, invoiceName):
        # getting data
        query = 'SELECT * FROM invoices ORDER BY name DESC'
        db_rows = self.run_query(query)
        # filling data
        for row in db_rows:
            print(row[1])
            if row[1] == invoiceName:
                print(row)
                invoiceNumber, invoiceToName, invoiceID, invoiceEmail, invoiceDate, invoiceExpiringDate, invoiceService, servicePrice, serviceDiscount, invoiceAddress = row
                query2 = "INSERT INTO invoices_search VALUES(NULL,?,?,?,?,?,?,?)"
                parametersForSearchDatabase = (invoiceNumber, invoiceToName,
                                               servicePrice,
                                               invoiceExpiringDate,
                                               servicePrice, invoiceDate,
                                               invoiceEmail)
                self.run_query_search_invoices(query2,
                                               parametersForSearchDatabase)
                print("done")

    def get_data_to_show_pdf(self):
        self.message_search_invoices['text'] = ""
        try:
            self.searchtree.item(self.searchtree.selection())['text'][1]
        except IndexError as e:
            self.message_search_invoices['text'] = "Please select a record"
            return
        self.message_search_invoices['text'] = ""
        name = self.searchtree.item(self.searchtree.selection())['values'][0]
        numberOfInvoice = self.searchtree.item(
            self.searchtree.selection())['text']
        print(name, numberOfInvoice)
        pdf_file = name + ".pdf"
        self.open_pdf_file(pdf_file)

    def open_pdf_file(self, pdf_file):
        for subdir, dirs, files in os.walk(
                r'C:\Users\Michael\Desktop\PROYECTO 3 - Company System With Face Recognition To Log - 1S - 2020\PROYECTO-3-Company-System-With-Face-Recognition-To-Log---1S---2020\invoices'
        ):
            for filename in files:
                filepath = subdir + os.sep + filename
                if filename == pdf_file:
                    if filename:
                        os.startfile(filepath)
                        print("PDF OPENING...")
                    else:
                        messagebox.showerror("Error", "Can't open PDF file")

    def search_for_email(self):
        self.message_search_invoices['text'] = ""
        try:
            self.searchtree.item(self.searchtree.selection())['text'][1]
        except IndexError as e:
            self.message_search_invoices['text'] = "Please select a record"
            return
        self.message_search_invoices['text'] = ""
        name = self.searchtree.item(self.searchtree.selection())['values'][0]
        numberOfInvoice = self.searchtree.item(
            self.searchtree.selection())['text']
        print(self.searchtree.item(self.searchtree.selection()))
        print(name, numberOfInvoice)
        # pdf_file = name + " - " + str(numberOfInvoice) + ".pdf"
        self.get_pdf_to_email(name)

    def get_pdf_to_email(self, name):
        # Getting data from database
        query = 'SELECT * FROM invoices_search ORDER BY name DESC'
        db_rows = self.run_query_search_invoices(query)
        # filling data
        for row in db_rows:
            if row[2] == name:
                print(row)
                email = row[7]
                date = row[6]
                pdf_file = str(row[2]) + ".pdf"
                print(email)
                print(date)
                print(pdf_file)
                newEmail = SendEmail(email, "invoices/" + pdf_file, date)
                newEmail.send_email()
                messagebox.showinfo("Email Sent",
                                    "Your email has been sent to: " + email)

    def get_prices(self):
        # getting data
        query = 'SELECT * FROM invoices_search ORDER BY name DESC'
        db_rows = self.run_query_search_invoices(query)
        # filling data
        for row in db_rows:
            print(row[5])
            newPrice = GetBankInformation()
            newPrice.ColonToDollar(float(row[5]))
            print(row)
Пример #29
0
class PaginaFactura(tk.Frame):
    def __init__(self, padre, controlador, cliente=None):
        """INICIAR LOS GRÁFICOS DE LA PÁGINA DE FACTURAS"""

        tk.Frame.__init__(self, padre)
        self.cliente = cliente
        self.controlador = controlador

        ######################################
        #CABECERA
        ######################################
        boton_inicio = tk.Button(
            self,
            text="INICIO",
            command=lambda: controlador.mostrar_marco("PaginaInicial"))
        boton_inicio.grid(row=00, column=0)

        boton_ver_clientes = tk.Button(self,
                                       text="Ver facturas",
                                       command=lambda: self.ver_facturas())
        boton_ver_clientes.grid(row=1, column=0)

        boton_actualizar = tk.Button(self,
                                     text="actualizar facturas",
                                     command=lambda: self.editar_facturas())
        boton_actualizar.grid(row=1, column=1)

        boton_añadir = tk.Button(self,
                                 text="Añadir factura",
                                 command=lambda: self.añadir_factura())
        boton_añadir.grid(row=2, column=0)

        boton_eliminar = tk.Button(self,
                                   text="Eliminar factura",
                                   command=lambda: self.eliminar_factura())
        boton_eliminar.grid(row=2, column=1)

        boton_borrar = tk.Button(self,
                                 text="Borrar cuadros",
                                 command=lambda: self.borrar())
        boton_borrar.grid(row=2, column=2)

        #caja de facturas
        self.caja_facturas = tk.Listbox(self, height=10, width=70)
        self.caja_facturas.grid(row=0, column=4, rowspan=9, columnspan=5)
        self.scroll_facturas = tk.Scrollbar(self)
        self.scroll_facturas.grid(row=0, column=10, rowspan=9)
        self.caja_facturas.configure(yscrollcommand=self.scroll_facturas.set)
        self.scroll_facturas.configure(command=self.caja_facturas.yview)
        self.caja_facturas.bind('<<ListboxSelect>>',
                                self.caja_factura_seleccionada)

        boton = ttk.Button(
            self,
            text="Elegir Cliente para la factura",
            command=lambda: controlador.mostrar_marco("PaginaCliente"))
        boton.grid(row=7, column=1)

        #ruta, factura, fecha, nombre, direccion, cp, dni, tratamientos, comentario, iva, descuento, total
        boton = ttk.Button(self, text="Imprimir PDF", command=self.imprimir)
        boton.grid(row=7, column=2)

        #título

        self.label = tk.Label(self,
                              text="Factura",
                              font=self.controlador.fuente_titulo)
        self.label.grid(row=10, column=0)

        self.texto_codigo = StringVar()
        self.etiqueta_codigo = tk.Label(self, text="Codigo de la factura")
        self.etiqueta_codigo.grid(row=11, column=0)
        self.cuadro_codigo = ttk.Entry(self,
                                       textvariable=self.texto_codigo,
                                       justify=tk.RIGHT)
        self.cuadro_codigo.grid(row=11, column=1)
        self.auto_id_factura = controlador.marcos[
            'PaginaInicial'].cuadro_resultado.get()
        self.cuadro_codigo.insert(END, self.auto_id_factura)

        self.texto_id_factura = StringVar()
        self.texto_id_factura.set("Factura no seleccionada")
        self.etiqueta_id_factura = tk.Label(self, text="ID Factura")
        self.etiqueta_id_factura.grid(row=11, column=2)
        self.cuadro_id_factura = ttk.Label(self,
                                           textvariable=self.texto_id_factura,
                                           justify=tk.RIGHT)
        self.cuadro_id_factura.grid(row=11, column=3)

        self.texto_cliente = StringVar()
        self.texto_cliente.set("Sin cliente seleccionado")
        self.etiqueta_cliente = tk.Label(self, text="Nº Cliente asociado:")
        self.etiqueta_cliente.grid(row=11, column=4)
        self.etiqueta_cliente_asignado = ttk.Label(
            self, textvariable=self.texto_cliente, justify=tk.RIGHT)
        self.etiqueta_cliente_asignado.grid(row=11, column=5)

        self.texto_nombre = StringVar()
        self.etiqueta_nombre = tk.Label(self, text="Nombre: ")
        self.etiqueta_nombre.grid(row=12, column=0)
        self.cuadro_nombre = ttk.Entry(self,
                                       textvariable=self.texto_nombre,
                                       justify=tk.RIGHT)
        self.cuadro_nombre.grid(row=12, column=1)

        self.texto_dni = StringVar()
        self.etiqueta_dni = tk.Label(self, text="DNI")
        self.etiqueta_dni.grid(row=12, column=2)
        self.cuadro_dni = ttk.Entry(self,
                                    textvariable=self.texto_dni,
                                    justify=tk.RIGHT)
        self.cuadro_dni.grid(row=12, column=3)

        self.texto_direccion = StringVar()
        self.etiqueta_direccion = tk.Label(self, text="Direccion")
        self.etiqueta_direccion.grid(row=13, column=0)
        self.cuadro_direccion = ttk.Entry(self,
                                          textvariable=self.texto_direccion,
                                          justify=tk.RIGHT)
        self.cuadro_direccion.grid(row=13, column=1)

        self.texto_cp = StringVar()
        self.etiqueta_cp = tk.Label(self, text="Código postal")
        self.etiqueta_cp.grid(row=13, column=2)
        self.cuadro_cp = ttk.Entry(self,
                                   textvariable=self.texto_cp,
                                   justify=tk.RIGHT)
        self.cuadro_cp.grid(row=13, column=3)

        self.etiqueta_fecha = tk.Label(self, text="Fecha factura")
        self.etiqueta_fecha.grid(row=14, column=0)
        self.cal = DateEntry(self,
                             width=12,
                             background='darkblue',
                             foreground='white',
                             borderwidth=2,
                             locale='es_ES')
        self.cal.grid(row=14, column=1)

        self.etiqueta_comentarios = tk.Label(self, text="Comentarios")
        self.etiqueta_comentarios.grid(row=15, column=0)
        self.cuadro_comentarios = tk.Text(self,
                                          width=70,
                                          height=10,
                                          wrap='word')
        self.cuadro_comentarios.grid(row=15, column=1, columnspan=3, rowspan=5)

        ###############################
        #SERVICIOS
        ##############################
        self.label = tk.Label(self,
                              text="Servicios",
                              font=self.controlador.fuente_titulo)
        self.label.grid(row=129, column=0)

        #caja de servicios
        self.caja_servicios = tk.Listbox(self, height=10, width=35)
        self.caja_servicios.grid(row=130, column=1, rowspan=9)
        self.scroll_servicios = tk.Scrollbar(self)
        self.scroll_servicios.grid(row=130, column=2, rowspan=9)
        self.caja_servicios.configure(yscrollcommand=self.scroll_servicios.set)
        self.scroll_servicios.configure(command=self.caja_servicios.yview)
        self.caja_servicios.bind('<<ListboxSelect>>',
                                 self.caja_servicio_seleccionado)

        boton_añadir_servicio = tk.Button(
            self,
            text="Añadir servicio",
            command=lambda: self.añadir_servicio())
        boton_añadir_servicio.grid(row=130, column=4)

        boton_eliminar_servicio = tk.Button(
            self,
            text="Eliminar servicio",
            command=lambda: self.eliminar_servicio())
        boton_eliminar_servicio.grid(row=131, column=4)

        boton_editar_servicio = tk.Button(
            self,
            text="Editar servicio",
            command=lambda: self.editar_servicio())
        boton_editar_servicio.grid(row=132, column=4)

        self.etiqueta_fecha_servicio = tk.Label(self, text="Fecha servicio")
        self.etiqueta_fecha_servicio.grid(row=133, column=3)
        self.cal_servicio = DateEntry(self,
                                      width=12,
                                      background='darkblue',
                                      foreground='white',
                                      borderwidth=2,
                                      locale='es_ES')
        self.cal_servicio.grid(row=133, column=4)

        self.texto_tratamiento = StringVar()
        self.etiqueta_tratamiento = tk.Label(self, text="Tratamiento: ")
        self.etiqueta_tratamiento.grid(row=134, column=3)
        self.cuadro_tratamiento = ttk.Entry(
            self, textvariable=self.texto_tratamiento, justify=tk.RIGHT)
        self.cuadro_tratamiento.grid(row=134, column=4)
        self.cuadro_tratamiento.delete(0, END)
        self.cuadro_tratamiento.insert(END, "Sesión de Fisioterapia")

        self.texto_precio_tratamiento = StringVar()
        self.etiqueta_precio_tratamiento = tk.Label(self, text="€: ")
        self.etiqueta_precio_tratamiento.grid(row=135, column=3)
        self.cuadro_precio_tratamiento = ttk.Entry(
            self, textvariable=self.texto_precio_tratamiento, justify=tk.RIGHT)
        self.cuadro_precio_tratamiento.grid(row=135, column=4)
        self.cuadro_precio_tratamiento.delete(0, END)
        self.cuadro_precio_tratamiento.insert(END, 28)

        ###############################
        #PIE DE FACTURA
        ##############################
        self.label = tk.Label(self,
                              text="Calculos",
                              font=self.controlador.fuente_titulo)
        self.label.grid(row=140, column=0)

        #calculos

        self.etiqueta_iva = tk.Label(self, text="IVA")
        self.etiqueta_iva.grid(row=141, column=0)
        self.combo_iva = ttk.Combobox(self)
        self.combo_iva["values"] = [0, 4, 16, 21]
        self.combo_iva.set(0)
        self.combo_iva.bind("<<ComboboxSelected>>", self.combo_seleccionado)
        self.combo_iva.grid(row=141, column=1)

        self.texto_descuento = StringVar()
        self.etiqueta_descuento = tk.Label(self, text="Descuento")
        self.etiqueta_descuento.grid(row=150, column=0)
        self.cuadro_descuento = ttk.Entry(self,
                                          textvariable=self.texto_descuento,
                                          justify=tk.RIGHT)
        self.cuadro_descuento.grid(row=150, column=1)
        self.cuadro_descuento.bind('<Return>', self.combo_seleccionado)
        self.cuadro_descuento.insert(END, "0")

        self.texto_total = StringVar()
        self.etiqueta_total = tk.Label(self, text="TOTAL")
        self.etiqueta_total.grid(row=160, column=0)
        self.cuadro_total = ttk.Entry(self,
                                      textvariable=self.texto_total,
                                      justify=tk.RIGHT)

        self.cuadro_total.grid(row=160, column=1)

        # iniciar el cuadro con las facturas

        self.ver_facturas()

###############################
#FUNCIONES
##############################

    def imprimir(self):
        print("impresión pulsado")

        print(self.controlador.ruta, self.cuadro_codigo.get(), self.cal.get(),
              self.cuadro_nombre.get(), self.cuadro_direccion.get(),
              self.cuadro_cp.get(), self.cuadro_dni.get(),
              self.ver_servicios(), self.cuadro_comentarios.get("1.0", END),
              self.combo_iva.get(), self.cuadro_descuento.get(),
              self.cuadro_total.get())
        imprimir(self.controlador.ruta, self.cuadro_codigo.get(),
                 self.cal.get(), self.cuadro_nombre.get(),
                 self.cuadro_direccion.get(), self.cuadro_cp.get(),
                 self.cuadro_dni.get(), self.ver_servicios(),
                 self.cuadro_comentarios.get("1.0", END), self.combo_iva.get(),
                 self.cuadro_descuento.get(), self.cuadro_total.get())

    def combo_seleccionado(self, event):
        iva_seleccionado = self.combo_iva.get()
        actualizarRegistro("FACTURA", "IVA_ID", self.combo_iva.get(), "ID",
                           self.texto_id_factura.get())
        actualizarRegistro("FACTURA", "DESCUENTO", self.cuadro_descuento.get(),
                           "ID", self.texto_id_factura.get())
        self.ver_facturas()
        self.actualizar_total()

    def editar_facturas(self):
        actualizarRegistro("FACTURA", "CODIGO_FACTURA",
                           self.cuadro_codigo.get(), "ID",
                           self.texto_id_factura.get())
        actualizarRegistro("FACTURA", "FECHA_FACTURA",
                           cal2fecha(self.cal.get()), "ID",
                           self.texto_id_factura.get())
        actualizarRegistro("FACTURA", "IVA_ID", self.combo_iva.get(), "ID",
                           self.texto_id_factura.get())
        actualizarRegistro("FACTURA", "DESCUENTO", self.cuadro_descuento.get(),
                           "ID", self.texto_id_factura.get())
        actualizarRegistro("FACTURA", "CLIENTE_ID", self.texto_cliente.get(),
                           "ID", self.texto_id_factura.get())
        actualizarRegistro("FACTURA", "COMENTARIO",
                           self.cuadro_comentarios.get("1.0", END), "ID",
                           self.texto_id_factura.get())
        self.ver_facturas()
        self.actualizar_total()

    def añadir_factura(self):
        datos = [(self.cuadro_codigo.get(), cal2fecha(self.cal.get()),
                  self.combo_iva.get(), self.cuadro_descuento.get(),
                  self.ID_cliente_asociado,
                  self.cuadro_comentarios.get("1.0", END))]
        print(self.cuadro_comentarios.get("1.0", END))
        crearFactura(datos)
        self.borrar()
        self.texto_id_factura.set(leerTodo("FACTURA")[-1][0])
        self.ver_facturas()
        self.controlador.marcos["PaginaInicial"].siguienteNumero()

    def editar_servicio(self):
        #FECHA_SERVICIO ,        TRATAMIENTO, PRECIO_FINAL,        FACTURA_ID
        actualizarRegistro("SERVICIO", "FECHA_SERVICIO",
                           cal2fecha(self.cal_servicio.get()), "ID",
                           tupla_servicios_seleccionados[0])
        actualizarRegistro("SERVICIO", "TRATAMIENTO",
                           self.cuadro_tratamiento.get(), "ID",
                           tupla_servicios_seleccionados[0])
        actualizarRegistro("SERVICIO", "PRECIO_FINAL",
                           self.cuadro_precio_tratamiento.get(), "ID",
                           tupla_servicios_seleccionados[0])
        self.ver_servicios()
        self.actualizar_total()

    def añadir_servicio(self):
        if self.texto_id_factura.get() != "Factura no seleccionada":
            datos = [
                (cal2fecha(self.cal_servicio.get()),
                 self.cuadro_tratamiento.get(),
                 self.cuadro_precio_tratamiento.get(),
                 self.texto_id_factura.get())
            ]  #fecha, tratamiento, precio y factura a la que pertenece
            crearServicio(datos)
            self.ver_servicios()
            self.actualizar_total()
        else:
            print("No hay factura seleccionada para asociarle el servicio")

    def eliminar_factura(self):
        borrarRegistro("FACTURA", "ID", self.texto_id_factura.get())
        self.ver_facturas()

    def eliminar_servicio(self):
        borrarRegistro("SERVICIO", "ID", tupla_servicios_seleccionados[0])
        self.ver_servicios()
        self.actualizar_total()

    def set_cliente(self, cliente):
        self.cliente = cliente
        id_seleccionado = cliente[0]
        self.cuadro_dni.delete(0, END)
        self.cuadro_dni.insert(END, cliente[1])

        self.ID_cliente_asociado = cliente[0]

        self.texto_cliente.set(cliente[0])

        self.cuadro_nombre.delete(0, END)
        self.cuadro_nombre.insert(END, cliente[2])
        self.cuadro_nombre.insert(END, " ")
        self.cuadro_nombre.insert(END, cliente[3])

        self.cuadro_direccion.delete(0, END)
        self.cuadro_direccion.insert(END, cliente[4])
        self.cuadro_direccion.insert(END, ". ")
        self.cuadro_direccion.insert(END, cliente[5])
        self.cuadro_direccion.insert(END, ". ")
        self.cuadro_direccion.insert(END, cliente[6])

        self.cuadro_cp.delete(0, END)
        self.cuadro_cp.insert(END, cliente[7])

        self.ver_facturas()

    def caja_factura_seleccionada(self, evento):
        global tupla_facturas_seleccionadas
        global id_factura
        if (self.caja_facturas.curselection()):
            indice = self.caja_facturas.curselection()[0]

            #print("Al pulsar se ve esto: "+ str(self.caja_facturas.curselection()))

            tupla_facturas_seleccionadas = self.caja_facturas.get(indice)

            cliente_factura = leerRegistro("CLIENTE", "ID",
                                           tupla_facturas_seleccionadas[5])
            id_factura = str(tupla_facturas_seleccionadas[0])

            self.texto_id_factura.set(id_factura)

            self.set_cliente(cliente_factura[0])

            lista_fecha = (str(tupla_facturas_seleccionadas[2]).split("-"))
            self.cal.set_date(
                datetime(int(lista_fecha[0]), int(lista_fecha[1]),
                         int(lista_fecha[2])))

            self.cuadro_codigo.delete(0, END)
            self.cuadro_codigo.insert(END, tupla_facturas_seleccionadas[1])

            self.cuadro_comentarios.delete("1.0", END)
            self.cuadro_comentarios.insert(END,
                                           tupla_facturas_seleccionadas[6])

            self.combo_iva.set(tupla_facturas_seleccionadas[3])

            self.cuadro_descuento.delete(0, END)
            self.cuadro_descuento.insert(END, tupla_facturas_seleccionadas[4])

            self.caja_facturas.itemconfigure(
                indice, bg="#00aa00",
                fg="#fff")  #darle colorcito verde a lo seleccionado
            self.caja_facturas.see(
                indice
            )  # esto es para que se centre en el que que has seleccionado

            self.ver_servicios()
            self.actualizar_total()

    def caja_servicio_seleccionado(self, evento):
        global tupla_servicios_seleccionados
        indice_servicio = self.caja_servicios.curselection()[0]
        tupla_servicios_seleccionados = self.caja_servicios.get(
            indice_servicio)

        lista_fecha = (str(tupla_servicios_seleccionados[1]).split("-"))
        self.cal_servicio.set_date(
            datetime(int(lista_fecha[0]), int(lista_fecha[1]),
                     int(lista_fecha[2])))

        self.cuadro_tratamiento.delete(0, END)
        self.cuadro_tratamiento.insert(END, tupla_servicios_seleccionados[2])

        self.cuadro_precio_tratamiento.delete(0, END)
        self.cuadro_precio_tratamiento.insert(END,
                                              tupla_servicios_seleccionados[3])

        self.caja_servicios.itemconfigure(
            indice_servicio, bg="#00aa00",
            fg="#fff")  #darle colorcito verde a lo seleccionado
        self.caja_servicios.see(
            indice_servicio
        )  # esto es para que se centre en el que que has seleccionado

        self.ver_servicios()
        self.actualizar_total()

    def borrar(self):
        self.cuadro_dni.delete(0, END)
        self.cuadro_nombre.delete(0, END)
        self.cuadro_direccion.delete(0, END)
        self.cuadro_cp.delete(0, END)
        self.texto_id_factura.set("Factura no seleccionada")
        self.cuadro_comentarios.delete("1.0", END)
        self.cuadro_codigo.delete(0, END)
        self.caja_servicios.delete(0, END)
        self.combo_iva.set(0)
        self.cuadro_descuento.delete(0, END)
        self.cuadro_descuento.insert(END, "0")
        self.cuadro_total.delete(0, END)
        self.controlador.marcos['PaginaInicial'].actualizar()

    def ver_facturas(self):
        self.caja_facturas.delete(0, END)
        for fila in leerTodo("FACTURA"):
            self.caja_facturas.insert(END, fila)

    def ver_servicios(self):
        servicios_factura = []
        self.caja_servicios.delete(0, END)
        for fila in leerRegistro("SERVICIO", "FACTURA_ID",
                                 self.texto_id_factura.get()):
            servicios_factura.append(fila)
            self.caja_servicios.insert(END, fila)
        return servicios_factura

    def actualizar_total(self):
        total = 0

        for fila in leerRegistro("SERVICIO", "FACTURA_ID",
                                 self.texto_id_factura.get()):
            total += float(fila[3])
        total_calculado = total * (1 - float(self.cuadro_descuento.get()) *
                                   0.01) * (1 +
                                            float(self.combo_iva.get()) * 0.01)
        total_calculado = round(total_calculado, 2)
        print("Total actualizado a ", total_calculado)
        self.cuadro_total.delete(0, END)
        self.cuadro_total.insert(END, total_calculado)
Пример #30
0
    else:
        print("Error")
        disimg.title("ERROR")
        w =tk.Label(disimg, text="Please select correct date.\n Date must be between Jun 16, 1995 to Today's Date.",height=3,width=100,wraplength=200)
        w.pack()
    disimg.mainloop()
def download(link):
    c=E1.get()
    c=c.split("/")
    c=c[2]+c[0]+c[1]
    r = requests.get(link, allow_redirects=True)
    name=c
    open(name+'.jpg', 'wb').write(r.content)
def changewall(url):
    os.system("/usr/bin/gsettings set org.gnome.desktop.background picture-uri "+url)

root.title("Kise")
cal = DateEntry(root, width=12,date_pattern='mm/dd/y', background='darkblue', foreground='white', borderwidth=2)
t=cal.get()
w =tk.Label(root, text="Today's Date:",height=2,width=100,wraplength=200)
w.pack()
E1 = tk.Entry( bd =5,text=t)
E1.insert(0,t)
E1.configure(state='readonly')
E1.pack()
B = tk.Button(root, text ="Update", command = up)
cal.pack(padx=10, pady=10)
B.pack()
root.mainloop()
#coded by kise