예제 #1
0
파일: UI.py 프로젝트: KNMI-DataLab/PyTSI
class CalenderUI:
    """Calendar interface. Example taken from the official documentation of tkcalendar."""

    def __init__(self, cal_root):
        """Construct widget with master as parent widget"""
        self.top = tk.Toplevel(cal_root)

        self.cal = Calendar(self.top, font="Arial 14", selectmode='day',
                            cursor="hand1", year=int(settings.year), month=int(settings.month), day=int(settings.day))
        self.cal.pack(fill="both", expand=True)
        ttk.Button(self.top, text="ok", command=self.print_sel).pack()
        ttk.Button(self.top, text="exit", command=self.quit1).pack()

        self.date = ''

        self.top.grab_set()

    def print_sel(self):
        """Callback function saving the date to a variable."""
        self.date = self.cal.selection_get()

    def quit1(self):
        """Callback function that saves the date to a variable and exits the calendar window"""
        self.date = self.cal.selection_get()
        self.top.destroy()
예제 #2
0
    def test_calendar_init(self):
        widget = Calendar(self.window)
        widget.pack()
        self.window.update()
        widget.destroy()
        widget = Calendar(self.window, font="Arial 14", selectmode='day',
                          cursor="hand1", year=2018, month=2, day=5)
        widget.pack()
        self.window.update()
        self.assertEqual(widget.selection_get(), date(2018, 2, 5))
        widget.destroy()

        widget = Calendar(self.window, year=2011, month=2, day=35)
        widget.pack()
        self.window.update()
        self.assertIsNone(widget.selection_get())
        self.assertEqual(widget._date, date(2011, 2, 1))
        widget.destroy()

        with self.assertRaises(ValueError):
            widget = Calendar(self.window, month=23)
            widget.pack()
            self.window.update()
            widget.destroy()

        with self.assertRaises(ValueError):
            widget = Calendar(self.window, borderwidth="e")
            widget.pack()
            self.window.update()
            widget.destroy()

        widget = Calendar(self.window, font="Arial 14", selectmode='day',
                          cursor="hand1", year=2018, month=2, day=5)
        widget.pack()
        self.window.update()
        widget.destroy()

        widget = Calendar(self.window, selectmode='none', locale=None,
                          year=2015, month=1, background="black",
                          foreground="white", key="a")
        widget.pack()
        self.window.update()
        self.assertIsNone(widget.selection_get())
        self.assertEqual(widget._date, date(2015, 1, 1))
        widget.destroy()

        with self.assertRaises(ValueError):
            widget = Calendar(self.window, selectmode='wrong')
            widget.pack()
            self.window.update()
            widget.destroy()
예제 #3
0
    def test_calendar_textvariable(self):
        var = tk.StringVar(self.window)
        widget = Calendar(self.window,
                          selectmode='day',
                          year=2015,
                          month=1,
                          day=3,
                          textvariable=var)
        widget.pack()
        self.window.update()
        self.assertEqual('', var.get())
        self.assertEqual('', widget.get_date())
        self.assertEqual(date(2015, 1, 1), widget._date)
        widget.selection_set(date(2018, 11, 21))
        self.window.update()
        self.assertEqual(format_date(date(2018, 11, 21), 'short'), var.get())
        self.assertEqual(format_date(date(2018, 11, 21), 'short'),
                         widget.get_date())
        widget.selection_set(None)
        self.window.update()
        self.assertEqual('', widget.get_date())
        self.assertEqual('', var.get())
        var.set(format_date(date(2014, 3, 2), 'short'))
        self.window.update()
        self.assertEqual(date(2014, 3, 2), widget.selection_get())
        self.assertEqual(format_date(date(2014, 3, 2), 'short'), var.get())
        self.assertEqual(format_date(date(2014, 3, 2), 'short'),
                         widget.get_date())
        try:
            var.set('a')
        except tk.TclError:
            # some versions of python raise an error because of the exception
            # raised inside the trace
            pass
        self.window.update()
        self.assertEqual(date(2014, 3, 2), widget.selection_get())
        self.assertEqual(format_date(date(2014, 3, 2), 'short'), var.get())
        self.assertEqual(format_date(date(2014, 3, 2), 'short'),
                         widget.get_date())
        var.set('')
        self.window.update()
        self.assertIsNone(widget.selection_get())
        self.assertEqual('', var.get())
        self.assertEqual('', widget.get_date())

        var2 = tk.StringVar(widget, format_date(date(2011, 1, 21), 'short'))
        widget['textvariable'] = var2
        self.window.update()
        self.assertEqual(widget.get_date(), var2.get())
        self.assertEqual('', var.get())
예제 #4
0
class CalendarGUI:
    is_open = False
    #새로 생성되는 클래스의 인자에 MainGUI을 넣어서 MainGUI 객체를 가져오게 함 그렇게 되면 MainGUI에 있는 변수들을 수정 가능

    def __init__(self, MainGui, selectCommand=None):

        if CalendarGUI.is_open:
            return
        CalendarGUI.is_open = True
        self.main_gui = MainGui
        self.gui = Toplevel(self.main_gui.gui)
        self.gui.title("Calendar")
        now = datetime.datetime.now()
        self.cal = Calendar(self.gui, selectmode='day', year=now.year, month=now.month, day=now.day)
        self.cal.pack(pady=10)

        Button(self.gui, text="날짜 선택", command=lambda cmd=selectCommand: self.SetTravelDate(command=cmd)).pack()

        self.gui.protocol("WM_DELETE_WINDOW", self.Closing)

    #현재는 시간이 20, 30으로 고정되어 있는데 이 부분은 xml 데이터 파일의 정보를 가져와서 설정해 주어야함.
    def SetTravelDate(self, command=None):
        date = self.cal.selection_get()

        if command is not None:
            command(date)

    def Closing(self):
        CalendarGUI.is_open = False
        self.gui.destroy()
예제 #5
0
    def get_calendar(self):
        print('in get_calendar app')
        window = tk.Tk()
        cal = Calendar(window)
        year = time.localtime(time.time())[0]
        month = time.localtime(time.time())[1]
        date = time.localtime(time.time())[2]

        if month == 12:
            cal.config(mindate=datetime.date(year, month, date),
                       maxdate=datetime.date(year, 1, date))
        elif month == 1 and date > 28:
            cal.config(mindate=datetime.date(year, month, date),
                       maxdate=datetime.date(year, month + 1, 28))
        else:
            try:
                cal.config(mindate=datetime.date(year, month, date),
                           maxdate=datetime.date(year, month + 1, date))
            except ValueError:
                cal.config(mindate=datetime.date(year, month, date),
                           maxdate=datetime.date(year, month + 1, date - 1))

        cal.config(showweeknumbers=False,
                   disabledbackground='red',
                   disabledforeground='blue',
                   disabledselectbackground='pink',
                   disabledselectforeground='purple',
                   disableddaybackground='red')
        cal.pack()

        select_button = tk.Button(cal,
                                  text='Select Date',
                                  command=lambda: print(cal.selection_get()))
        select_button.pack()
        cal.mainloop()
class Cal:
    def __init__(self, root):

        self.date = ''

        self.top = tk.Toplevel(root)
        self.top.title('Select Start Date')

        self.cal = Calendar(
            self.top,
            font='Arial 14',
            selectmode='day',
            cursor='hand1',
        )
        self.cal.pack(fill='both', expand=True)
        tk.Button(self.top, text='OK', command=self.set_date).pack()
        tk.Button(self.top, text='Close', command=self.quit).pack()

    def set_date(self):
        self.date = self.cal.selection_get()
        self.top.destroy()

    def get_date(self):
        return self.date

    def quit(self):
        self.top.destroy()
예제 #7
0
class HebrewSchedulerGUI(object):
    def __init__(self, input_handler):
        self.input_handler = input_handler
        self.root = tk.Tk(className=' HebrewScheduler')
        s = ttk.Style(self.root)
        s.theme_use('clam')
        tk.Label(self.root, text="Summary").grid(row=0)
        tk.Label(self.root, text="Description").grid(row=1)
        tk.Label(self.root, text="Location").grid(row=2)
        tk.Label(self.root, text="Number of years").grid(row=3)
        tk.Label(self.root, text="Color").grid(row=4)
        ttk.Button(self.root, text='Calendar',
                   command=self.open_calendar).grid(row=5)

        self.summary = tk.Entry(self.root)
        self.desc = tk.Entry(self.root)
        self.loc = tk.Entry(self.root)
        self.num_of_years = tk.Entry(self.root)

        self.color_listbox = tk.Listbox(self.root,
                                        selectmode=tk.SINGLE,
                                        height=len(configuration.COLOR_CODES))
        for i, (c_n, c) in enumerate(
                zip(configuration.COLOR_CODES_LEGEND.keys(),
                    configuration.COLOR_CODES)):
            self.color_listbox.insert("end", c_n)
            self.color_listbox.itemconfig(i, {'bg': c})

        self.summary.grid(row=0, column=1)
        self.desc.grid(row=1, column=1)
        self.loc.grid(row=2, column=1)
        self.num_of_years.grid(row=3, column=1)
        self.color_listbox.grid(row=4, column=1)

        self.top = None
        self.cal = None

    def open_calendar(self):
        self.top = tk.Toplevel(self.root)
        ttk.Label(self.top, text='Choose date').pack(padx=10, pady=10)
        self.cal = Calendar(self.top,
                            font="Arial 14",
                            selectmode='day',
                            cursor="hand1")
        self.cal.pack(fill="both", expand=True)
        ttk.Button(self.top, text="ok", command=self.process_inputs).pack()

    def process_inputs(self):
        picked_vals = (self.cal.selection_get(), self.summary.get(),
                       self.desc.get(), self.loc.get(),
                       configuration.COLOR_CODES_LEGEND[
                           self.color_listbox.selection_get()],
                       int(self.num_of_years.get()))
        print(picked_vals)
        self.top.destroy()
        self.root.destroy()
        self.input_handler(*picked_vals)

    def run_gui(self):
        self.root.mainloop()
예제 #8
0
 def set_date(this, calendar: Calendar, enty: tkinter.Entry,
              frame: tkinter.Toplevel):
     enty.config(state="normal")
     enty.delete(0, "end")
     enty.insert(0, calendar.selection_get())
     enty.config(state="disabled")
     frame.destroy()
예제 #9
0
class CusCalendar():
    def __init__(self, root):
        self.top = tk.Toplevel(root)
        self.cal = Calendar(self.top,
                            font="Arial 14",
                            selectmode='day',
                            cursor="hand1",
                            year=2018,
                            month=2,
                            day=5)
        self.cal.pack(fill="both", expand=True)
        ttk.Button(self.top, width="14", text="선택",
                   command=self.select_date).pack(side="left", padx=5, pady=5)
        ttk.Button(self.top, width="14", text="창닫기",
                   command=self.destory_win).pack(side="left", padx=5, pady=5)
        # self.date = ''
        # self.top.grab_set()

    def select_date(self):
        self.date = self.cal.selection_get()
        self.top.destroy()

    def destory_win(self):
        self.date = ''
        self.top.destroy()

    pass
예제 #10
0
    def test_calendar_buttons_functions(self):
        widget = Calendar(self.window)
        widget.pack()
        widget._prev_month()
        widget._next_month()
        widget._prev_year()
        widget._next_year()
        widget._remove_selection()
        widget.selection_set(format_date(date(2018, 12, 31), 'short'))
        self.assertEqual(widget.selection_get(), date(2018, 12, 31))
        with self.assertRaises(ValueError):
            widget.selection_set("ab")
        widget.selection_set(None)
        self.assertIsNone(widget.selection_get())
        widget.selection_set(date(2015, 12, 31))
        self.assertEqual(widget.selection_get(), date(2015, 12, 31))

        widget.config(selectmode='none')
        self.assertIsNone(widget.selection_get())
        l = ttk.Label(widget, text="12")
        widget._on_click(TestEvent(widget=l))
        self.assertIsNone(widget.selection_get())
        self.window.update()
        widget.config(selectmode='day')
        l = ttk.Label(widget, text="12")
        widget._on_click(TestEvent(widget=l))
        self.window.update()
        self.assertEqual(widget.selection_get(), date(2015, 12, 12))
        widget.config(state='disabled')
        l = ttk.Label(widget, text="14")
        widget._on_click(TestEvent(widget=l))
        self.window.update()
        self.assertEqual(widget.selection_get(), date(2015, 12, 12))
예제 #11
0
def ViewCalendar():  #Pop Calendar Function #Srishti
    cal_window = tk.Tk()
    cal_window.title("Canteen Viewer Calendar")
    cal_window.iconbitmap("./Gui_Images/CanteenViewer.ico")
    cal_window.resizable(False, False)

    todaydate = dt.today()
    label_Select = tk.Label(
        cal_window,
        text="Please Choose A Date and Enter A Time",
        font="Verdana 15 bold",
        foreground="white",
        background="black",
        padx=5,
        pady=5,
        relief="groove")  #Heading "Please Choose A Date and Enter A Time"
    label_Select.pack()

    cal = Calendar(
        cal_window,
        font="Verdana 12 bold",
        selectmode="day",
        curcor="hand1",
        background="gray",
        foreground="white",
        year=todaydate.year,
        month=todaydate.month,
        day=todaydate.day,
    )  #Calendar Picker
    cal.pack(fill="both")

    userEntry = tk.Entry(cal_window, text="HHMM",
                         font="Verdana 18")  #Entry Box to input time
    userEntry.pack()

    button_Select = tk.Button(
        cal_window,
        text="Enter",
        font="Verdana 11 bold",
        foreground="black",
        background="white",
        padx=5,
        command=lambda: SelectedDayStall(userEntry.get(), cal.selection_get(
        ), cal_window))  #Confirm date and time selected
    button_Select.pack()
    button_Select.place(relx=0.99, rely=0.995, anchor="se")

    label_HHMM = tk.Label(cal_window,
                          text="HHMM >",
                          font="Verdana 11 bold",
                          foreground="black",
                          background="white")  #Label "HHMM"
    label_HHMM.pack()
    label_HHMM.place(relx=0, rely=0.98, anchor="sw")
예제 #12
0
    def test_calendar_buttons_functions(self):
        widget = Calendar(self.window)
        widget.pack()
        widget._prev_month()
        widget._next_month()
        widget._prev_year()
        widget._next_year()
        widget._remove_selection()
        widget.selection_set(datetime(2018, 12, 31).strftime('%x'))
        self.assertEqual(widget.selection_get(), datetime(2018, 12, 31))
        with self.assertRaises(ValueError):
            widget.selection_set("ab")
        widget.selection_set(None)
        self.assertIsNone(widget.selection_get())
        widget.selection_set(datetime(2015, 12, 31))
        self.assertEqual(widget.selection_get(), datetime(2015, 12, 31))

        widget.config(selectmode='none')
        self.assertIsNone(widget.selection_get())

        l = ttk.Label(widget, text="12")
        widget._on_click(TestEvent(widget=l))
예제 #13
0
def seleccionarFechas():
  # Metodo para seleccionar las fechas de la prediccion
  clearVentana()
  l_inicio = Label(root, text="Seleccione fecha de inicio")
  cal_inicio = Calendar(root, font="Arial 12", year=2018, month=10, day=1)
  l_horaI = Label(root, text="Seleccione la hora")  
  hora_inicio = Entry(root)
  hora_inicio.insert(END, '00:00')
  insertarComponentesEnVentana([l_inicio, cal_inicio, l_horaI, hora_inicio])
  
  espacioEntreComponentes(root)
  l_final = Label(root, text="Seleccione fecha de termino")
  cal_final = Calendar(root, font="Arial 12", year=2018, month=10, day=2)
  l_horaF = Label(root, text="Seleccione la hora")
  hora_final = Entry(root)
  hora_final.insert(END, '23:59')
  insertarComponentesEnVentana([l_final, cal_final, l_horaF, hora_final])
  
  # Boton para realizar las predicciones  
  espacioEntreComponentes(root)
  boton_sig = Button(root, text="Siguiente", command= lambda: especificacionDatos(\
    cal_inicio.selection_get(), hora_inicio.get(), cal_final.selection_get(), hora_final.get()))
  boton_sig.pack()
예제 #14
0
 def test_calendar_textvariable(self):
     var = tk.StringVar(self.window,)
     widget = Calendar(self.window, selectmode='day', locale=None,
                       year=2015, month=1, day=3, textvariable=var)
     widget.pack()
     self.window.update()
     self.assertEqual(datetime(2015, 1, 3).strftime('%x'), var.get())
     self.assertEqual(datetime(2015, 1, 3).strftime('%x'), widget.get_date())
     widget.selection_set(datetime(2018, 11, 21))
     self.window.update()
     self.assertEqual(datetime(2018, 11, 21).strftime('%x'), var.get())
     self.assertEqual(datetime(2018, 11, 21).strftime('%x'), widget.get_date())
     widget.selection_set(None)
     self.window.update()
     self.assertEqual('', widget.get_date())
     self.assertEqual('', var.get())
     var.set(datetime(2014, 3, 2).strftime('%x'))
     self.window.update()
     self.assertEqual(datetime(2014, 3, 2), widget.selection_get())
     self.assertEqual(datetime(2014, 3, 2).strftime('%x'), var.get())
     self.assertEqual(datetime(2014, 3, 2).strftime('%x'), widget.get_date())
     try:
         var.set('a')
     except tk.TclError:
         # some versions of python raise an error because of the exception
         # raised inside the trace
         pass
     self.window.update()
     self.assertEqual(datetime(2014, 3, 2), widget.selection_get())
     self.assertEqual(datetime(2014, 3, 2).strftime('%x'), var.get())
     self.assertEqual(datetime(2014, 3, 2).strftime('%x'), widget.get_date())
     var.set('')
     self.window.update()
     self.assertIsNone(widget.selection_get())
     self.assertEqual('', var.get())
     self.assertEqual('', widget.get_date())
예제 #15
0
def get_date():
    def cal_done():
        top.withdraw()
        root.quit()
        root.destroy()

    root = tk.Tk()
    root.withdraw()  # keep the root window from appearing

    top = tk.Toplevel(root)

    cal = Calendar(top, font="Arial 14", selectmode='day', cursor="hand1")
    cal.pack(fill="both", expand=True)
    ttk.Button(top, text="ok", command=cal_done).pack()

    selected_date = None
    root.mainloop()
    return cal.selection_get()
예제 #16
0
class MainGui():
    def __init__(self, master):
        self.master = master
        master.title("Linear YahooStocks")
        master.geometry("{}x{}".format(300, 300))
        self.link = Entry()
        self.link_text = Label(text="Entry link: ")
        self.cal_but = Button(text="choose date", command=self.date_select)
        self.cal_lab = Label()
        self.start_but = Button(text="start", command=self.start_regression)
        self.link.grid(row=0, column=1)
        self.link_text.grid(row=0, column=0)
        self.cal_but.grid(row=1, column=0)
        self.cal_lab.grid(row=1, column=1)
        self.start_but.grid(row=2, columnspan=2)
        self.date2 = date.today()
        f = open("config.txt", "r")
        lines = f.readlines()
        self.driver_path = str(lines[0])
        self.download_path = str(lines[1])
        f.close()
    def calendar(self, root):
        self.top = Toplevel(root)
        self.date = date.today()
        self.cal = Calendar(self.top, font="Arial 14", selectmode="day", cursor="hand1", year=self.date.year,
                            month=self.date.month, day=self.date.day)
        self.cal.pack(fill="both", expand=True)
        Button(self.top, text="select", command=self.print_sel).pack()
        self.top.grab_set()
    def print_sel(self):
        self.date2 = self.cal.selection_get()
        self.cal_lab.configure(text=str(self.date2))
        self.top.destroy()
    def date_select(self):
        self.calendar(self.master)
    def start_regression(self):

        link =self.link.get()
        S = StockCSV(driver=self.driver_path)
        S.download_stock_diagram(url=link)
        folder = S.get_stock_diagram(dir=self.download_path)
        Sr = StockReg(csv=folder)
        Sr.predict_period(self.date2.year, self.date2.month, self.date2.day)
        Sr.show_graph()
예제 #17
0
    def show_cal2():
        toplevel1 = Toplevel()

        def print_sel():
            s2.set(cal.selection_get())
            toplevel1.destroy()

        today = str(date.today())
        l1 = today.split("-")
        year = l1[0]
        month = l1[1]
        day = l1[2]
        cal = Calendar(toplevel1,
                       font="Arial 14",
                       selectmode='day',
                       cursor="hand1",
                       year=int(year),
                       month=int(month),
                       day=int(day))
        cal.grid(row=0, column=0)
        s2.set(cal.selection_get())
        Button(toplevel1, text="Done", command=print_sel).grid(row=1, column=0)
예제 #18
0
class CalendarView(View):
    def __init__(self, parent, controller):
        View.__init__(self, parent, controller)

        self.mindate = datetime.date.today() - datetime.timedelta(days=30)
        self.calendar = Calendar(self,
                                 font="Comic_Sans 14",
                                 selectmode='day',
                                 locale='en_US',
                                 mindate=self.mindate,
                                 disabledforeground='red',
                                 cursor="hand2")

        self.calendar.tag_config('Komunia',
                                 background='yellow',
                                 foreground='black')
        self.calendar.tag_config('Wesele',
                                 background='red',
                                 foreground='black')
        self.calendar.tag_config('Spotkanie biznesowe',
                                 background='blue',
                                 foreground='white')
        self.calendar.tag_config('Urodziny',
                                 background='black',
                                 foreground='yellow')

        self.button_frame = tk.Frame(self)
        self.buttons = []
        self.__build_grid()

        self.grid_columnconfigure(0, weight=1)

    def __build_grid(self):
        self.calendar.grid(column=0, row=0)
        self.button_frame.grid(column=0, row=1)

    def get_date(self):
        return self.calendar.selection_get()
예제 #19
0
class calendario():
    def __init__(self, root, mini=date(year=2019, month=9, day=11)):
        self.top = Toplevel(root)
        self.cal = Calendar(self.top,
                            font=('Times New Roman', 14),
                            selectmode='day',
                            mindate=mini,
                            maxdate=date.today() - timedelta(1),
                            cursor='arrow')
        self.cal.pack(padx=7, pady=11)
        ttk.Button(self.top, text='ok', command=self.get_sel).pack()
        self.date = ''

        self.top.grab_set()

    def get_sel(self):
        self.date = self.cal.selection_get()

        self.top.destroy()

    def format_date(self):
        return str(self.date.day) + '\\' + str(self.date.month) + '\\' + str(
            self.date.year)
예제 #20
0
파일: old.py 프로젝트: jobmos/PyTSI-UI
class Example1():
    def __init__(self, root):
        self.top = tk.Toplevel(root)

        self.cal = Calendar(self.top,
                            font="Arial 14",
                            selectmode='day',
                            cursor="hand1",
                            year=2018,
                            month=2,
                            day=5)
        self.cal.pack(fill="both", expand=True)
        ttk.Button(self.top, text="ok", command=self.print_sel).pack()
        ttk.Button(self.top, text="exit", command=self.quit1).pack()

        self.date = ''

        self.top.grab_set()

    def print_sel(self):
        self.date = self.cal.selection_get()

    def quit1(self):
        self.top.destroy()
class Window:
    def __init__(self, master):
        '''Inisialisasi window'''

        self.master = master
        self.init_window()

    def init_window(self):
        '''Mengabungkan semua method dalam satu window'''

        self.master.title("Kalkulator Waktu Sholat")
        self.fontstyle = Font(family='Times New Roman', size=12)
        self.fontstyle2 = Font(family='Times New Roman', size=11)
        self.fontstyle3 = ('Times New Roman', 12, 'bold')
        self.fontstyle4 = ('Times New Roman', 17, 'bold')
        self.menus()
        self.make_frame()
        self.title()
        self.get_date()
        self.frame_1()
        self.frame_2()
        self.convert_button()
        self.frame_3()

    def menus(self):
        '''Membuat menu'''

        menu = Menu(self.master)
        self.master.config(menu=menu)

        file = Menu(menu)
        file.add_command(label='Save As..', command=self.save_file)
        file.add_command(label='Exit', command=self.exit_program)

        view = Menu(menu)
        view.add_command(label='Show Credit', command=self.show_credit)
        view.add_command(label='Hide Credit', command=self.hide_credit)

        helps = Menu(menu)
        helps.add_command(label='About', command=self.about)

        menu.add_cascade(label='File', menu=file)
        menu.add_cascade(label='View', menu=view)
        menu.add_cascade(label='Help', menu=helps)

    def exit_program(self):
        '''Perintah untuk keluar dari program'''

        exit()

    def show_credit(self):
        '''Menampilkan credit pada bagian bawah window'''

        self.lbl_version = Label(
            self.master,
            text='Program Kalkulator Waktu Shalat Version 1.5 - ',
            font=self.fontstyle,
            fg='black')
        self.lbl_credit = Label(
            self.master,
            text='Created by Adh : [email protected]',
            font=self.fontstyle,
            fg='black')
        self.lbl_version.place(x=20, y=620)
        self.lbl_credit.place(x=315, y=620)

    def hide_credit(self):
        '''Menyembuyikan credit pada bagian bawah window setelah dipanggil menggunakn show_credit()'''

        self.lbl_credit.place_forget()
        self.lbl_version.place_forget()

    def make_frame(self):
        '''Membuat widget frame pada jendela window'''

        self.frame1 = Frame(height=210,
                            width=550,
                            bg='#f0f8ff',
                            borderwidth=3,
                            relief=GROOVE)
        self.frame2 = Frame(height=210,
                            width=360,
                            bg='#7eb593',
                            borderwidth=3,
                            relief=GROOVE)
        self.frame3 = Frame(height=390,
                            width=925,
                            bg='#c0d6e4',
                            borderwidth=3,
                            relief=GROOVE)
        self.frame1.place(x=10, y=10)
        self.frame2.place(x=575, y=10)
        self.frame3.place(x=10, y=230)

    def title(self):
        '''Membuat judul program/aplikasi -- diletakkan di bagian atas window'''

        title = Label(self.frame2,
                      text="KALKULATOR WAKTU \nSHALAT",
                      font=self.fontstyle4,
                      fg='darkgreen',
                      bg='#7eb593')
        title.place(x=50, y=5)

    def get_date(self):
        '''Menampilkan kalender'''

        self.kalender = Calendar(self.frame1,
                                 font=self.fontstyle2,
                                 selectmode='day',
                                 cursor='hand1')
        self.kalender.place(x=260, y=0)
        selected_date = None

    def about(self):
        '''Membuat jendela about'''

        about = Toplevel()
        about.title('About')
        about.geometry('300x115')
        about.resizable(0, 0)
        icon_photo = PhotoImage(file='cal_logo.ico')
        about.iconphoto(False, icon_photo)

        title = Label(master=about,
                      text="KALKULATOR WAKTU\nSHALAT",
                      font=self.fontstyle3,
                      justify='center',
                      fg='green')
        email = Label(master=about,
                      text="Adh : [email protected]",
                      font=self.fontstyle,
                      justify='center')
        version = Label(master=about,
                        text="Version 1.5 - @2020",
                        font=self.fontstyle,
                        justify='center')
        title.pack()
        email.pack()
        version.pack()

    def dataset(self):
        '''Memuat dataset yang digunakan pada perhitungan waktu sholat'''

        dataset = pd.read_csv(os.path.dirname(os.getcwd()) +
                              '/data/KOTA_DATABASE_COMPLETE.csv',
                              sep=';')
        negara = dataset.Country
        negara = negara.drop_duplicates()

        return negara, dataset

    def frame_1(self):
        '''Frame - 1'''

        title = Label(self.frame1,
                      text="Masukkan Input",
                      font=(self.fontstyle),
                      fg='darkgreen',
                      bg='#f0f8ff')
        title.place(x=75, y=5)
        #Style
        style = ttk.Style()
        style.theme_use('clam')

        #Label
        lbl_negara = Label(self.frame1,
                           text='Negara 	    : ',
                           font=self.fontstyle,
                           bg='#f0f8ff')
        tanggal = Label(self.frame1,
                        text='Tanggal 	    : ',
                        font=self.fontstyle,
                        bg='#f0f8ff')
        lbl_kota = Label(self.frame1,
                         text='Kota    	    :',
                         font=self.fontstyle,
                         bg='#f0f8ff')
        lbl_tanggalVar = StringVar()
        lbl_tanggal = Label(self.frame1,
                            text=self.kalender.selection_get(),
                            font=self.fontstyle,
                            width=15,
                            justify='center',
                            bg='lightgreen')

        def select_date():
            '''Memilih tanggal pada kalendar'''

            date = self.kalender.selection_get()
            lbl_tanggal.configure(text=date)

        #Tombol OK
        ok_button = Button(self.frame1,
                           text='OK',
                           font=self.fontstyle2,
                           width=2,
                           command=select_date)
        ok_button.place(x=515, y=170)

        #Combobox Negara dan Kota
        style.map('TCombobox', fieldbackground=[('readonly', 'lightgreen')])
        style.map('TCombobox', background=[('readonly', 'lightgreen')])
        style.map('TCombobox', foreground=[('readonly', 'black')])
        cmb_negaraVar = StringVar()
        self.cmb_negara = ttk.Combobox(self.frame1,
                                       textvariable='cmb_negaraVar',
                                       font=self.fontstyle,
                                       width=15,
                                       justify='center')

        cmb_kotaVar = StringVar()
        self.cmb_kota = ttk.Combobox(self.frame1,
                                     textvariable='cmb_kotaVar',
                                     font=self.fontstyle,
                                     width=15,
                                     justify='center')

        negara, dataset = self.dataset()
        value_negara = ['Pilih Negara']
        for country in negara:
            value_negara.append(country)

        self.cmb_negara['values'] = value_negara
        self.cmb_negara['state'] = 'readonly'
        self.cmb_negara.current(0)

        #Place
        lbl_negara.place(x=5, y=32)
        tanggal.place(x=5, y=100)
        self.cmb_negara.place(x=100, y=32)
        lbl_tanggal.place(x=100, y=100)
        lbl_kota.place(x=5, y=68)
        self.cmb_kota.place(x=100, y=65)

    def frame_2(self):
        '''Frame - 2'''

        #Mengammbil tanggal hari ini
        hari_ini = datetime.datetime.now()
        hari = hari_ini.weekday()
        nama_hari = calendar.day_name[hari]

        harii = '{}, {} {} {}'.format(nama_hari, hari_ini.day,
                                      hari_ini.strftime('%B'), hari_ini.year)

        def time():
            '''Konfigurasi lbl_jam denga format H:M:S'''

            string = strftime('%H:%M:%S')
            lbl_jam.config(text=string)
            lbl_jam.after(1000, time)

        lbl_hari = Label(self.frame2,
                         text=harii,
                         font=self.fontstyle,
                         bg='#7eb593')
        lbl_jam = Label(self.frame2,
                        font=('Times New Roman', 50),
                        bg='#7eb593')
        time()

        lbl_hari.place(x=100, y=70)
        lbl_jam.place(x=70, y=95)

    def take_city_value(self):
        '''Mengambil value dari Combobox berupa negara dan kota'''

        negara, dataset = self.dataset()
        negara_pilih = self.cmb_negara.current()

        def callback(eventObject):
            '''Event handling, jika terjadi event pada combobox Negara, akan menambilkan
				daftar kota paa combobox Kota'''

            pilihan_negara = eventObject.widget.get()
            print(eventObject.widget.get())  #Negara yang dipilih User
            negara_mask = dataset["Country"].values == pilihan_negara
            kota = dataset["City"].loc[negara_mask]

            self.value_kota = []
            for city in kota:
                self.value_kota.append(city)

            self.cmb_kota['values'] = self.value_kota
            self.cmb_kota['state'] = 'readonly'
            self.cmb_kota.current(0)

        #Bind callback ke combobox
        self.cmb_negara.bind("<<ComboboxSelected>>", callback)

        kota_cmb = self.cmb_kota.get()
        negara_cmb = self.cmb_negara.get()
        print(kota_cmb)  #Kota yang dipilih User
        nama_kota = dataset.loc[dataset['City'] == kota_cmb]

        return nama_kota, kota_cmb, negara_cmb

    def hitung_waktu_shalat(self):
        '''Menghitung waktu sholat dengan menggunakan module Waktu Sholat'''

        nama_kota, kota_cmb, negara_cmb = self.take_city_value()

        #Untuk pertama kali, nilai lintang dll harus ada nilainya,
        #sehingga perlu diinisialisasi
        try:
            lintang = float(nama_kota.Latitude.values[0])
            bujur = float(nama_kota.Longitude.values[0])
            ketinggian = nama_kota.Elevation.values[0]
            zona_waktu = nama_kota.Time_zone.values[0]
        except IndexError:
            lintang = 0
            bujur = 0
            ketinggian = 50
            zona_waktu = 0

        tahun = self.kalender.selection_get().year
        bulan = self.kalender.selection_get().month
        tanggal = self.kalender.selection_get().day

        #Menambahkan tanda + pada zona waktu tertentu
        if int(zona_waktu) > 0:
            get_time_zone = '+' + str(zona_waktu)
        else:
            get_time_zone = str(zona_waktu)

        nama_bulanDict = {
            1: 'Jan',
            2: 'Feb',
            3: 'Mar',
            4: 'Apr',
            5: 'May',
            6: 'Jun',
            7: 'Jul',
            8: 'Aug',
            9: 'Sep',
            10: 'Oct',
            11: 'Nov',
            12: 'Dec'
        }
        no_bulan = list(nama_bulanDict.keys())
        nama_bulan = list(nama_bulanDict.values())
        jumlah_hari = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

        #Menempatkan nama kota, lintang, bujur dan zona waktu pada frame 2
        #nilainya akan diupdate setiap tombol hitung waktu sholat ditekan
        sign_lat = 'N'
        if lintang < 0:
            sign_lat = 'S'

        sign_lng = 'E'
        if bujur < 0:
            sign_lng = 'W'

        lbl_desc1 = Label(self.frame3,
                          text=("{}").format(kota_cmb),
                          width=20,
                          font=('Times New Roman', 12, 'bold'),
                          bg='#c0d6e4',
                          fg='blue',
                          justify='center')
        lbl_desc2 = Label(
            self.frame3,
            text=("{}\N{DEGREE SIGN} {}  -  {}\N{DEGREE SIGN} {}").format(
                abs(lintang), sign_lat, abs(bujur), sign_lng),
            width=20,
            font=('Times New Roman', 12, 'bold'),
            bg='#c0d6e4',
            fg='blue',
            justify='center')
        lbl_desc3 = Label(self.frame3,
                          text=("GMT {}").format(get_time_zone),
                          width=7,
                          font=('Times New Roman', 12, 'bold'),
                          bg='#c0d6e4',
                          fg='blue',
                          justify='center')
        lbl_desc1.place(x=720, y=60)
        lbl_desc2.place(x=720, y=83)
        lbl_desc3.place(x=783, y=103)

        #Jika user menyimpan file
        self.file_to_save1 = "\t\t\t\t\t\tJADWAL SHALAT BULANAN {}, {} - BULAN {} TAHUN {}\n".format(
            kota_cmb, negara_cmb, bulan, tahun)
        self.file_to_save2 = "\t\t\t\t\t\t\tLintang : {}\N{DEGREE SIGN} {}, Bujur : {}\N{DEGREE SIGN} {}, GMT : {}\n\n\n".format(
            abs(lintang), sign_lat, abs(bujur), sign_lng, get_time_zone)

        def isLeap(tahun):
            '''Menentukan apakah tahun kabisat atau tidak'''

            kabisat = 28
            if tahun % 4 == 0:
                if tahun % 100 == 0:
                    if tahun % 400 == 0:
                        kabisat = 29
                    else:
                        kabisat = 28
                else:
                    kabisat = 29
            else:
                kabisat = 28
            return kabisat

        if bulan == 2:
            jumlah_hari[1] = isLeap(tahun)

        month = []
        date = 0
        for i in range(0, len(no_bulan) + 1):
            if bulan == no_bulan[i - 1]:
                month.append(nama_bulan[i - 1])
            if i == bulan:
                date = (jumlah_hari[i - 1])

        #List kosong jadwal sholat
        subuh_list = []
        terbit_list = []
        zuhur_list = []
        ashar_list = []
        maghrib_list = []
        isya_list = []

        for day in range(1, int(date) + 1):
            #Jika value error (untuk lintang ekstrem) akan menghitung waktu sholat
            #dengan menggunakan class LintangEkstrem
            #kekurangan --> tanggal terkhir tidak dihitung / listnya kosong
            try:
                jadwal_shalat = WaktuSholat(tahun, bulan, day, lintang, bujur,
                                            zona_waktu, ketinggian)
                subuh, terbit, zuhur, ashar, maghrib, isya = jadwal_shalat.show_result(
                )
                subuh_list.append(subuh)
                terbit_list.append(terbit)
                zuhur_list.append(zuhur)
                ashar_list.append(ashar)
                maghrib_list.append(maghrib)
                isya_list.append(isya)

            except ValueError:
                try:
                    jadwal_shalat = LintangEkstrem(tahun, bulan, day, lintang,
                                                   bujur, zona_waktu,
                                                   ketinggian)
                    subuh, terbit, zuhur, ashar, maghrib, isya = jadwal_shalat.result(
                    )
                    subuh_list.append(subuh)
                    terbit_list.append(terbit)
                    zuhur_list.append(zuhur)
                    ashar_list.append(ashar)
                    maghrib_list.append(maghrib)
                    isya_list.append(isya)
                except IndexError:
                    continue
                continue

        self.lbl_date = Label(self.frame3,
                              text='{} {} {}'.format(tanggal, month[0], tahun),
                              width=10,
                              font=self.fontstyle3,
                              bg='#c0d6e4',
                              justify="center",
                              fg='green')
        self.lbl_date.place(x=770, y=35)

        return date, month, subuh_list, terbit_list, zuhur_list, ashar_list, maghrib_list, isya_list

    def convert_button(self):
        '''Membuat button / tombol konversi'''

        style = ttk.Style()
        style.configure('TButton',
                        font=self.fontstyle2,
                        bg='dark green',
                        width=10)
        btn_convert = ttk.Button(self.frame1,
                                 text='Hitung Waktu Sholat',
                                 style='TButton',
                                 width=20,
                                 command=self.take_value)
        btn_convert.place(x=60, y=160)

    def take_value(self):
        '''Perintah mengambil nilai'''

        print("Proccesing . . . .")
        date, month, subuh, terbit, zuhur, ashar, maghrib, isya = self.hitung_waktu_shalat(
        )
        tanggal = self.kalender.selection_get().day
        print("Finished. . . ")
        self.scr_jadwal.delete(1.0, END)
        x_tanggal = 3
        x_subuh = x_tanggal + 135
        x_terbit = x_subuh + 135
        x_zuhur = x_subuh + 135
        x_ashar = x_zuhur + 135
        x_maghrib = x_ashar + 135
        x_isya = x_maghrib + 135
        y_size = 30

        for i in range(0, date):
            if i + 1 < 10:
                self.scr_jadwal.state = NORMAL
                self.scr_jadwal.insert(
                    END,
                    '  0{} {}           \t{}         \t{}           \t{}          \t {}           \t  {}        \t  {}\n'
                    .format(i + 1, str(month[0]), subuh[i], terbit[i],
                            zuhur[i], ashar[i], maghrib[i], isya[i]))
                self.scr_jadwal.state = DISABLED
            else:
                self.scr_jadwal.state = NORMAL
                self.scr_jadwal.insert(
                    END,
                    '  {} {}           \t{}         \t{}           \t{}          \t {}           \t  {}        \t  {}\n'
                    .format(i + 1, str(month[0]), subuh[i], terbit[i],
                            zuhur[i], ashar[i], maghrib[i], isya[i]))
                self.scr_jadwal.state = DISABLED

            if tanggal == i + 1:
                lbl_subuh = Label(self.frame3,
                                  text=subuh[i],
                                  font=self.fontstyle3,
                                  bg='#c0d6e4',
                                  fg='green')
                lbl_terbit = Label(self.frame3,
                                   text=terbit[i],
                                   font=self.fontstyle3,
                                   bg='#c0d6e4',
                                   fg='green')
                lbl_zuhur = Label(self.frame3,
                                  text=zuhur[i],
                                  font=self.fontstyle3,
                                  bg='#c0d6e4',
                                  fg='green')
                lbl_ashar = Label(self.frame3,
                                  text=ashar[i],
                                  font=self.fontstyle3,
                                  bg='#c0d6e4',
                                  fg='green')
                lbl_maghrib = Label(self.frame3,
                                    text=maghrib[i],
                                    font=self.fontstyle3,
                                    bg='#c0d6e4',
                                    fg='green')
                lbl_isya = Label(self.frame3,
                                 text=isya[i],
                                 font=self.fontstyle3,
                                 bg='#c0d6e4',
                                 fg='green')

                lbl_subuh.place(x=820, y=140)
                lbl_terbit.place(x=820, y=180)
                lbl_zuhur.place(x=820, y=220)
                lbl_ashar.place(x=820, y=260)
                lbl_maghrib.place(x=820, y=300)
                lbl_isya.place(x=820, y=340)

    def frame_3(self):
        '''Frame - 3'''

        tahun = self.kalender.selection_get().year
        bulan = self.kalender.selection_get().month
        tanggal = self.kalender.selection_get().day

        date, month, subuh, terbit, zuhur, ashar, maghrib, isya = self.hitung_waktu_shalat(
        )

        lbl_index = Label(self.frame3,
                          text='',
                          bg='#23dd17',
                          font=self.fontstyle2,
                          width='87')
        lbl_index.place(x=3, y=3)
        indexx = [
            'TANGGAL', 'SUBUH', 'TERBIT', 'ZUHUR', 'ASHAR', ' MAGHRIB',
            '   ISYA'
        ]
        x_size = 3
        y_size = 3

        for i in range(0, len(indexx)):
            lbl_tanggal = Label(self.frame3,
                                text=indexx[i],
                                font=self.fontstyle2,
                                bg='#23dd17')
            lbl_tanggal.place(x=x_size, y=y_size)
            x_size = x_size + 100

        self.scr_jadwal = scrolledtext.ScrolledText(self.frame3,
                                                    width=85,
                                                    height=18,
                                                    bg='#c0d6e4',
                                                    font=self.fontstyle)
        self.scr_jadwal.place(x=5, y=30)

        lbl_jadwal = Label(self.frame3,
                           text='JADWAL SHALAT',
                           font=self.fontstyle3,
                           bg='#c0d6e4',
                           fg='black')
        lbl_jadwal.place(x=750, y=15)

        x_size2 = 730
        y_size2 = 140
        index = ['SUBUH', 'TERBIT', 'ZUHUR', 'ASHAR', 'MAGHRIB', 'ISYA']
        for i in range(0, len(index)):
            lbl_subuh = Label(self.frame3,
                              text=index[i],
                              font=self.fontstyle,
                              bg='#c0d6e4',
                              fg='black')
            lbl_subuh.place(x=x_size2, y=y_size2)
            y_size2 = y_size2 + 40

    def save_file(self):
        '''Command untuk menyimpan file dalam format .txt'''

        files = [('Text Document', '*.txt')]
        file = asksaveasfile(mode='w', filetypes=files, defaultextension=files)

        if file is None:  #Jika user menekan cancel
            return

        file_to_save3 = "  TANGGAL           \tSUBUH         \t\tTERBIT           \tZUHUR        \t\t ASHAR           \t  MAGHRIB        \t  ISYA\n"
        file_to_save4 = "------------------------------------------------------------------------------------------------------------------------------------------------------------\n"
        file.write(self.file_to_save1)
        file.write(self.file_to_save2)
        file.write(file_to_save4)
        file.write(file_to_save3)
        file.write(file_to_save4)
        file.write(self.scr_jadwal.get("1.0", 'end'))
        file.close()
예제 #22
0
class SchichtView(tk.Toplevel):
    def __init__(self, parent_view, asn_liste, adressliste):
        super().__init__(parent_view)

        # unterframes zur optisch-logischen Einteilung
        self.asn_frame = tk.Frame(self)
        self.datetime_frame = tk.Frame(self)
        self.template_frame = tk.Frame(self.asn_frame)
        self.add_options_frame = tk.Frame(self)
        self.add_options_checkbuttons_frame = tk.Frame(self.add_options_frame)
        self.save_buttons_frame = tk.Frame(self)

        self.asn_dropdown = Combobox(self.asn_frame,
                                     values=asn_liste,
                                     width=38,
                                     state="readonly")
        self.asn_dropdown.set(-1)
        self.selected_template = tk.IntVar()

        self.asn_stammdaten_form = AsnStammdatenView(
            parent_view=self.asn_frame)

        self.startdatum_input = Calendar(self.datetime_frame,
                                         date_pattern='MM/dd/yyyy')
        # day=day,
        # month=month,
        # year=year)
        self.startzeit_input = TimePicker(self.datetime_frame)
        self.endzeit_input = TimePicker(self.datetime_frame)
        self.startzeit_input.bind('<FocusOut>',
                                  self.nachtschicht_durch_uhrzeit)
        self.endzeit_input.bind('<FocusOut>', self.nachtschicht_durch_uhrzeit)

        self.enddatum_input = Calendar(self.datetime_frame,
                                       date_pattern='MM/dd/yyyy')
        # , day=day, month=month, year=year)

        self.abweichende_adresse_beginn = PostadresseView(
            self.add_options_frame)
        self.abweichende_adresse_ende = PostadresseView(self.add_options_frame)

        self.abweichende_adresse_beginn_dropdown = Combobox(
            self.add_options_frame,
            values=adressliste,
            width=38,
            state="readonly")
        self.abweichende_adresse_beginn_dropdown.set(-2)

        self.abweichende_adresse_ende_dropdown = Combobox(
            self.add_options_frame,
            values=adressliste,
            width=38,
            state="readonly")
        self.abweichende_adresse_ende_dropdown.set(-2)

        self.ist_at = tk.IntVar()
        self.ist_pcg = tk.IntVar()
        self.ist_rb = tk.IntVar()
        self.ist_afg = tk.IntVar()
        self.ist_at_button = tk.Checkbutton(
            self.add_options_checkbuttons_frame,
            text="AT",
            onvalue=1,
            offvalue=0,
            variable=self.ist_at)
        self.ist_pcg_button = tk.Checkbutton(
            self.add_options_checkbuttons_frame,
            text="PCG",
            onvalue=1,
            offvalue=0,
            variable=self.ist_pcg)
        self.ist_rb_button = tk.Checkbutton(
            self.add_options_checkbuttons_frame,
            text="Kurzfristig (RB/BSD)",
            onvalue=1,
            offvalue=0,
            variable=self.ist_rb)
        self.ist_afg_button = tk.Checkbutton(
            self.add_options_checkbuttons_frame,
            text="Ausfallgeld",
            onvalue=1,
            offvalue=0,
            variable=self.ist_afg)

        # formbuttons
        self.save_button = tk.Button(self.save_buttons_frame,
                                     text="Daten speichern")
        self.exit_button = tk.Button(self.save_buttons_frame, text="Abbrechen")
        # command=self.destroy)
        self.saveandnew_button = tk.Button(self.save_buttons_frame,
                                           text="Daten speichern und neu")
        # command=lambda: self.action_save_neue_schicht(undneu=1))

    def draw_templates(self, template_list):
        for child in self.template_frame.winfo_children():
            child.destroy()

        if not template_list:
            self.add_template_text()
        else:
            for template in template_list:
                text = template.bezeichner
                text += " von " + template.beginn.strftime('%H:%M') \
                        + " bis " + template.ende.strftime('%H:%M')
                button = tk.Radiobutton(
                    self.template_frame,
                    text=text,
                    variable=self.selected_template,
                    value=template.id,
                    command=lambda: self.change_template(template_list))
                button.pack()

    def nachtschicht_durch_uhrzeit(self, event=None):
        start = time(hour=int(self.startzeit_input.hourstr.get()),
                     minute=int(self.startzeit_input.minstr.get()))
        ende = time(hour=int(self.endzeit_input.hourstr.get()),
                    minute=int(self.endzeit_input.minstr.get()))

        beginn = self.startdatum_input.selection_get()

        if ende < start:
            enddatum = beginn + timedelta(days=1)
        else:
            enddatum = beginn

        self.enddatum_input.selection_set(enddatum)

    def change_template(self, template_list):
        template_id = self.selected_template.get()
        for template in template_list:
            if template_id == template.id:
                self.startzeit_input.hourstr.set(
                    template.beginn.strftime('%H'))
                self.startzeit_input.minstr.set(template.beginn.strftime('%M'))
                self.endzeit_input.hourstr.set(template.ende.strftime('%H'))
                self.endzeit_input.minstr.set(template.ende.strftime('%M'))
                self.nachtschicht_durch_uhrzeit()
                break

    def draw(self):

        # positionierung der Unterframes
        self.asn_frame.grid(row=0, column=0, sticky=tk.NW)
        self.datetime_frame.grid(row=0, column=1, sticky=tk.NW)
        self.template_frame.grid(row=1, column=0, sticky=tk.NW, columnspan=4)
        self.add_options_frame.grid(row=2,
                                    column=0,
                                    columnspan=2,
                                    sticky=tk.NW)
        self.add_options_checkbuttons_frame.grid(row=3,
                                                 column=0,
                                                 columnspan=2,
                                                 sticky=tk.NW)
        self.save_buttons_frame.grid(row=3,
                                     column=0,
                                     columnspan=2,
                                     sticky=tk.NE)

        # asn-frame
        asn_label = tk.Label(self.asn_frame, text='ASN auswählen')
        asn_label.grid(row=0, column=0, sticky=tk.NW)
        self.asn_dropdown.grid(row=0, column=1, sticky=tk.NE)
        self.asn_stammdaten_form.grid(row=1,
                                      column=0,
                                      columnspan=2,
                                      sticky=tk.NW)

        # datetime-frame
        startdatum_label = tk.Label(self.datetime_frame, text='Beginn')
        startdatum_label.grid(row=0, column=0, sticky=tk.NW)
        self.startdatum_input.grid(row=1, column=0, sticky=tk.NW, columnspan=2)
        self.startzeit_input.grid(row=0, column=1, sticky=tk.NW)

        enddatum_label = tk.Label(self.datetime_frame, text='Ende')
        enddatum_label.grid(row=0, column=2, sticky=tk.NW)
        self.enddatum_input.grid(row=1, column=2, sticky=tk.NW, columnspan=2)
        self.endzeit_input.grid(row=0, column=3, sticky=tk.NW)

        # add-options-frame
        abweichende_adresse_beginn_label = tk.Label(
            self.add_options_frame, text="Adresse zu beginn der Schicht?")
        abweichende_adresse_ende_label = tk.Label(
            self.add_options_frame, text="Adresse zum Ende der Schicht?")
        abweichende_adresse_beginn_label.grid(row=0, column=0, sticky=tk.NW)
        self.abweichende_adresse_beginn_dropdown.grid(row=1,
                                                      column=0,
                                                      sticky=tk.NE)
        self.abweichende_adresse_beginn.grid(row=2, column=0, sticky=tk.NW)
        abweichende_adresse_ende_label.grid(row=0, column=1, sticky=tk.NW)
        self.abweichende_adresse_ende_dropdown.grid(row=1,
                                                    column=1,
                                                    sticky=tk.NE)
        self.abweichende_adresse_ende.grid(row=2, column=1, sticky=tk.NW)

        self.ist_at_button.grid(row=0, column=0, sticky=tk.NW)
        self.ist_pcg_button.grid(row=0, column=1, sticky=tk.NW)
        self.ist_rb_button.grid(row=0, column=2, sticky=tk.NW)
        self.ist_afg_button.grid(row=0, column=3, sticky=tk.NW)

        # save-button-frame
        self.save_button.grid(row=0, column=0)
        self.exit_button.grid(row=0, column=1)
        self.saveandnew_button.grid(row=0, column=2)

    @staticmethod
    def hide(frame: tk.Frame):
        frame.grid_remove()

    @staticmethod
    def show(frame: tk.Frame):
        frame.grid()

    def add_template_text(self):
        # template-frame
        template_text = tk.Label(
            self.template_frame,
            justify="left",
            text='Wenn der Assistent "Schicht-Vorlagen" hat,\n'
            'stehen diese hier zur Auswahl.\n\n'
            'Das ist absolut anzuraten, da es das Eintragen\n'
            'von Schichten deutlich beschleunigt. \n\n'
            'Die Möglichkeit dazu findest Du im Hauptfenster unter: \n'
            'Bearbeiten -> ASN bearbeiten')
        template_text.pack()

    def set_data(self, **kwargs):
        """
        parst alle daten ins Formular

        :param kwargs:
        :return:
        """
        if 'asn' in kwargs.keys():
            self.asn_dropdown.set(kwargs['asn'])
        if 'asn_stammdaten' in kwargs.keys():
            self.asn_stammdaten_form.set_data(**kwargs['asn_stammdaten'])
        if 'beginn' in kwargs.keys():
            self.startdatum_input.selection_set(date=kwargs['beginn'])
            self.startzeit_input.hourstr.set(kwargs['beginn'].strftime('%H'))
            self.startzeit_input.minstr.set(kwargs['beginn'].strftime('%M'))
        if 'ende' in kwargs.keys():
            self.enddatum_input.selection_set(date=kwargs['ende'])
            self.endzeit_input.hourstr.set(kwargs['ende'].strftime('%H'))
            self.endzeit_input.minstr.set(kwargs['ende'].strftime('%M'))

        self.ist_at.set(
            1 if 'ist_at' in kwargs.keys() and kwargs['ist_at'] else 0)
        self.ist_pcg.set(
            1 if 'ist_pcg' in kwargs.keys() and kwargs['ist_pcg'] else 0)
        self.ist_rb.set(
            1 if 'ist_rb' in kwargs.keys() and kwargs['ist_rb'] else 0)
        self.ist_afg.set(
            1 if 'ist_afg' in kwargs.keys() and kwargs['ist_afg'] else 0)

        # TODO Zurücksetzen bei Change ASN
        if 'abweichende_adresse_beginn' in kwargs.keys():
            if kwargs['abweichende_adresse_beginn']:
                self.abweichende_adresse_beginn_dropdown.set(
                    kwargs['abweichende_adresse_beginn'])

        if 'abweichende_adresse_ende' in kwargs.keys():
            if kwargs['abweichende_adresse_ende']:
                self.abweichende_adresse_ende_dropdown.set(
                    kwargs['abweichende_adresse_ende'])

    def get_data(self):

        return {
            'asn_id':
            self.asn_dropdown.get(),
            'asn_stammdaten':
            self.asn_stammdaten_form.get_data(),
            'startdatum':
            self.startdatum_input.get_date(),
            'startzeit_stunde':
            self.startzeit_input.hourstr.get(),
            'startzeit_minute':
            self.startzeit_input.minstr.get(),
            'enddatum':
            self.enddatum_input.get_date(),
            'endzeit_stunde':
            self.endzeit_input.hourstr.get(),
            'endzeit_minute':
            self.endzeit_input.minstr.get(),
            'abweichende_adresse_beginn':
            self.abweichende_adresse_beginn_dropdown.get(),
            'abweichende_adresse_beginn_data':
            self.abweichende_adresse_beginn.get_data(),
            'abweichende_adresse_ende':
            self.abweichende_adresse_ende_dropdown.get(),
            'abweichende_adresse_ende_data':
            self.abweichende_adresse_ende.get_data(),
            'ist at':
            self.ist_at.get(),
            'ist pcg':
            self.ist_pcg.get(),
            'ist rb':
            self.ist_rb.get(),
            'ist afg':
            self.ist_afg.get()
        }
예제 #23
0
class HeaderView:
    def __init__(self, parent):
        self.__container = parent
        self.__width = int(parent.winfo_screenwidth())
        self.__height = int((parent.winfo_screenheight() / 6))
        self.__actual_date = dt.datetime.today().strftime(
            "%Y-%m-%d")  # AKTUALNA DATA

    @property
    def width(self):
        return self.__width

    @property
    def height(self):
        return self.__height

    @property
    def actual_date(self):
        return self.__actual_date

    def setup(self):
        """
        Metoda tworząca widok.
        """
        self.create_widgets()
        self.setup_layout()

    def create_widgets(self):
        """
        Metoda zawiera inicjalizację komponentów widoku.
        """
        self.__main_frame = tk.Frame(self.__container,
                                     width=self.width,
                                     height=self.height,
                                     bg=colors.main_background_color)
        self.__header_label = tk.Label(self.__main_frame,
                                       text="YOUR COSMIC DAY: ",
                                       font=("Courier", 30),
                                       background=colors.main_background_color,
                                       foreground=colors.main_font_color)

        datetime_obj = dt.datetime.strptime(self.__actual_date, "%Y-%m-%d")
        self.__header_date = tk.Label(
            self.__main_frame,
            text=datetime_obj.strftime('%a %d. of %B %Y'),
            font=("Courier", 30),
            background=colors.main_background_color,
            foreground=colors.main_font_color)
        self.__pick_date_button = tk.Button(
            self.__main_frame,
            width=15,
            height=2,
            text="PICK DAY",
            command=self.change_date_window_open,
            font=("Courier", 15),
            bg=colors.button_color,
            fg=colors.button_font_color)

        self.__img_logo_nasa = tk.Label(
            self.__main_frame, background=colors.main_background_color)

    def setup_layout(self):
        """
        Metoda rozmieszcza komponenty widoku.
        """
        self.load_nasa_logo()
        self.__main_frame.pack(side=tk.LEFT)
        self.__main_frame.pack_propagate(0)
        self.__header_label.pack(side=tk.LEFT)
        self.__header_label.pack_propagate(0)
        self.__header_date.pack(side=tk.LEFT)
        self.__header_date.pack_propagate(0)
        self.__pick_date_button.pack(side=tk.RIGHT,
                                     padx=10,
                                     pady=10,
                                     ipadx=10,
                                     ipady=10)

    def change_date_window_open(self):
        """
        Metoda tworzy i otwiera okno wybierania daty z kalendarzem. Wykonywana jest w momencie użycia przycisku
        pick date w nagłówku.
        """
        today = dt.date.today()
        self.__pick_date_window = tk.Toplevel(
            background=colors.main_background_color)
        self.__calendar = Calendar(self.__pick_date_window,
                                   font="Arial 14",
                                   maxdate=today,
                                   selectmode='day',
                                   cursor="hand1",
                                   year=int(today.year),
                                   month=int(today.month),
                                   day=int(today.day))
        accept_date = tk.Button(self.__pick_date_window,
                                text="Accept",
                                command=self.accept_changed_date,
                                bg=colors.button_color,
                                fg=colors.button_font_color,
                                width=30)
        self.__calendar.pack(fill="both", expand=True)
        accept_date.pack()

    def accept_changed_date(self):
        """
        Metoda jest wywoływana w przypadku użycia przycisku Accept w oknie wyboru daty. Zmienia aktualną datę w widoku
        oraz wysyła do kontrolera informację o zmianie daty.
        """
        self.__actual_date = str(self.__calendar.selection_get())
        datetime_obj = dt.datetime.strptime(self.__actual_date, "%Y-%m-%d")
        self.__header_date.config(
            text=datetime_obj.strftime('%a %d. of %B %Y'))
        self.__pick_date_window.destroy()
        pub.sendMessage("picked_date", data=self.__actual_date)

    def load_nasa_logo(self):
        """
        Metoda wczytuje zdjęcie logo nasa z pliku, i umieszcza go w nagłówku.
        """
        self.__img_logo_nasa.pack(side=tk.LEFT,
                                  padx=1,
                                  pady=1,
                                  ipady=1,
                                  ipadx=3)
        img = Image.open('nasa_logo.png')
        resized_img = img.resize((140, 125), Image.ANTIALIAS)
        img_tk = ImageTk.PhotoImage(resized_img)
        self.__img_logo_nasa.image = img_tk
        self.__img_logo_nasa.config(image=img_tk, width=140, height=125)
class Aplicacion:
    

    def __init__(self):
        self.raiz = Tk()
        self.raiz.title ("Mantenimiento de Administración")
        self.raiz.geometry('900x600') 
        menubar = Menu(self.raiz)
        self.raiz.config(menu=menubar)
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Acerca de..")
        filemenu.add_separator()
        filemenu.add_command(label="Salir", command=self.raiz.quit)
        mantmenu = Menu(menubar, tearoff=0)
        mantmenu.add_command(label="Clientes", command=self.mostrar_mant_telefonos)
        mantmenu.add_command(label="Servidor")
        menubar.add_cascade(label="Archivo", menu=filemenu)
        menubar.add_cascade(label="Mantenimiento", menu=mantmenu)
        self.fuente = font.Font(weight="bold")
        self.persona = Persona.Persona() 
        self.insertando = True
        self.lb_tituloPantalla = Label(self.raiz, text = "MANTENIMIENTO DE ADMINISTRACIÓN", font = self.fuente)
        self.lb_tituloPantalla.place(x = 320, y = 20)
        self.lb_cedula = Label(self.raiz, text = "Cedula:")
        self.lb_cedula.place(x = 240, y = 60)
        self.txt_cedula = Entry(self.raiz, textvariable=self.persona.cedula, justify="right")
        self.txt_cedula.place(x = 370, y = 60)
        self.lb_nombre = Label(self.raiz, text = "Nombre:")
        self.lb_nombre.place(x = 240, y = 90)
        self.txt_nombre = Entry(self.raiz, textvariable=self.persona.nombre, justify="right", width=30)
        self.txt_nombre.place(x = 370, y = 90)
        self.lb_apellido1 = Label(self.raiz, text = "Primer apellido:")
        self.lb_apellido1.place(x = 240, y = 120)
        self.txt_apellido1 = Entry(self.raiz, textvariable=self.persona.apellido1, justify="right", width=30)
        self.txt_apellido1.place(x = 370, y = 120)
        self.lb_apellido2 = Label(self.raiz, text = "Segundo apellido:")
        self.lb_apellido2.place(x = 240, y = 150)
        self.txt_apellido2 = Entry(self.raiz, textvariable=self.persona.apellido2, justify="right", width=30)
        self.txt_apellido2.place(x = 370, y = 150)
        self.lb_fec_nacimiento = Label(self.raiz, text = "Fecha nacimiento:")
        self.lb_fec_nacimiento.place(x = 240, y = 180)
        self.txt_fechaNacimiento = Entry(self.raiz, textvariable=self.persona.fecNacimiento, justify="right", width=30, state="readonly")
        self.txt_fechaNacimiento.place(x = 370, y = 180)
        self.bt_mostrarCalendario = Button(self.raiz, text="...", width=3, command = self.mostrarDatePicker)
        self.bt_mostrarCalendario.place(x = 650, y = 180)
        self.lb_sexo = Label(self.raiz, text = "Sexo:")
        self.lb_sexo.place(x = 240, y = 210)
        self.radio_sexoM = Radiobutton(self.raiz, text="Masculino", variable=self.persona.sexo,   value=1)
        self.radio_sexoF = Radiobutton(self.raiz, text="Femenino", variable=self.persona.sexo,   value=2)
        self.radio_sexoM.place(x = 370, y = 210)
        self.radio_sexoF.place(x = 490, y = 210)
        self.persona.sexo.set(1)
        self.lb_observaciones = Label(self.raiz, text = "Observaciones:")
        self.lb_observaciones.place(x = 240, y = 250)
        self.txt_observaciones = Entry(self.raiz, textvariable=self.persona.observaciones, justify="right", width=30)
        self.txt_observaciones.place(x = 370, y = 250)
        self.bt_borrar = Button(self.raiz, text="Limpiar", width=15, command = self.limpiarInformacion)
        self.bt_borrar.place(x = 370, y = 310)
        self.bt_enviar = Button(self.raiz, text="Enviar", width=15, command = self.enviarInformacion)
        self.bt_enviar.place(x = 510, y = 310)
        self.bt_modificar = Button(self.raiz, text="Modificar", width=15, command = self.enviarInformacion)
        self.bt_modificar.place(x = 650, y = 310)
        self.lb_tituloPantalla = Label(self.raiz, text = "INFORMACIÓN INCLUIDA", font = self.fuente)
        self.lb_tituloPantalla.place(x = 350, y = 355)
        self.lb_bloquear=Button(self.raiz,text="Bloquear",width=15,command=self.bloquear)
        self.lb_bloquear.place(x=650,y=330)
        self.desbloquear=Button(self.raiz,text="Desbloquear",width=15,command=self.desbloquear)
        self.lb_desbloquear.place(x=650,y=340)
        self.lb_iniciar_tiempo=Button(self.raiz,text="Iniciar tiempo",width=15,command=self.iniciar_tiempo)
        self.lb_iniciar_tiempo.place(x=650,y=350)
        self.lb_detener_tiempo=Button(self.raiz,text="Detener tiempo",width=15,command=self.detener_tiempo)
        self.lb_bloquear.place(x=650,y=360)
        self.lb_enviar_mensaje=Button(self.raiz,text="Enviar",width=15,command=self.enviarInformacion)
        self.lb_enviar_mensaje.place(x=650,y=370)
        self.sheet = Sheet(self.raiz,
                            page_up_down_select_row = True,
                            column_width = 120,
                            startup_select = (0,1,"rows"),
                            headers = ['Cédula', 'Nombre', 'Primer Ape.', 'Segundo Ape.', 'Fec. Nacimiento', 'Sexo'],
                            height = 195, 
                            width = 720 
                            )
        
        self.sheet.enable_bindings(("single_select", 
                                    "column_select",
                                    "row_select",
                                    "column_width_resize",
                                    "double_click_column_resize",
                                    #"row_width_resize",
                                    #"column_height_resize",
                                    "arrowkeys",
                                    "row_height_resize",
                                    "double_click_row_resize",
                                    "right_click_popup_menu",
                                    "rc_select",
                                    "rc_insert_column",
                                    "rc_delete_column",
                                    "rc_insert_row",
                                    "rc_delete_row"))
        self.sheet.place(x = 20, y = 390)
        self.bt_cargar = Button(self.raiz, text="Cargar", width=15, command = self.cargarInformacion)
        self.bt_cargar.place(x = 750, y = 385)
        self.bt_eliminar = Button(self.raiz, text="Eliminar", width=15, command = self.eliminarInformacion)
        self.bt_eliminar.place(x = 750, y = 425)
        self.cargarTodaInformacion()
        self.raiz.mainloop()
    def mostrar_mant_telefonos(self):
        mant_telefonos.MantTelefonos(self.raiz)
    def cargarTodaInformacion(self):
        try:
            self.personaBo = PersonoBO.PersonaBO() 
            resultado = self.personaBo.consultar()

            self.sheet.set_sheet_data(resultado)
        except Exception as e: 
            msg.showerror("Error",  str(e))
    def cargarInformacion(self):
        try:
            datoSeleccionado = self.sheet.get_currently_selected()
            cedula = (self.sheet.get_cell_data(datoSeleccionado[0],0))
            self.persona.cedula.set(cedula)
            self.personaBo = PersonoBO.PersonaBO() 
            self.personaBo.consultarPersona(self.persona) 
            self.insertando = False
            msg.showinfo("Acción: Consultar persona", "La información de la persona ha sido consultada correctamente")
        except Exception as e: 
            msg.showerror("Error",  str(e))
    def eliminarInformacion(self):
        try:
            datoSeleccionado = self.sheet.get_currently_selected()
            cedula = (self.sheet.get_cell_data(datoSeleccionado[0],0))
            nombre = (self.sheet.get_cell_data(datoSeleccionado[0],1))
            resultado = msg.askquestion("Eliminar",  "¿Desear eliminar a "+nombre+" de la base de datos?")
            if resultado == "yes":
                self.persona.cedula.set(cedula)
                self.personaBo = PersonoBO.PersonaBO()
                self.personaBo.eliminar(self.persona) 
                self.cargarTodaInformacion()
                self.persona.limpiar()
        except Exception as e: 
            msg.showerror("Error",  str(e))
    def printTxt(self, texto):
        print(texto)
    def enviarInformacion(self):
        try:
            self.personaBo = PersonoBO.PersonaBO() 
            if(self.insertando == True):
                self.personaBo.guardar(self.persona)
            else:
                self.personaBo.modificar(self.persona)
            self.cargarTodaInformacion()
            self.persona.limpiar() 
            if(self.insertando == True):
                msg.showinfo("Acción: Agregar persona", "La información de la persona ha sido incluida correctamente")
            else:
                msg.showinfo("Acción: Agregar modificar", "La información de la persona ha sido modificada correctamente") 
            self.insertando = True
        except Exception as e: 
            msg.showerror("Error",  str(e))
    def limpiarInformacion(self):
        self.persona.limpiar() 
        self.insertando = True
        msg.showinfo("Acción del sistema", "La información del formulario ha sido eliminada correctamente")
    def mostrarDatePicker(self):
        self.top = Toplevel(self.raiz)
        self.cal = Calendar(self.top, font="Arial 14", selectmode='day', locale='en_US',
                   cursor="hand", year=2019, month=6, day=16)
        self.cal.pack(fill="both", expand=True)
        ttk.Button(self.top, text="Seleccionar", command = self.seleccionarFecha).pack()
    def seleccionarFecha(self):
        self.persona.fecNacimiento.set(self.cal.selection_get())
예제 #25
0
class Alarm:
    """ class that displays an alarm widget """
    def __init__(self, root, engine):
        """ 
            construct an alarm widget with the parent root 
        
            Args:
                root: tk.Tk()
                engine: pyttsx3.engine
            
            Returns:
                None
        
        """
        #speech engine
        self.engine = engine

        #values for time
        self.values = ["AM", "PM"]

        #main root window
        self.root = root
        self.root.title("Signteract Alarm")
        self.root.config(bg="azure")

        #title label
        self.title = Label(self.root, text="Set an Alarm")
        self.title.config(font=("Comic Sans MS Bold Italic", 15), bg="azure")

        #calendar title
        self.cal_title = Label(self.root, text="Set the date")
        self.cal_title.config(font=("Comic Sans MS Bold Italic", 12),
                              bg="azure")

        #calendar frame
        self.cal_frame = Frame(self.root)
        self.cal_frame.configure(bg="azure")

        #calendar
        self.cal = Calendar(self.cal_frame,
                            font="Arial 14",
                            selectmode='day',
                            cursor="hand1",
                            year=2020,
                            month=12,
                            day=19)

        #time title
        self.time_title = Label(self.root, text="Set the time")
        self.time_title.config(font=("Comic Sans MS Bold Italic", 12),
                               bg="azure")

        #time frame
        self.time_frame = Frame(self.root)
        self.time_frame.configure(bg="azure")

        #time labels
        self.hr_label = Label(self.time_frame, text="Hours")
        self.min_label = Label(self.time_frame, text="Minutes")
        self.hr_label.config(font=("Comic Sans MS Italic", 10), bg="azure")
        self.min_label.config(font=("Comic Sans MS Italic", 10), bg="azure")

        #time strings
        self.min_str = tk.StringVar(self.time_frame, '30')
        self.hr_str = tk.StringVar(self.time_frame, '2')
        self.ampm_str = tk.StringVar(self.time_frame, 'AM')

        #time spinbox
        self.hr_spbox = tk.Spinbox(self.time_frame, from_=0, to=12, wrap = True,\
                                   textvariable=self.hr_str, width=5, state="readonly")
        self.min_spbox = tk.Spinbox(self.time_frame, from_=0, to=59, wrap = True, \
                                    textvariable=self.min_str, width=5, state="readonly")
        self.ampm_spbox = tk.Spinbox(self.time_frame, values=self.values, wrap = True, \
                                     textvariable=self.ampm_str, width=5, state="readonly")

        self.hr_spbox.config(font=("Comic Sans MS Bold Italic", 10))
        self.min_spbox.config(font=("Comic Sans MS Bold Italic", 10))
        self.ampm_spbox.config(font=("Comic Sans MS Bold Italic", 10))

        #set alarm button
        self.btn = Button(self.time_frame,
                          text="SET ALARM",
                          command=self.get_alarm_time)

        #building the UI
        self.title.pack(expand=True)
        self.cal_title.pack(expand=True)
        self.cal_frame.pack(expand=True)
        self.time_title.pack(expand=True)
        self.time_frame.pack(expand=True)

        #building the calendar frame
        self.cal.pack(expand=True)

        #building the time frame
        self.hr_label.grid(row=2, column=1, sticky=E, pady=2)
        self.min_label.grid(row=2, column=2, sticky=E, pady=2)
        self.hr_spbox.grid(row=3, column=1, sticky=E, pady=2, padx=5)
        self.min_spbox.grid(row=3, column=2, sticky=E, pady=2, padx=5)
        self.ampm_spbox.grid(row=3, column=3, sticky=E, pady=2, padx=5)

        #adding the button
        self.btn.grid(row=5, column=1, columnspan=2, sticky=E, pady=2)

    def get_alarm_time(self):
        """ gets the alarm time from the widget and converts it to speech """

        #getting the values from the UI
        mins = self.min_str.get()
        hrs = self.hr_str.get()
        date = self.cal.selection_get()
        ampm = self.ampm_str.get()

        #getting the date and month
        month = date.strftime("%B")
        date = date.strftime("%d")

        #construction of the command
        command = "Set an alarm on " + date + month + " at " + hrs + " " + mins + " " + ampm

        #saying the command
        self.engine.say("Alexa")
        self.engine.runAndWait()
        self.engine.say(command)
        self.engine.runAndWait()

        #destroying the window
        self.root.destroy()
        LaunchWindow(tk.Tk(), self.engine)
예제 #26
0
    def test_calendar_selection(self):
        widget = Calendar(self.window,
                          month=3,
                          year=2011,
                          day=10,
                          maxdate=date(2013, 1, 1),
                          mindate=date(2010, 1, 1))
        widget.pack()
        self.assertEqual(widget.selection_get(), date(2011, 3, 10))

        widget.selection_set(date(2012, 4, 11))
        self.assertEqual(widget.selection_get(), date(2012, 4, 11))
        self.assertEqual(widget._date, date(2012, 4, 1))
        widget.selection_set(datetime(2012, 5, 11))
        self.assertEqual(widget.selection_get(), date(2012, 5, 11))
        self.assertNotIsInstance(widget.selection_get(), datetime)
        self.assertIsInstance(widget.selection_get(), date)
        widget.selection_set(datetime(2012, 5, 21).strftime('%x'))
        self.assertEqual(widget.selection_get(), date(2012, 5, 21))
        self.assertNotIsInstance(widget.selection_get(), datetime)
        self.assertIsInstance(widget.selection_get(), date)

        widget.selection_set(date(2018, 4, 11))
        self.assertEqual(widget.selection_get(), date(2013, 1, 1))
        widget.selection_set(date(2001, 4, 11))
        self.assertEqual(widget.selection_get(), date(2010, 1, 1))
        widget.selection_clear()
        self.assertIsNone(widget.selection_get())
        # test Swedish locale
        widget.destroy()
        widget = Calendar(self.window, locale='sv_SE')
        widget.pack()
        widget.selection_set(format_date(date(2012, 4, 11), 'short', 'sv_SE'))
예제 #27
0
    def test_calendar_init(self):
        widget = Calendar(self.window)
        widget.pack()
        self.window.update()
        widget.destroy()
        widget = Calendar(self.window, showweeknumbers=False)
        self.window.update()
        widget.destroy()
        today = format_date(date.today(), 'short')
        var = tk.StringVar(self.window, today)
        widget = Calendar(self.window,
                          textvariable=var,
                          month=3,
                          year=2011,
                          day=10)
        self.window.update()
        self.assertEqual(var.get(), today)
        self.assertEqual(widget.selection_get(), date.today())
        widget.destroy()
        widget = Calendar(self.window,
                          font="Arial 14",
                          selectmode='day',
                          cursor="hand1",
                          year=2018,
                          month=2,
                          day=5)
        widget.pack()
        self.window.update()
        self.assertEqual(widget.selection_get(), date(2018, 2, 5))
        self.assertEqual(widget.get_displayed_month(), (2, 2018))
        w, d = widget._get_day_coords(date(2018, 2, 5))
        self.assertEqual(widget._calendar[w][d].cget('text'), '5')
        widget.destroy()

        widget = Calendar(self.window, year=2011, month=2, day=35)
        widget.pack()
        self.window.update()
        self.assertIsNone(widget.selection_get())
        self.assertEqual(widget._date, date(2011, 2, 1))
        widget.destroy()

        with self.assertRaises(ValueError):
            widget = Calendar(self.window, month=23)
            widget.pack()
            self.window.update()
            widget.destroy()

        with self.assertRaises(ValueError):
            widget = Calendar(self.window, borderwidth="e")
            widget.pack()
            self.window.update()
            widget.destroy()

        with self.assertRaises(TypeError):
            widget = Calendar(self.window, weekenddays=7)
            widget.pack()
            self.window.update()
            widget.destroy()

        with self.assertRaises(ValueError):
            widget = Calendar(self.window, weekenddays="e")
            widget.pack()
            self.window.update()
            widget.destroy()

        with self.assertRaises(ValueError):
            widget = Calendar(self.window, weekenddays=[1])
            widget.pack()
            self.window.update()
            widget.destroy()

        with self.assertRaises(ValueError):
            widget = Calendar(self.window, weekenddays=['a', 'b'])
            widget.pack()
            self.window.update()
            widget.destroy()

        with self.assertRaises(ValueError):
            widget = Calendar(self.window, weekenddays=[12, 3])
            widget.pack()
            self.window.update()
            widget.destroy()

        with self.assertRaises(TypeError):
            widget = Calendar(self.window, maxdate="e")
            widget.pack()
            self.window.update()
            widget.destroy()

        widget = Calendar(self.window,
                          mindate=datetime(2013, 5, 22, 10, 5),
                          maxdate=datetime.today())
        widget.pack()
        self.window.update()
        widget.destroy()

        with self.assertRaises(TypeError):
            widget = Calendar(self.window, mindate="e")
            widget.pack()
            self.window.update()
            widget.destroy()

        with self.assertRaises(ValueError):
            widget = Calendar(self.window,
                              mindate=date(2018, 4, 5),
                              maxdate=date(2018, 4, 4))
            widget.pack()
            self.window.update()
            widget.destroy()

        with self.assertRaises(ValueError):
            widget = Calendar(self.window, firstweekday="e")
            widget.pack()
            self.window.update()
            widget.destroy()

        widget = Calendar(self.window,
                          font="Arial 14",
                          selectmode='day',
                          cursor="hand1",
                          year=2018,
                          month=2,
                          day=5)
        widget.pack()
        self.window.update()
        widget.destroy()

        widget = Calendar(self.window,
                          selectmode='none',
                          year=2015,
                          month=1,
                          background="black",
                          foreground="white",
                          key="a")
        widget.pack()
        self.window.update()
        self.assertIsNone(widget.selection_get())
        self.assertEqual(widget._date, date(2015, 1, 1))
        widget.destroy()

        with self.assertRaises(ValueError):
            widget = Calendar(self.window, selectmode='wrong')
            widget.pack()
            self.window.update()
            widget.destroy()
               cursor="sizing",
               background="white",
               disabledbackground="white",
               bordercolor="pink",
               headersbackground="bisque2",
               normalbackground="black",
               foreground="bisque4",
               normalforeground="bisque4",
               headersforeground="bisque4")

cal.config(background="black")
cal.grid(row=0, column=0, sticky="N", rowspan=9)
cal.bind("<<CalendarSelected>>", ListTodo)

#Variable Global
tanggal = str(cal.selection_get())

#Style
style = ttk.Style()
style.configure("Treeview", background="bisque4", foreground="bisque4")

treev = ttk.Treeview(root)
treev.grid(row=0, column=1, sticky="WNE", rowspan=4, columnspan=2)

#Scrollbar Settings
scrollBar = tk.Scrollbar(root, orient="vertical", command=treev.yview)
scrollBar.grid(row=0, column=3, sticky="ENS", rowspan=4)
treev.configure(yscrollcommand=scrollBar.set)
treev.bind("<Double-1>", DetailTodo)

#Time and Title Setting
예제 #29
0
class Directorio_C:
    def __init__(self):

        #Pantalla
        self.raiz = Tk()
        self.raiz.title("Mantenimiento de Clientes")
        self.raiz.geometry('600x630')

        #Barra menu
        menubar = Menu(self.raiz)
        self.raiz.config(menu=menubar)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Salir", command=self.raiz.quit)

        mantmenu = Menu(menubar, tearoff=0)
        mantmenu.add_command(label="Facturas", command=self.abrir_F)
        mantmenu.add_command(label="Articulos", command=self.abrir_A)
        mantmenu.add_command(label="Proveedores", command=self.abrir_p)
        mantmenu.add_command(label="Conexion", command=self.abrir_R)

        menubar.add_cascade(label="Archivo", menu=filemenu)
        menubar.add_cascade(label="Mantenimiento", menu=mantmenu)

        #Objecto cliente
        self.fuente = font.Font(weight="bold")
        self.cliente = Cliente.Cliente()
        self.insertando = True

        #Titulo
        self.lb_tituloPantalla = Label(self.raiz,
                                       text="MANTENIMIENTO DE CLIENTES",
                                       font=self.fuente)
        self.lb_tituloPantalla.place(x=180, y=20)

        #Formulario

        #Cedula
        self.lb_cedula = Label(self.raiz, text="Cedula:")
        self.lb_cedula.place(x=100, y=60)
        self.txt_cedula = Entry(self.raiz,
                                textvariable=self.cliente.PK_CEDULA,
                                justify="right")
        self.txt_cedula.place(x=230, y=60)

        #Nombre
        self.lb_nombre = Label(self.raiz, text="Nombre:")
        self.lb_nombre.place(x=100, y=90)
        self.txt_nombre = Entry(self.raiz,
                                textvariable=self.cliente.NOMBRE_C,
                                justify="right",
                                width=30)
        self.txt_nombre.place(x=230, y=90)

        #Apellido 1
        self.lb_apellido1 = Label(self.raiz, text="Primer apellido:")
        self.lb_apellido1.place(x=100, y=120)
        self.txt_apellido1 = Entry(self.raiz,
                                   textvariable=self.cliente.APELLIDO_1,
                                   justify="right",
                                   width=30)
        self.txt_apellido1.place(x=230, y=120)

        #Apellido 2
        self.lb_apellido2 = Label(self.raiz, text="Segundo apellido:")
        self.lb_apellido2.place(x=100, y=150)
        self.txt_apellido2 = Entry(self.raiz,
                                   textvariable=self.cliente.APELLIDO_2,
                                   justify="right",
                                   width=30)
        self.txt_apellido2.place(x=230, y=150)

        #Fecha nacimiento
        self.lb_fec_nacimiento = Label(self.raiz, text="Fecha nacimiento:")
        self.lb_fec_nacimiento.place(x=100, y=180)
        self.txt_fechaNacimiento = Entry(
            self.raiz,
            textvariable=self.cliente.FECHA_NACIMIENTO,
            justify="right",
            width=30,
            state="readonly")
        self.txt_fechaNacimiento.place(x=230, y=180)
        self.bt_mostrarCalendario = Button(self.raiz,
                                           text="...",
                                           width=3,
                                           command=self.mostrarDatePicker)
        self.bt_mostrarCalendario.place(x=510, y=180)

        #Direccion
        self.lb_direccion = Label(self.raiz, text="Direccion:")
        self.lb_direccion.place(x=100, y=210)
        self.txt_direccion = Entry(self.raiz,
                                   textvariable=self.cliente.DIRECCION,
                                   justify="right",
                                   width=30)
        self.txt_direccion.place(x=230, y=210)

        #Observaciones
        self.lb_observaciones = Label(self.raiz, text="Observaciones:")
        self.lb_observaciones.place(x=100, y=240)
        self.txt_observaciones = Entry(self.raiz,
                                       textvariable=self.cliente.OBSERVACIONES,
                                       justify="right",
                                       width=30)
        self.txt_observaciones.place(x=230, y=240)

        #Telefono 1
        self.lb_telefono_1 = Label(self.raiz, text="Telefono Principal:")
        self.lb_telefono_1.place(x=100, y=270)
        self.txt_telefono_1 = Entry(self.raiz,
                                    textvariable=self.cliente.TELEFONO_1,
                                    justify="right",
                                    width=30)
        self.txt_telefono_1.place(x=230, y=270)

        #Telefono 2
        self.lb_telefono_2 = Label(self.raiz, text="Telefono segundario:")
        self.lb_telefono_2.place(x=100, y=300)
        self.txt_telefono_2 = Entry(self.raiz,
                                    textvariable=self.cliente.TELEFONO_2,
                                    justify="right",
                                    width=30)
        self.txt_telefono_2.place(x=230, y=300)

        #Boton Limpiar
        self.bt_borrar = Button(self.raiz,
                                text="Limpiar",
                                width=15,
                                command=self.limpiarInformacion)
        self.bt_borrar.place(x=70, y=340)

        #Boton Enviar
        self.bt_enviar = Button(self.raiz,
                                text="Enviar",
                                width=15,
                                command=self.enviarInformacion)
        self.bt_enviar.place(x=190, y=340)

        #Boton Cargar
        self.bt_borrar = Button(self.raiz,
                                text="Cargar",
                                width=15,
                                command=self.cargarInformacion)
        self.bt_borrar.place(x=310, y=340)

        #Boton Eliminar
        self.bt_enviar = Button(self.raiz,
                                text="Eliminar",
                                width=15,
                                command=self.eliminarInformacion)
        self.bt_enviar.place(x=430, y=340)

        self.bt_reporte = Button(self.raiz,
                                 text="Reporte",
                                 width=15,
                                 command=self.generarPDFListado)
        self.bt_reporte.place(x=550, y=340)

        #label del informacion
        self.lb_tituloPantalla = Label(self.raiz,
                                       text="INFORMACIÓN INCLUIDA",
                                       font=self.fuente)
        self.lb_tituloPantalla.place(x=190, y=400)

        #cuadro excel
        self.sheet = Sheet(self.raiz,
                           page_up_down_select_row=True,
                           column_width=120,
                           startup_select=(0, 1, "rows"),
                           headers=[
                               'Cédula', 'Nombre', 'Primer Ape.',
                               'Segundo Ape.', 'Fec. Nacimiento', 'Direccion',
                               'Observaciones', 'Telefono 1', 'Telefono 2'
                           ],
                           height=170,
                           width=560)

        self.sheet.enable_bindings(
            ("single_select", "column_select", "row_select",
             "column_width_resize", "double_click_column_resize", "arrowkeys",
             "row_height_resize", "double_click_row_resize",
             "right_click_popup_menu", "rc_select", "rc_insert_column",
             "rc_delete_column", "rc_insert_row", "rc_delete_row"))

        self.sheet.place(x=20, y=440)

        #toda informacion
        self.cargarTodaInformacion()

        #cierre de raiz
        self.raiz.mainloop()

    def generarPDFListado(self):
        try:
            #Crea un objeto para la creación del PDF
            nombreArchivo = "ListadoPersonas.pdf"
            rep = reportPDF.Canvas(nombreArchivo)

            #Agrega el tipo de fuente Arial
            registerFont(TTFont('Arial', 'ARIAL.ttf'))

            #Crea el texto en donde se incluye la información
            textobject = rep.beginText()
            # Coloca el titulo
            textobject.setFont('Arial', 16)
            textobject.setTextOrigin(10, 800)
            textobject.setFillColor(colors.darkorange)
            textobject.textLine(text='LISTA DE CLIENTES')
            #Escribe el titulo en el reportes
            rep.drawText(textobject)

            #consultar la informacion de la base de datos
            self.clienteBo = ClienteBO.ClienteBO(
            )  #se crea un objeto de logica de negocio
            informacion = self.clienteBo.consultar()
            #agrega los titulos de la tabla en la información consultada
            titulos = [
                "Cédula", "Nombre", "Primer Ape.", "Segundo Ape.",
                "Fec. Nacimiento", "Direccion", "Observaciones", "Telefono 1",
                "Telefono 2"
            ]
            informacion.insert(0, titulos)
            #crea el objeto tabla  para mostrar la información
            t = Table(informacion)
            #Le coloca el color tanto al borde de la tabla como de las celdas
            t.setStyle(
                TableStyle([("BOX", (0, 0), (-1, -1), 0.25, colors.black),
                            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)
                            ]))

            #para cambiar el color de las fichas de hace un ciclo según la cantidad de datos
            #que devuelve la base de datos
            data_len = len(informacion)
            for each in range(data_len):
                if each % 2 == 0:
                    bg_color = colors.whitesmoke
                else:
                    bg_color = colors.lightgrey

                if each == 0:  #Le aplica un estilo diferente a la tabla
                    t.setStyle(
                        TableStyle([('BACKGROUND', (0, each), (-1, each),
                                     colors.orange)]))
                else:
                    t.setStyle(
                        TableStyle([('BACKGROUND', (0, each), (-1, each),
                                     bg_color)]))

            #acomoda la tabla según el espacio requerido
            aW = 840
            aH = 780
            w, h = t.wrap(aW, aH)
            t.drawOn(rep, 10, aH - h)

            #Guarda el archivo
            rep.save()
            #Abre el archivo desde comandos, puede variar en MacOs es open
            #subprocess.Popen("open '%s'" % nombreArchivo, shell=True)
            subprocess.Popen(nombreArchivo, shell=True)  #Windows
        except IOError:
            msg.showerror("Error", "El archivo ya se encuentra abierto")

    #calendario
    def mostrarDatePicker(self):
        #ventana segundaria
        self.top = Toplevel(self.raiz)
        self.cal = Calendar(self.top,
                            font="Arial 14",
                            selectmode='day',
                            locale='en_US',
                            cursor="hand1",
                            year=2019,
                            month=6,
                            day=16)
        self.cal.pack(fill="both", expand=True)
        ttk.Button(self.top, text="Seleccionar",
                   command=self.seleccionarFecha).pack()

    #Selecciona la fecha
    def seleccionarFecha(self):
        self.cliente.FECHA_NACIMIENTO.set(self.cal.selection_get())
        self.top.destroy()

    #Limpiar
    def limpiarInformacion(self):
        self.cliente.limpiar()
        msg.showinfo(
            "Acción del sistema",
            "La información del formulario ha sido eliminada correctamente")

    #envia la info
    def enviarInformacion(self):
        try:
            self.clienteBo = ClienteBO.ClienteBO()
            if (self.insertando == True):
                self.clienteBo.guardar(self.cliente)
            else:
                self.clienteBo.modificar(self.cliente)

            self.cargarTodaInformacion()
            self.insertando = True
            self.cliente.limpiar()

            if (self.insertando == True):
                msg.showinfo(
                    "Acción: Agregar cliente",
                    "La información del cliente ha sido incluida correctamente"
                )
            else:
                msg.showinfo(
                    "Acción: modificar cliente",
                    "La información del cliente ha sido modificada correctamente"
                )
        except Exception as e:
            msg.showerror("Error", str(e))

    #eliminar la info
    def eliminarInformacion(self):
        try:
            datoSeleccionado = self.sheet.get_currently_selected()
            cedula = (self.sheet.get_cell_data(datoSeleccionado[0], 0))
            nombre = (self.sheet.get_cell_data(datoSeleccionado[0], 1))

            resultado = msg.askquestion(
                "Eliminar",
                "¿Desear eliminar a " + nombre + " de la base de datos?")
            if resultado == "yes":
                self.cliente.PK_CEDULA.set(cedula)
                self.clienteBo = ClienteBO.ClienteBO()
                self.clienteBo.eliminar(self.cliente)
                self.cliente.limpiar()
        except Exception as e:
            msg.showerror("Error", str(e))

        self.cargarTodaInformacion(
        )  #refrescar la pagina especialmente para llaves foraneas relacionales

    #cargar toda la info
    def cargarTodaInformacion(self):
        try:
            self.clienteBo = ClienteBO.ClienteBO()
            resultado = self.clienteBo.consultar()

            self.sheet.set_sheet_data(resultado)
        except Exception as e:
            msg.showerror("Error", str(e))

    #selecionado
    def cargarInformacion(self):
        try:
            datoSeleccionado = self.sheet.get_currently_selected()
            cedula = (self.sheet.get_cell_data(datoSeleccionado[0], 0))
            self.cliente.PK_CEDULA.set(cedula)
            self.clienteBo = ClienteBO.ClienteBO()
            self.clienteBo.consultarCliente(self.cliente)
            self.insertando = False
            msg.showinfo(
                "Acción: Consultar cliente",
                "La información del cliente ha sido consultada correctamente")

        except Exception as e:
            msg.showerror("Error", str(e))

    #abrir
    def abrir_F(self):
        from mant_Factura import Directorio_F
        self.raiz.destroy()
        Directorio_F()

    def abrir_A(self):
        from mant_Articulos import Directorio_A
        self.raiz.destroy()
        Directorio_A()

    def abrir_p(self):
        from mant_Proveedor import Directorio_P
        self.raiz.destroy()
        Directorio_P()

    def abrir_R(self):
        from mant_RelacionAP import Conexion_AP
        self.raiz.destroy()
        Conexion_AP()
예제 #30
0
class Aplicacion:
    def __init__(self):
        #*************************************************************************
        #Crea un objeto TK
        #*************************************************************************
        self.raiz = Tk()
        self.raiz.title("Mantenimiento de Personas")
        self.raiz.geometry('900x600')

        #*************************************************************************
        #crea el menu de la pantalla
        #*************************************************************************
        menubar = Menu(self.raiz)
        self.raiz.config(menu=menubar)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Acerca de..")
        filemenu.add_separator()
        filemenu.add_command(label="Salir", command=self.raiz.quit)

        mantmenu = Menu(menubar, tearoff=0)
        mantmenu.add_command(label="Personas")
        mantmenu.add_command(label="Gustos")
        mantmenu.add_command(label="Amigos")

        menubar.add_cascade(label="Archivo", menu=filemenu)
        menubar.add_cascade(label="Mantenimiento", menu=mantmenu)

        #*************************************************************************
        #crea un objeto tipo fuenta
        #*************************************************************************
        self.fuente = font.Font(weight="bold")

        #*************************************************************************
        #se crean atributos de la clase
        #*************************************************************************
        self.t_personas = Persona.Persona(
        )  #se crea el objeto de dominio para guardar la información
        self.insertando = True

        #*************************************************************************
        #se crean los campos de la pantalla
        #*************************************************************************

        #Se coloca un label del titulo
        self.lb_tituloPantalla = Label(self.raiz,
                                       text="MANTENIMIENTO DE PERSONAS",
                                       font=self.fuente)
        self.lb_tituloPantalla.place(
            x=320, y=20
        )  #colocar por medio de espacion en pixeles de la parte superior de la pantalla considerando un eje x y un eje y

        #coloca en el formulario el campo y el label de idUsuario
        self.lb_idUsuario = Label(self.raiz, text="id Usuario:")
        self.lb_idUsuario.place(x=240, y=60)
        self.txt_idUsuario = Entry(self.raiz,
                                   textvariable=self.t_personas.idUsuario,
                                   justify="right")
        self.txt_idUsuario.place(x=370, y=60)

        #coloca en el formulario el campo y el label de nombre
        self.lb_nombreUsuario = Label(self.raiz, text="Nombre De Usuario:")
        self.lb_nombreUsuario.place(x=240, y=90)
        self.txt_nombreUsuario = Entry(
            self.raiz,
            textvariable=self.t_personas.nombreUsuario,
            justify="right",
            width=30)
        self.txt_nombreUsuario.place(x=370, y=90)

        #coloca en el formulario el campo y el label de contraseña
        self.lb_contraseña = Label(self.raiz, text="Contraseña:")
        self.lb_contraseña.place(x=240, y=120)
        self.txt_contraseña = Entry(self.raiz,
                                    textvariable=self.t_personas.contraseña,
                                    justify="right",
                                    width=30)
        self.txt_contraseña.place(x=370, y=120)

        #coloca en el formulario el campo y el label de correo
        self.lb_correo = Label(self.raiz, text="Correo:")
        self.lb_correo.place(x=240, y=150)
        self.txt_correo = Entry(self.raiz,
                                textvariable=self.t_personas.correo,
                                justify="right",
                                width=30)
        self.txt_correo.place(x=370, y=150)

        #coloca en el formulario el campo y el label de nombre
        self.lb_nombrePersona = Label(self.raiz, text="Nombre Persona:")
        self.lb_nombrePersona.place(x=240, y=180)
        self.txt_nombrePersona = Entry(
            self.raiz,
            textvariable=self.t_personas.nombrePersona,
            justify="right",
            width=30)
        self.txt_nombrePersona.place(x=370, y=180)

        #coloca en el formulario el campo y el label de apellido
        self.lb_apellidoPersona = Label(self.raiz, text="Apellido Persona:")
        self.lb_apellidoPersona.place(x=240, y=210)
        self.txt_apellidoPersona = Entry(
            self.raiz,
            textvariable=self.t_personas.apellidoPersona,
            justify="right",
            width=30)
        self.txt_apellidoPersona.place(x=370, y=210)

        #coloca en el formulario el campo y el label de fecha nacimiento
        self.lb_fechaNacimiento = Label(self.raiz, text="Fecha nacimiento:")
        self.lb_fechaNacimiento.place(x=240, y=240)
        self.txt_fechaNacimiento = Entry(
            self.raiz,
            textvariable=self.t_personas.fechaNacimiento,
            justify="right",
            width=30,
            state="readonly")
        self.txt_fechaNacimiento.place(x=370, y=240)
        self.bt_mostrarCalendario = Button(self.raiz,
                                           text="...",
                                           width=3,
                                           command=self.mostrarDatePicker)
        self.bt_mostrarCalendario.place(x=650, y=240)

        #coloca en el formulario el campo y el label de estado
        self.lb_estado = Label(self.raiz, text="Estado: ")
        self.lb_estado.place(x=240, y=270)
        self.txt_estado = Entry(self.raiz,
                                textvariable=self.t_personas.estado,
                                justify="right",
                                width=30)
        self.txt_estado.place(x=370, y=270)

        #coloca en el formulario el campo y el label de personal
        self.lb_descripcionPersonal = Label(self.raiz,
                                            text="Descripcion Personal")
        self.lb_descripcionPersonal.place(x=240, y=300)
        self.txt_descripcionPersonal = Entry(
            self.raiz,
            textvariable=self.t_personas.descripcionPersona,
            justify="right",
            width=30)
        self.txt_descripcionPersonal.place(x=370, y=300)

        #coloca los botones enviar y borrar
        self.bt_borrar = Button(self.raiz,
                                text="Limpiar",
                                width=15,
                                command=self.limpiarInformacion)
        self.bt_borrar.place(x=370, y=330)

        self.bt_enviar = Button(self.raiz,
                                text="Enviar",
                                width=15,
                                command=self.enviarInformacion)
        self.bt_enviar.place(x=510, y=330)

        #Se coloca un label del informacion
        self.lb_tituloPantalla = Label(self.raiz,
                                       text="INFORMACIÓN INCLUIDA",
                                       font=self.fuente)
        self.lb_tituloPantalla.place(
            x=350, y=360
        )  #colocar por medio de espacion en pixeles de la parte superior de la pantalla considerando un eje x y un eje y

        #*************************************************************************
        #tabla con informacion
        #*************************************************************************

        self.sheet = Sheet(
            self.raiz,
            page_up_down_select_row=True,
            #empty_vertical = 0,
            column_width=120,
            startup_select=(0, 1, "rows"),
            #row_height = "4",
            #default_row_index = "numbers",
            #default_header = "both",
            #empty_horizontal = 0,
            #show_vertical_grid = False,
            #show_horizontal_grid = False,
            #auto_resize_default_row_index = False,
            #header_height = "3",
            #row_index_width = 100,
            #align = "center",
            #header_align = "w",
            #row_index_align = "w",
            #data = [[f"Row {r}, Column {c}\nnewline1\nnewline2" for c in range(50)] for r in range(1000)], #to set sheet data at startup
            headers=[
                'idUsuario', 'nombreUsuario', 'contraseña.', 'correo.',
                'nombrePersona', 'apellidoPersona', 'Fec. Nacimiento',
                'estado', 'descripcionPersona'
            ],
            #row_index = [f"Row {r}\nnewline1\nnewline2" for r in range(2000)],
            #set_all_heights_and_widths = True, #to fit all cell sizes to text at start up
            #headers = 0, #to set headers as first row at startup
            #headers = [f"Column {c}\nnewline1\nnewline2" for c in range(30)],
            #theme = "light green",
            #row_index = 0, #to set row_index as first column at startup
            #total_rows = 2000, #if you want to set empty sheet dimensions at startup
            #total_columns = 30, #if you want to set empty sheet dimensions at startup
            height=195,  #height and width arguments are optional
            width=720  #For full startup arguments see DOCUMENTATION.md
        )
        #self.sheet.hide("row_index")
        #self.sheet.hide("header")
        #self.sheet.hide("top_left")
        self.sheet.enable_bindings((
            "single_select",  #"single_select" or "toggle_select"
            "column_select",
            "row_select",
            "column_width_resize",
            "double_click_column_resize",
            #"row_width_resize",
            #"column_height_resize",
            "arrowkeys",
            "row_height_resize",
            "double_click_row_resize",
            "right_click_popup_menu",
            "rc_select",
            "rc_insert_column",
            "rc_delete_column",
            "rc_insert_row",
            "rc_delete_row"))
        #self.sheet.disable_bindings() #uses the same strings
        #self.sheet.enable_bindings()

        self.sheet.place(x=20, y=390)

        #coloca los botones cargar y eliminar
        self.bt_cargar = Button(self.raiz,
                                text="Cargar",
                                width=15,
                                command=self.cargarInformacion)
        self.bt_cargar.place(x=750, y=385)

        self.bt_eliminar = Button(self.raiz,
                                  text="Eliminar",
                                  width=15,
                                  command=self.eliminarInformacion)
        self.bt_eliminar.place(x=750, y=425)

        self.cargarTodaInformacion()

        #*************************************************************************
        #se inicial el main loop de la pantalla
        #*************************************************************************
        self.raiz.mainloop()

    #*************************************************************************
    #Metodo para consultar la información de la base de datos para
    #cargarla en la tabla
    #*************************************************************************
    def cargarTodaInformacion(self):
        try:
            self.personaBo = PersonaBO.PersonaBO(
            )  #se crea un objeto de logica de negocio
            resultado = self.personaBo.consultar()

            self.sheet.set_sheet_data(resultado)
        except Exception as e:
            msg.showerror(
                "Error", str(e)
            )  #si se genera algun tipo de error muestra un mensache con dicho error

    #*************************************************************************
    #Metodo para cargar informacion
    #*************************************************************************
    def cargarInformacion(self):
        try:
            datoSeleccionado = self.sheet.get_currently_selected()
            idUsuarios = (self.sheet.get_cell_data(datoSeleccionado[0], 0))
            self.t_personas.idUsuario.set(idUsuarios)
            self.personaBo = PersonaBO.PersonaBO(
            )  #se crea un objeto de logica de negocio
            self.personaBo.consultarPersona(
                self.t_personas)  #se envia a consultar
            self.insertando = False
            msg.showinfo(
                "Acción: Consultar persona",
                "La información de la persona ha sido consultada correctamente"
            )  # Se muestra el mensaje de que todo esta correcto

        except Exception as e:
            msg.showerror(
                "Error", str(e)
            )  #si se genera algun tipo de error muestra un mensache con dicho error

    #*************************************************************************
    #Metodo para cargar eliminar la informacion
    #*************************************************************************
    def eliminarInformacion(self):
        try:
            datoSeleccionado = self.sheet.get_currently_selected()
            idUsuarios = (self.sheet.get_cell_data(datoSeleccionado[0], 0))
            nombre = (self.sheet.get_cell_data(datoSeleccionado[0], 1))

            resultado = msg.askquestion(
                "Eliminar",
                "¿Desear eliminar a " + nombre + " de la base de datos?")
            if resultado == "yes":
                self.t_personas.idUsuario.set(idUsuarios)
                self.personaBo = PersonaBO.PersonaBO(
                )  #se crea un objeto de logica de negocio
                self.personaBo.eliminar(self.t_personas)  #se envia a consultar
                self.cargarTodaInformacion()
                self.t_personas.limpiar()
        except Exception as e:
            msg.showerror(
                "Error", str(e)
            )  #si se genera algun tipo de error muestra un mensache con dicho error

    #*************************************************************************
    #Metodo para enviar la información a la base de datos
    #*************************************************************************
    def enviarInformacion(self):
        try:
            self.personaBo = PersonaBO.PersonaBO(
            )  #se crea un objeto de logica de negocio
            if (self.insertando == True):
                self.personaBo.guardar(self.t_personas)
            else:
                self.personaBo.modificar(self.t_personas)

            self.cargarTodaInformacion()
            self.t_personas.limpiar()  #se limpia el formulario

            if (self.insertando == True):
                msg.showinfo(
                    "Acción: Agregar persona",
                    "La información de la persona ha sido incluida correctamente"
                )  # Se muestra el mensaje de que todo esta correcto
            else:
                msg.showinfo(
                    "Acción: Agregar modificar",
                    "La información de la persona ha sido modificada correctamente"
                )  # Se muestra el mensaje de que todo esta correcto
        except Exception as e:
            msg.showerror(
                "Error", str(e)
            )  #si se genera algun tipo de error muestra un mensache con dicho error

    #*************************************************************************
    #Metodo para limpiar el formulario
    #*************************************************************************
    def limpiarInformacion(self):
        self.t_personas.limpiar(
        )  #llama al metodo de la clase persona para limpiar los atritudos de la clase
        self.insertando = True
        msg.showinfo(
            "Acción del sistema",
            "La información del formulario ha sido eliminada correctamente"
        )  # muestra un mensaje indicando que se limpio el formulario

    #*************************************************************************
    #Metodo para mostrar un contro tipo datepicker
    #*************************************************************************
    def mostrarDatePicker(self):
        self.top = Toplevel(self.raiz)
        self.cal = Calendar(self.top,
                            font="Arial 14",
                            selectmode='day',
                            locale='en_US',
                            year=2019,
                            month=6,
                            day=16)
        self.cal.pack(fill="both", expand=True)
        ttk.Button(self.top, text="Seleccionar",
                   command=self.seleccionarFecha).pack()

    #*************************************************************************
    #Evento para obtener la fecha del datepicker
    #*************************************************************************
    def seleccionarFecha(self):
        self.t_personas.fechaNacimiento.set(self.cal.selection_get())