def example1():
        def print_sel():
            cal.destroy()
            global dobVal
            dobVal = cal.selection_get()
            print(dobVal)
            fin.config(text="YYYY/MM/DD : " + str(dobVal))

        mindate = datetime.date(year=1999, month=1, day=20)
        maxdate = datetime.date(year=2003, month=1, day=20)
        cal = Calendar(first,
                       font="Arial 14",
                       selectmode='day',
                       locale='en_US',
                       mindate=mindate,
                       maxdate=maxdate,
                       disabledforeground='red')

        cal.place(x=720, y=360)
        ttk.Button(first, text="save", command=print_sel).place(x=1100, y=350)
Пример #2
0
def cal_set(root):
    global cal_variable, widgets
    # Calender widget
    today = (today_date_num('m') + "/" + today_date_num('d') + "/" +
             today_date_num('y'))
    cal_variable.set(today)
    cal = Calendar(root,
                   font=calender_font,
                   selectmode='day',
                   textvariable=cal_variable,
                   firstweekday="sunday",
                   showweeknumbers=False,
                   background=cal_bg,
                   headersbackground=cal_text,
                   weekendforeground='black',
                   showothermonthdays=False,
                   othermonthforeground='#bfbfbf',
                   othermonthbackground='#d9d9d9',
                   othermonthweforeground='#bfbfbf',
                   othermonthwebackground='#d9d9d9')
    cal.place(x=10, y=150, w=380, h=300)

    widgets["CAL"] = cal
    return cal
                       bg="#3841c7",
                       width=8)
Calendar_Label.place(x=820, y=195)

Calendar_Interface_Label = Calendar(root,
                                    font=("Century Gothic", 15),
                                    selectmode='day',
                                    locale='en_US',
                                    mindate=mindate,
                                    maxdate=maxdate,
                                    disabledforeground='red',
                                    cursor="hand1",
                                    year=2020,
                                    month=8,
                                    day=11)
Calendar_Interface_Label.place(x=700, y=250)

#Alarm


def alarm():

    #Set up the program

    root = tkinter.Tk()
    root.title("Alarm")
    root.geometry("400x270")
    root.resizable(width=False, height=False)
    root.configure(bg="#323999")

    Alarm_Label = Label(root,
    def add_expense(self):
        exp_win = Tk()
        exp_win.geometry("800x1000")
        exp_win.title("Expense")
        win_h = 600
        win_w = 1200
        exp_win.configure(bg="powder blue")
        style = ttk.Style()
        a = Label(exp_win,
                  text="Enter Expense Data",
                  bg="blue",
                  fg='Yellow',
                  font=("Times new roman", 30, "italic",
                        'bold')).pack(fill='both')  #place(x=50,y=50)
        b = Label(exp_win, text="Select Date: ",
                  font=("Times new roman", 14)).place(x=50, y=70)
        cal = Calendar(exp_win,
                       font=("Times new roman", 10, 'bold'),
                       selectmode='day',
                       cursor="hand1",
                       year=2020,
                       month=7,
                       day=5)
        cal.place(x=50, y=100)
        frame = tk.Frame(exp_win)
        frame.place(x=50, y=320)
        tree = ttk.Treeview(frame,
                            columns=(1, 2, 3, 4),
                            height=10,
                            show="headings",
                            style="mystyle.Treeview")
        tree.pack(side='left')
        tree.heading(1, text='ID')
        tree.heading(2, text="Date")
        tree.heading(3, text="Expense Title")
        tree.heading(4, text="Amount")
        tree.column(1, width=50)
        tree.column(2, width=100)
        tree.column(3, width=100)
        tree.column(4, width=120)
        scroll = ttk.Scrollbar(frame, orient="vertical", command=tree.yview)
        scroll.pack(side='right', fill='y')
        tree.configure(yscrollcommand=scroll.set)

        Label(exp_win,
              text="Expense Title: ",
              bg="white",
              font=("Times new roman", 14)).place(x=400, y=100)
        ty = Entry(exp_win, font=("Times new roman", 14))
        ty.place(x=520, y=100)

        Label(exp_win, text="Amount", bg="white",
              font=("Times new roman", 14)).place(x=400, y=160)
        amt = Entry(exp_win, font=("Times new roman", 14))
        amt.place(x=520, y=160)

        def add():
            i = Expense.assign_id(self)
            a = cal.selection_get()
            c = ty.get()
            f = amt.get()
            print(i, a, c, f)
            tree.insert('', 'end', values=(i, a, c, f))
            Expense.add(self, i, a, c, f)
            messagebox.showinfo('Confirmation',
                                'Record is added successesfully')

        b1 = Button(exp_win, text="Confirm", command=add).place(x=400, y=250)

        def back():
            exp_win.destroy()
            self.interface()

        b2 = Button(exp_win, text="Main Menu", command=back).place(x=600,
                                                                   y=250)
    def add_pur(self):
        pur_win = Tk()
        pur_win.geometry("1000x1200")
        pur_win.title("Purchase")
        win_h = 600
        win_w = 1200
        pur_win.configure(bg="powder blue")
        style = ttk.Style()
        a = Label(pur_win,
                  text="Enter Purhase Data",
                  fg="yellow",
                  bg='blue',
                  font=("Times new roman", 30, "italic",
                        'bold')).pack(fill='both')  #place(x=50,y=50)
        b = Label(pur_win, text="Select Date",
                  font=("Times new roman", 12)).place(x=50, y=70)
        cal = Calendar(pur_win,
                       font=("Times new roman", 10, 'bold'),
                       selectmode='day',
                       cursor="hand1",
                       year=2020,
                       month=7,
                       day=5)
        cal.place(x=50, y=100)
        frame = tk.Frame(pur_win)
        frame.place(x=50, y=350)
        tree = ttk.Treeview(frame,
                            columns=(1, 2, 3, 4, 5, 6),
                            height=10,
                            show="headings",
                            style="mystyle.Treeview")
        tree.pack(side='left')
        tree.heading(1, text='ID')
        tree.heading(2, text="Date")
        tree.heading(3, text="Product Name")
        tree.heading(4, text="Price")
        tree.heading(5, text="Quantity")
        tree.heading(6, text="Amount")
        tree.column(1, width=50)
        tree.column(2, width=100)
        tree.column(3, width=100)
        tree.column(4, width=120)
        tree.column(5, width=100)
        tree.column(6, width=80)
        scroll = ttk.Scrollbar(frame, orient="vertical", command=tree.yview)
        scroll.pack(side='right', fill='y')
        tree.configure(yscrollcommand=scroll.set)
        Label(pur_win,
              text="Product Name:",
              bg="white",
              font=("Times new roman", 14)).place(x=400, y=80)
        ty = Entry(pur_win, font=("Times new roman", 14))
        ty.place(x=520, y=80)

        Label(pur_win,
              text="Price: ",
              bg="white",
              font=("Times new roman", 14)).place(x=400, y=140)
        pr = Entry(pur_win, font=("Times new roman", 14))
        pr.place(x=520, y=140)

        Label(pur_win,
              text="Quantity: ",
              bg="white",
              font=("Times new roman", 14)).place(x=400, y=190)
        quan = Spinbox(pur_win,
                       from_=1,
                       to=1000,
                       width=5,
                       font=("Times new roman", 14))
        quan.place(x=520, y=200)

        def add():
            i = Purchase.assign_id(self)
            a = cal.selection_get()
            c = ty.get()
            d = pr.get()
            e = quan.get()
            f = int(d) * int(e)
            print(i, a, c, d, e, f)
            tree.insert('', 'end', values=(i, a, c, d, e, f))
            Purchase.add(self, i, a, c, d, e, f)
            messagebox.showinfo('Confirmation',
                                'Record is added successesfully')

        b1 = Button(pur_win, text="Confirm", command=add).place(x=700, y=330)

        def back():
            pur_win.destroy()
            self.interface()

        b2 = Button(pur_win, text="Main Menu", command=back).place(x=850,
                                                                   y=330)
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()
Пример #7
0
frame_stat.place(relx=0.5, rely=0.1, relwidth=0.8, relheight=0.8, anchor='n')

# frame: setting
frame_setting = tk.Frame(root, bg="#efc6d9", bd=5)
frame_setting.place(relx=0.5,
                    rely=0.1,
                    relwidth=0.8,
                    relheight=0.8,
                    anchor='n')

#calendar = DateEntry(frame2)
calendar = Calendar(frame_cal,
                    year=today.year,
                    month=today.month,
                    day=today.day)
calendar.place(relx=0.5, rely=0.3, relwidth=0.7, anchor='n')


def calPage():
    calendar.place(relx=0.5, rely=0.3, relwidth=0.7, anchor='n')
    frame_cal.place(relx=0.5,
                    rely=0.1,
                    relwidth=0.8,
                    relheight=0.8,
                    anchor='n')
    frame_cal.tkraise()


def expPage():
    #-- Test: date chosen from calendar received properly --
    #input_date = calendar.get_date()
Пример #8
0
def EnrollPage():
    def enroll_ok():
        try:
            profile = {
                "ID": int(id_box.get()),
                "Name": name_box.get(),
                "Class": int(class_box.get()),
                "Section": section_list.curselection()[0],
                "DOB": dob_box.get_date(),
                "ParentContact": int(contact_box.get())
            }
            dir_path = f"./StudentManagementSystem/data/profiles"
            file_path = dir_path + f"/{profile['ID']}.json"
            
            if (not os.path.exists(dir_path)):
                os.makedirs(dir_path)
            with open(file_path, "w") as f:
                f.write(json.dumps(profile, indent=4))

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

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

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

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

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

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

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

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

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

    ok_button = Button(window, text="OK", command=enroll_ok)
    ok_button.place(x=240, y=520, width=90)
    cancel_button = Button(window, text="Cancel", command=window.destroy)
    cancel_button.place(x=340, y=520, width=90)
Пример #9
0
def showOptionsOtherDays(win1):
    frame = tk.Frame(win1)
    frame.place(relx=0, rely=0, relwidth=1, relheight=1)
    #-------------- Background Image--------------------------
    img = Image.open("./images/background3.png")
    img = img.resize((500, 500), Image.ANTIALIAS)
    background_image = ImageTk.PhotoImage(img)
    background_label = tk.Label(win1, image=background_image)
    background_label.image = background_image
    background_label.place(x=0, y=0, relwidth=1, relheight=1)
    #---------------------------------------------------------
    to_display_date_and_time = Date_Time(win1)
    label_month = tk.Label(win1,
                           text="SELECT DATE:",
                           width=12,
                           font=("Times", 15, "bold"),
                           borderwidth=2,
                           relief="solid")
    label_month.place(x=150, y=50)
    cal = Calendar(win1,
                   font="Arial 14",
                   selectmode='day',
                   cursor="hand1",
                   year=datetime.datetime.now().year,
                   month=datetime.datetime.now().month,
                   day=datetime.datetime.now().day,
                   mindate=datetime.date(2018, 11, 1),
                   maxdate=datetime.date(2020, 11, 1))
    cal.place(x=50, y=90)

    def getDate():
        try:
            finalday = " ".join([
                elem for elem in reversed(str(cal.selection_get()).split('-'))
            ])  # convert i.e 2019-11-12 to 12 11 2019
            which_day = findDay(finalday)  #convert i.e 12 11 2019 to Tuesday
            if int(spinbox_hr.get()) not in range(1, 13) or int(
                    spinbox_min.get()) not in range(
                        0, 61):  #validate user input for time
                print('time out of range')
                raise ValueError
            finaltime = convert_to_24hr(
                minutes=spinbox_min.get(),
                hours=spinbox_hr.get(),
                AM_PM=AM_PM_str.get())  # convert i.e 4.30PM to 16:30
            ## check if any stores are open and then create a window with the list of stores
            ids, no_of_available_stores = [], 0  # a list that will contain the ids of stores available in that time frame, no_of_available_stores is to keep track of the available stores
            for id, operating_hours in operating_hrs.items():
                for day_of_the_week, time in operating_hours.items():
                    if day_of_the_week == which_day:
                        start_time = datetime.datetime.strptime(
                            time.split('-')[0],
                            '%H:%M').time()  #convert i.e 09:00 to 09:00:00
                        end_time = datetime.datetime.strptime(
                            time.split('-')[1],
                            '%H:%M').time()  #convert i.e 09:00 to 09:00:00
                        final_time = datetime.datetime.strptime(
                            finaltime,
                            '%H:%M').time()  #convert i.e 09:00 to 09:00:00
                        if final_time > end_time or final_time < start_time:
                            continue
                        else:
                            no_of_available_stores += 1
                            ids.append(id)

            if no_of_available_stores == 0:  #means no stores are available
                raise Exception
            show_list_of_avalble_store(
                final_time, ids, win1
            )  #if there are available stores we proceed to the nxt frame
        except ValueError as e:
            print(e)
            win_error = tk.Tk()
            win_error.resizable(False, False)
            win_error.geometry('150x150')
            win_error.title('Error Message')
            error_msg = tk.Label(win_error,
                                 text="PLEASE KEY IN \nVALID INPUTS",
                                 width=16,
                                 font=("Times", 12, "bold"),
                                 fg="red")
            error_msg.place(x=0, y=25)
            Back_button = tk.Button(win_error,
                                    text="BACK",
                                    width=10,
                                    font=("Times", 15),
                                    borderwidth=2,
                                    relief="solid",
                                    command=win_error.destroy)
            Back_button.place(x=15, y=100)
        except Exception as e:
            print(e)
            win_error = tk.Tk()
            win_error.resizable(False, False)
            win_error.title('Error Message')
            win_error.geometry('150x150')
            error_msg = tk.Label(win_error,
                                 text="NO STORES ARE \nAVAILABLE",
                                 width=16,
                                 font=("Times", 12, "bold"),
                                 fg="red")
            error_msg.place(x=0, y=25)
            Back_button = tk.Button(win_error,
                                    borderwidth=2,
                                    relief="solid",
                                    text="BACK",
                                    width=10,
                                    font=("Times", 15),
                                    command=win_error.destroy)
            Back_button.place(x=15, y=100)

    label_month = tk.Label(win1,
                           text="SELECT TIME:",
                           width=12,
                           font=("Times", 15, "bold"),
                           borderwidth=2,
                           relief="solid")
    label_month.place(x=150, y=340)
    spinbox_hr = tk.Spinbox(win1, from_=1, to=12, width=6)
    spinbox_hr.place(x=120, y=385)
    colon = tk.Label(win1, text=":", width=1, font=("Times", 9, "bold"))
    colon.place(x=176, y=383)
    spinbox_min = tk.Spinbox(win1, from_=00, to=59, width=6)
    spinbox_min.place(x=195, y=385)
    AM_PM_optionlist = ['AM', 'PM']
    AM_PM_str = tk.StringVar(win1)
    AM_PM_str.set(AM_PM_optionlist[0])
    AM_PM_option = tk.OptionMenu(win1, AM_PM_str, *AM_PM_optionlist)
    AM_PM_option.place(x=250, y=377)

    confirm_button = tk.Button(win1,
                               text="ENTER",
                               borderwidth=2,
                               relief="solid",
                               width=20,
                               font=("Times", 15),
                               command=lambda: getDate())
    confirm_button.place(x=100, y=415)

    Back_button = tk.Button(win1,
                            text="BACK",
                            borderwidth=2,
                            relief="solid",
                            width=20,
                            font=("Times", 15),
                            command=lambda: landing_page(win1))
    Back_button.place(x=100, y=460)
Пример #10
0
class Vista(Frame):
    # Inicializa el controlador y algunas variables globales
    # Params:
    #   master: instancia de Window
    #   modelo: Modelo
    def __init__(self, master, modelo):
        Frame.__init__(self, master)
        self.pack()
        self.master = master
        self.modelo = modelo
        self.controlador = Controlador(self.modelo, self)
        self.col1 = 'khaki1'
        self.col2 = 'snow'
        self.font = 'Helvetica'
        self.init_components()
        return

    #Inicializa los componentes de la Vista y los coloca
    def init_components(self):
        self.label_model = Label(self.master,
                                 text='Modelo',
                                 font=(self.font, 14),
                                 relief=GROOVE,
                                 bg=self.col2)
        self.label_data = Label(self.master,
                                text='Datos',
                                font=(self.font, 14),
                                relief=GROOVE,
                                bg=self.col2)
        self.label_pred = Label(self.master,
                                text='Predicción',
                                font=(self.font, 14),
                                relief=GROOVE,
                                bg=self.col2)
        self.label_res = Label(self.master,
                               text='Resultados',
                               font=(self.font, 14),
                               relief=GROOVE,
                               bg=self.col2)

        self.variable = StringVar()
        self.variable.set('Modelo 1')
        self.variable.trace("w", self.change_model)

        self.model_selector = OptionMenu(self.master, self.variable,
                                         *list(self.modelo.modelos.keys()))

        self.frame = Frame(self.master)

        self.alg_label = Label(self.frame,
                               text='Algoritmo',
                               font=(self.font, 8, 'bold'),
                               bg=self.col2,
                               relief='raised',
                               width=20)
        self.seas_label = Label(self.frame,
                                text='Temporadas',
                                font=(self.font, 8, 'bold'),
                                bg=self.col2,
                                relief='raised',
                                width=20)
        self.columns_label = Label(self.frame,
                                   text='Selección columnas',
                                   font=(self.font, 8, 'bold'),
                                   bg=self.col2,
                                   relief='raised',
                                   width=20)
        self.pca_label = Label(self.frame,
                               text='PCA',
                               font=(self.font, 8, 'bold'),
                               bg=self.col2,
                               relief='raised',
                               width=20)
        self.params_label = Label(self.frame,
                                  text='Parámetros',
                                  bg=self.col2,
                                  font=(self.font, 8, 'bold'),
                                  relief='raised',
                                  width=20)

        self.alg_value = Label(self.frame,
                               text='',
                               font=(self.font, 8),
                               bg=self.col2,
                               relief='raised',
                               width=30)
        self.seas_value = Label(self.frame,
                                text='',
                                font=(self.font, 8),
                                bg=self.col2,
                                relief='raised',
                                width=30)
        self.columns_value = Label(self.frame,
                                   text='',
                                   font=(self.font, 8),
                                   bg=self.col2,
                                   relief='raised',
                                   width=30)
        self.pca_value = Label(self.frame,
                               text='',
                               font=(self.font, 8),
                               bg=self.col2,
                               relief='raised',
                               width=30)
        self.params_value = Label(self.frame,
                                  text='',
                                  font=(self.font, 8),
                                  bg=self.col2,
                                  relief='raised',
                                  width=30)

        self.load_model_but = Button(self.master,
                                     text='Cargar modelo',
                                     state='disabled',
                                     command=self.load_model,
                                     bg=self.col2)

        self.train_model_but = Button(self.master,
                                      text='Entrenar modelo',
                                      state='disabled',
                                      command=self.train_model,
                                      bg=self.col2)

        self.load_data_but = Button(self.master,
                                    text='Cargar datos',
                                    command=self.load_data,
                                    bg=self.col2)

        self.ref_but = Button(self.master,
                              text='Actualizar datos',
                              command=self.refresh,
                              bg=self.col2)

        self.home_label = Label(self.master, text='Equipo local', bg=self.col1)
        self.away_label = Label(self.master,
                                text='Equipo visitante',
                                bg=self.col1)

        self.home = StringVar()
        self.home.set(self.modelo.teams[0])
        self.homeOptionMenu = OptionMenu(self.master, self.home,
                                         *list(self.modelo.teams))
        self.homeOptionMenu.config(state='disabled')

        self.away = StringVar()
        self.away.set(self.modelo.teams[0])
        self.awayOptionMenu = OptionMenu(self.master, self.away,
                                         *list(self.modelo.teams))
        self.awayOptionMenu.config(state='disabled')

        self.calendar = Calendar(self.master, state='disabled')

        self.pred_but = Button(self.master,
                               text='Hallar predicciones',
                               state='disabled',
                               command=self.exec_prediction,
                               bg=self.col2)

        self.result = Label(self.master,
                            text='',
                            bg=self.col1,
                            font=(self.font, 10, 'bold'))
        self.pred = Label(self.master,
                          text='',
                          bg=self.col1,
                          font=(self.font, 10, 'bold'))
        self.team_win = Label(self.master,
                              text='',
                              bg=self.col1,
                              font=(self.font, 10, 'bold'))

        self.sep1 = Separator(self.master, orient=HORIZONTAL)
        self.sep2 = Separator(self.master, orient=HORIZONTAL)
        self.sep3 = Separator(self.master, orient=VERTICAL)

        self.label_error = Label(self.master,
                                 text='',
                                 font=('device', 10),
                                 fg='red',
                                 bg=self.col1)

        ### PACKING & PLACING
        self.label_model.pack()
        self.label_model.place(relx=0.05, rely=0.05, anchor=W)
        self.label_data.pack()
        self.label_data.place(relx=0.05, rely=0.4, anchor=W)
        self.label_pred.pack()
        self.label_pred.place(relx=0.05, rely=0.6, anchor=W)

        self.model_selector.pack()
        self.model_selector.place(relx=0.15, rely=0.15, anchor=CENTER)

        self.frame.pack()
        self.frame.place(relx=0.25, rely=0.05)

        self.alg_label.grid(row=0, rowspan=1, column=0, columnspan=1)
        self.seas_label.grid(row=1, rowspan=1, column=0, columnspan=1)
        self.columns_label.grid(row=2, rowspan=1, column=0, columnspan=1)
        self.pca_label.grid(row=3, rowspan=1, column=0, columnspan=1)
        self.params_label.grid(row=4,
                               rowspan=1,
                               column=0,
                               columnspan=1,
                               sticky=N + E + S + W)

        self.alg_value.grid(row=0, rowspan=1, column=1, columnspan=1)
        self.seas_value.grid(row=1, rowspan=1, column=1, columnspan=1)
        self.columns_value.grid(row=2, rowspan=1, column=1, columnspan=1)
        self.pca_value.grid(row=3, rowspan=1, column=1, columnspan=1)
        self.params_value.grid(row=4, rowspan=1, column=1, columnspan=1)
        self.change_model()

        self.load_model_but.pack()
        self.load_model_but.place(relx=0.1, rely=0.48, anchor=CENTER)

        self.train_model_but.pack()
        self.train_model_but.place(relx=0.24, rely=0.48, anchor=CENTER)

        self.load_data_but.pack()
        self.load_data_but.place(relx=0.38, rely=0.48, anchor=CENTER)

        self.ref_but.pack()
        self.ref_but.place(relx=0.52, rely=0.48, anchor=CENTER)

        self.home_label.pack()
        self.home_label.place(relx=0.1, rely=0.7, anchor=CENTER)

        self.away_label.pack()
        self.away_label.place(relx=0.25, rely=0.7, anchor=CENTER)

        self.homeOptionMenu.pack()
        self.homeOptionMenu.place(relx=0.1, rely=0.75, anchor=CENTER)

        self.awayOptionMenu.pack()
        self.awayOptionMenu.place(relx=0.25, rely=0.75, anchor=CENTER)

        self.calendar.pack()
        self.calendar.place(relx=0.45, rely=0.75, anchor=CENTER)

        self.pred_but.pack()
        self.pred_but.place(relx=0.17, rely=0.82, anchor=CENTER)

        self.label_res.pack()
        self.label_res.place(relx=0.7, rely=0.05, anchor=CENTER)

        self.result.pack()
        self.result.place(relx=0.8, rely=0.15, anchor=CENTER)

        self.pred.pack()
        self.pred.place(relx=0.8, rely=0.85, anchor=CENTER)

        self.team_win.pack()
        self.team_win.place(relx=0.8, rely=0.89, anchor=CENTER)

        self.sep1.place(relx=0.05, rely=0.33, relwidth=0.55)
        self.sep2.place(relx=0.05, rely=0.53, relwidth=0.55)
        self.sep3.place(relx=0.61, rely=0.05, relheight=0.9)

        self.label_error.place(relx=0.8, rely=0.93, anchor=CENTER)

    # Evento de cambiar el modelo que se esta seleccionando
    def change_model(self, *args):
        self.controlador.evento_change_model()
        if self.modelo.model_read is not None:
            self.alg_value['text'] = self.modelo.algorithms[
                self.modelo.model_read.alg]
            if self.modelo.model_read.seasons == '2015':
                seas = 'Desde 2014/2015'
            elif self.modelo.model_read.seasons == '2005':
                seas = 'Desde 2004/2005'
            else:
                seas = 'Desde 2000/2001'
            self.seas_value['text'] = seas
            self.columns_value['text'] = self.modelo.model_read.col
            self.pca_value[
                'text'] = 'Sí' if self.modelo.model_read.pca_analysis else 'No'

            if not pd.isnull(self.modelo.model_read.params):
                aux = ''
                for key in list(eval(self.modelo.model_read.params).keys()):
                    aux += str(key) + ': ' + str(
                        eval(self.modelo.model_read.params)[key]) + '\n'
                self.params_value['text'] = aux[:-1]
            else:
                self.params_value['text'] = ''

    # Evento de cargar los datos de los partidos
    def load_data(self):
        self.controlador.evento_load()
        if self.modelo.file is not None:
            self.load_model_but['state'] = 'active'
            self.calendar['state'] = 'normal'
            self.label_error.config(fg='green')
            self.label_error['text'] = 'Datos cargados con éxito'

    # Evento de actualizar los datos
    def refresh(self):
        self.controlador.evento_refresh()
        self.load_data()
        self.label_error.config(fg='green')
        self.label_error['text'] = 'Datos actualizados con éxito'

    # Evento de cargar el modelo predictivo seleccionado
    def load_model(self):
        self.label_error['text'] = ''
        self.train_model_but['state'] = 'active'
        self.controlador.evento_load_model()
        performance = self.modelo.modelo_prediccion.ac
        self.result['text'] = 'TASA DE ACIERTO: ' + str(
            performance.round(4) * 100) + '%'
        self.roc()
        self.pred_but['state'] = 'active'
        self.homeOptionMenu.config(state='active')
        self.awayOptionMenu.config(state='active')
        self.label_error.config(fg='green')
        self.label_error['text'] = 'Modelo cargado con éxito'

    # Evento de entrenar el modelo predictivo seleccionado
    def train_model(self):
        self.label_error['text'] = ''
        self.controlador.evento_train_model()
        self.load_model()

    # Evento de crear una curva ROC sobre los resultados del modelo predictivo seleccionado
    def roc(self):
        fpr, tpr, thres = roc_curve(self.modelo.modelo_prediccion.Y_test,
                                    self.modelo.modelo_prediccion.scores)
        auc_roc = auc(fpr, tpr)

        fig = Figure(figsize=(3.2, 3.2))
        a = fig.add_subplot(111)
        a.plot(fpr, tpr, color='blue', label='AUC %0.2f' % auc_roc)
        a.legend(loc="lower right")

        a.set_position([0.15, 0.12, 0.8, 0.8])
        a.set_xticks(ticks=np.arange(0, 1.5, 0.5))
        a.set_yticks(ticks=np.arange(0, 1.5, 0.5))
        a.set_xticklabels(labels=np.arange(0, 1.5, 0.5),
                          fontdict={'fontsize': 8})
        a.set_yticklabels(labels=np.arange(0, 1.5, 0.5),
                          fontdict={'fontsize': 8})
        a.set_title("Curva ROC " +
                    self.modelo.algorithms[self.modelo.model_read.alg],
                    fontsize=10)
        a.set_ylabel("TPR", fontsize=8)
        a.set_xlabel("FPR", fontsize=8)

        canvas = FigureCanvasTkAgg(fig, master=self.master)
        canvas.get_tk_widget().pack(expand=True)
        canvas.get_tk_widget().place(relx=0.8, rely=0.5, anchor=CENTER)
        canvas.draw()

    # Evento de crear las predicciones para un partido determinado
    def exec_prediction(self):
        date = datetime.strptime(self.calendar.get_date(), '%m/%d/%y')
        game_id = str(
            date.year
        ) + '%02d' % date.month + '%02d' % date.day + '0' + self.home.get()

        if self.home.get() != self.away.get() and self.home.get(
        ) != 'No seleccionado' and self.away.get() != 'No seleccionado':
            aux = self.modelo.modelo_prediccion.predictions_test
            game_true = game_id in aux.game_id.values
            if date < datetime.today() and game_true and aux[
                    aux.game_id == game_id]['a_team_id'].values[
                        0] == self.away.get() or date > datetime.today():
                self.controlador.evento_exec_prediction()
                predres = self.modelo.prediction
                aux = self.home.get() if predres else self.away.get()
                self.label_error['text'] = ''
                self.pred['text'] = str(self.home.get()) + ': ' + str(
                    predres.round(2)) + '\t' + str(
                        self.away.get()) + ': ' + str((1 - predres).round(2))
                if date < datetime.today():
                    self.team_win['text'] = 'Victoria real: ' + str(aux)
            else:
                self.label_error.config(fg='red')
                self.label_error[
                    'text'] = 'ERROR: Ese partido no se ha disputado.'
                self.pred['text'] = ''
                self.team_win['text'] = ''
        elif self.home.get() == 'No seleccionado' and self.away.get(
        ) == 'No seleccionado':
            self.label_error.config(fg='red')
            self.pred['text'] = ''
            self.team_win['text'] = ''
            self.label_error['text'] = 'ERROR: Hay que determinar los equipos'
        elif self.home.get() == 'No seleccionado' or self.away.get(
        ) == 'No seleccionado':
            self.label_error.config(fg='red')
            self.pred['text'] = ''
            self.team_win['text'] = ''
            self.label_error['text'] = 'ERROR: Falta un equipo por determinar'
        elif self.home.get() == self.away.get():
            self.label_error.config(fg='red')
            self.pred['text'] = ''
            self.team_win['text'] = ''
            self.label_error[
                'text'] = 'ERROR: Los equipos deben ser diferentes.'
Пример #11
0
def deploy_component(frame):
    #define callback for change image (home team)
    def image_callback_home(var, indx, mode):
        load = Image.open(utils.get_image_path(home_team_dropdown_var.get()))
        load = load.resize((200, 200))
        render = ImageTk.PhotoImage(load)
        img = tk.Label(frame, image=render)
        img.image = render
        img.place(x=70, y=160)

    #define callback for change image (away team)
    def image_callback_away(var, indx, mode):
        load = Image.open(utils.get_image_path(away_team_dropdown_var.get()))
        load = load.resize((200, 200))
        render = ImageTk.PhotoImage(load)
        img = tk.Label(frame, image=render)
        img.image = render
        img.place(x=310, y=160)

    #define callback for calculate
    def calculate():
        def dialog_box_close():
            dialog_box.destroy()

        def result_frame_close():
            result_frame.destroy()

        print(cal.get_date())
        if home_team_dropdown_var.get() == away_team_dropdown_var.get():
            #when the team is same
            dialog_box = tk.Toplevel()
            dialog_box.geometry("350x115")

            ok_button = tk.Button(dialog_box,
                                  text="OK",
                                  command=dialog_box_close,
                                  height=2,
                                  width=7)

            message = tk.Label(dialog_box,
                               text="Please choose a different team",
                               font=("Helvetica", 14))

            print(utils.get_image_path("error"))
            loader = Image.open(utils.get_image_path("error"))
            loader = loader.resize((60, 50))
            err_img = ImageTk.PhotoImage(loader)
            err_label = tk.Label(dialog_box, image=err_img)
            err_label.image = err_img

            err_label.place(x=10, y=10)
            message.place(x=70, y=20)
            ok_button.place(x=155, y=55)

            dialog_box.mainloop()
        elif home_team_dropdown_var.get(
        ) == "Home Team" or away_team_dropdown_var.get() == "Away Team":
            #when home and away is empty
            dialog_box = tk.Toplevel()
            dialog_box.geometry("350x115")

            message = tk.Label(dialog_box,
                               text="Team field cannot be empty",
                               font=("Helvetica", 14))

            ok_button = tk.Button(dialog_box,
                                  text="OK",
                                  command=dialog_box_close,
                                  height=2,
                                  width=7)

            loader = Image.open(utils.get_image_path("error"))
            loader = loader.resize((60, 50))
            err_img = ImageTk.PhotoImage(loader)
            err_label = tk.Label(dialog_box, image=err_img)
            err_label.image = err_img

            err_label.place(x=10, y=10)
            message.place(x=85, y=20)
            ok_button.place(x=155, y=55)

            dialog_box.mainloop()
        elif cal.get_date() == "":
            #when date is not picked
            dialog_box = tk.Toplevel()
            dialog_box.geometry("350x115")

            message = tk.Label(dialog_box,
                               text="Date field cannot be empty",
                               font=("Helvetica", 14))

            ok_button = tk.Button(dialog_box,
                                  text="OK",
                                  command=dialog_box_close,
                                  height=2,
                                  width=7)

            loader = Image.open(utils.get_image_path("error"))
            loader = loader.resize((60, 50))
            err_img = ImageTk.PhotoImage(loader)
            err_label = tk.Label(dialog_box, image=err_img)
            err_label.image = err_img

            err_label.place(x=10, y=10)
            message.place(x=85, y=20)
            ok_button.place(x=155, y=55)

            dialog_box.mainloop()
        else:
            #do the calculation
            result_frame = tk.Toplevel()
            result_frame.geometry("350x330")

            home_team = home_team_dropdown_var.get()
            away_team = away_team_dropdown_var.get()
            date = cal.get_date()
            season = utils.get_season(date)

            utils.generate_data_for_calculation(home_team, away_team,
                                                utils.get_year(date))

            result = calculation.calculate(home_team, away_team, season)

            home_info = tk.Label(result_frame,
                                 text="Home Team : " + home_team,
                                 font=("Helvetica", 13))

            away_info = tk.Label(result_frame,
                                 text="Away Team : " + away_team,
                                 font=("Helvetica", 13))

            date_info = tk.Label(result_frame,
                                 text="Date           : " + date,
                                 font=("Helvetica", 13))

            season_info = tk.Label(result_frame,
                                   text="Season       : " + season,
                                   font=("Helvetica", 13))

            result_info = tk.Label(result_frame,
                                   text="Result : ",
                                   font=("Helvetica", 15))

            home_win = tk.Label(result_frame,
                                text="Home Win   : " + str(result[0]) + "%",
                                font=("Helvetica", 13))

            home_draw = tk.Label(result_frame,
                                 text="Draw           : " + str(result[1]) +
                                 "%",
                                 font=("Helvetica", 13))

            home_lose = tk.Label(result_frame,
                                 text="Home Lose  : " + str(result[2]) + "%",
                                 font=("Helvetica", 13))

            the_button = tk.Button(result_frame,
                                   text="OK",
                                   command=result_frame_close,
                                   height=2,
                                   width=7)

            #deployment
            home_info.place(x=20, y=20)
            away_info.place(x=20, y=50)
            date_info.place(x=20, y=80)
            season_info.place(x=20, y=110)
            result_info.place(x=20, y=150)
            home_win.place(x=20, y=180)
            home_draw.place(x=20, y=210)
            home_lose.place(x=20, y=240)
            the_button.place(x=140, y=280)
            result_frame.mainloop()

    #define the "Home Team" Label
    home_team_label = tk.Label(frame, text="Home Team", font=("Helvetica", 15))

    #define the "Away Team" Label
    away_team_label = tk.Label(frame, text="Away Team", font=("Helvetica", 15))

    #define the "Date" Label
    date_label = tk.Label(frame, text="Date", font=("Helvetiva", 16))

    #define the home team dropdown
    home_team_dropdown_var = tk.StringVar(frame)
    home_team_dropdown_var.set("Home Team")
    home_team_dropdown_var.trace('w', image_callback_home)
    home_team_dropdown = tk.OptionMenu(frame, home_team_dropdown_var,
                                       *utils.get_team_list())
    home_team_dropdown.config(width=25)

    #define the away team dropdown
    away_team_dropdown_var = tk.StringVar(frame)
    away_team_dropdown_var.set("Away Team")
    away_team_dropdown_var.trace('w', image_callback_away)
    away_team_dropdown = tk.OptionMenu(frame, away_team_dropdown_var,
                                       *utils.get_team_list())
    away_team_dropdown.config(width=25)

    #define the calendar
    cal = Calendar(frame,
                   selectmode="day",
                   date_pattern="dd/mm/yyyy",
                   year=2019)

    #define the button
    calculate_button = tk.Button(frame, text="Calculate", command=calculate)

    #deploying the component
    home_team_label.place(x=120.0, y=50.0)
    away_team_label.place(x=350.0, y=50.0)
    date_label.place(x=270, y=370)
    home_team_dropdown.place(x=70, y=120)
    away_team_dropdown.place(x=310, y=120)
    cal.place(x=170, y=400)
    calculate_button.place(x=260, y=630)
Пример #12
0
class MyApp(object):
    def __init__(self, parent):

        self.root = parent
        self.root.title("Main frame")
        self.root.protocol("WM_DELETE_WINDOW", self.cancelCallBack)

        todaystr = datetime.today().strftime("%Y-%m-%d")
        yesterdaystr = (datetime.today() -
                        timedelta(days=1)).strftime("%Y-%m-%d")

        self.todayLabel = Tk.Label(self.root)
        self.todayLabel.configure(height=1, width=3)
        self.todayLabel.configure(font=("Calibri", 8))
        self.todayLabel.configure(text="Received Today")
        self.todayLabel.configure(compound="left")
        self.todayLabel.place(relx=0.05,
                              rely=0.02,
                              relheight=0.1,
                              relwidth=0.4)

        self.todayBtn = Tk.Button(self.root, command=self.todayCallBack)
        self.todayBtn.configure(height=1, width=3)
        self.todayBtn.configure(font=("Calibri", 8))
        self.todayBtn.configure(text=todaystr + " - FileName")
        self.todayBtn.place(relx=0.45, rely=0.02, relheight=0.1, relwidth=0.5)

        self.yesterdayLabel = Tk.Label(self.root)
        self.yesterdayLabel.configure(height=1, width=3)
        self.yesterdayLabel.configure(font=("Calibri", 8))
        self.yesterdayLabel.configure(text="Received Yesterday")
        self.yesterdayLabel.place(relx=0.05,
                                  rely=0.14,
                                  relheight=0.1,
                                  relwidth=0.4)

        self.yesterdayBtn = Tk.Button(self.root,
                                      command=self.yesterdayCallBack)
        self.yesterdayBtn.configure(height=1, width=3)
        self.yesterdayBtn.configure(font=("Calibri", 8))
        self.yesterdayBtn.configure(text=yesterdaystr + " - FileName")
        self.yesterdayBtn.place(relx=0.45,
                                rely=0.14,
                                relheight=0.1,
                                relwidth=0.5)

        self.cal = Calendar(self.root,
                            font="Calibri 8",
                            selectmode='day',
                            locale='en_US',
                            cursor="hand2",
                            showweeknumbers=False)
        self.cal.place(relx=0.1, rely=0.27, relheight=0.6, relwidth=0.8)

        self.curdayBtn = Tk.Button(self.root, command=self.curdayCallBack)
        self.curdayBtn.configure(height=1, width=3)
        self.curdayBtn.configure(font=("Calibri", 8))
        self.curdayBtn.configure(text="Use date selected from calendar")
        self.curdayBtn.place(relx=0.05, rely=0.88, relheight=0.1, relwidth=0.7)

        self.cancelBtn = Tk.Button(self.root, command=self.cancelCallBack)
        self.cancelBtn.configure(height=1, width=3)
        self.cancelBtn.configure(font=("Calibri", 8))
        self.cancelBtn.configure(text="Cancel")
        self.cancelBtn.place(relx=0.78,
                             rely=0.88,
                             relheight=0.1,
                             relwidth=0.17)

        keyboard.add_hotkey('ctrl+shift+v', self.show)
        self.hide()

    def changeFileNames(self, template):
        files = self.explorer_fileselection()
        if files:
            for f in files:
                dirpath = os.path.dirname(os.path.abspath(f))
                filename = os.path.basename(os.path.abspath(f))
                newfilename = template + " - " + filename
                src = dirpath + "\\" + filename
                dst = dirpath + "\\" + newfilename
                os.rename(src, dst)
        else:
            win32ui.MessageBox("No seleted Files!", "Error")

    def todayCallBack(self):
        todaystr = datetime.today().strftime("%Y-%m-%d")
        self.changeFileNames(todaystr)
        self.hide()

    def yesterdayCallBack(self):
        yesterdaystr = (datetime.today() -
                        timedelta(days=1)).strftime("%Y-%m-%d")
        self.changeFileNames(yesterdaystr)
        self.hide()

    def curdayCallBack(self):
        curdatestr = self.cal.selection_get().strftime("%Y-%m-%d")
        self.changeFileNames(curdatestr)
        self.hide()

    def cancelCallBack(self):
        self.hide()

    def explorer_fileselection(self):
        clsid = '{9BA05972-F6A8-11CF-A442-00A0C90A8F39}'  #Valid for IE as well!
        shellwindows = win32.Dispatch(clsid)
        files = []
        try:
            for window in range(shellwindows.Count):
                window_URL = shellwindows[window].LocationURL
                window_dir = window_URL.split("///")[1].replace("/", "\\")
                selected_files = shellwindows[window].Document.SelectedItems()
                for file in range(selected_files.Count):
                    files.append(selected_files.Item(file).Path)
        except:
            win32ui.MessageBox("Close IE!", "Error")
        del shellwindows
        return files

    def show(self):
        self.root.attributes('-topmost', True)
        self.root.update()
        self.root.attributes('-topmost', False)
        self.root.deiconify()

    def hide(self):
        self.root.update()
        self.root.withdraw()
Пример #13
0
class ReadBooks():
    def __init__(self, master):
        '''Creamos un layout general formado por etiquetas, campos de entrada, radiobutton, calendario (que por defecto especifica la fecha de hoy) y 3 botones.
        Uno para confirmar la fecha introducida en el calendario y los otros dos: guardar registro y mostrar registros.'''

        self.master = master
        master.title('LIBROS LEIDOS DE LA HEMEROTECA:')
        master.geometry('550x525+500+0')
        master.configure(bg='light slate grey')
        self.score = IntVar()

        self.l_customer = Label(master,
                                text='Introduce DNI de CLIENTE:',
                                bg='light slate grey',
                                fg='white').place(x=50, y=40)
        self.e_customer = Entry(master, width=20)
        self.e_customer.place(x=350, y=40)
        self.l_book = Label(master,
                            text='Introduce ISBN del Libro:',
                            bg='light slate grey',
                            fg='white').place(x=50, y=80)
        self.e_book = Entry(master, width=20)
        self.e_book.place(x=350, y=80)
        self.l_score = Label(
            master,
            text='Puntuacion sobre 10 que da el cliente a la pelicula:',
            bg='light slate grey',
            fg='white').place(x=50, y=120)
        self.l_score2 = Label(master,
                              text='(Clica un boton del 1 al 10)',
                              bg='light slate grey',
                              fg='white',
                              font=('Verdana', 7)).place(x=50, y=135)
        self.e_score = Entry(master, width=20)
        self.e_score.place(x=350, y=120)
        for i in range(1, 11):
            self.rb_score = Radiobutton(master,
                                        text='' + str(i),
                                        value=i,
                                        variable=self.score,
                                        command=self.get_score).place(
                                            x=(40 + 35 * i), y=160)

        self.calendar = Calendar(master,
                                 selectmode='day',
                                 year=date.today().year,
                                 month=date.today().month,
                                 day=date.today().day)
        self.calendar.place(x=250, y=200)

        self.b_selectiondate = Button(master,
                                      text='Confirma fecha de lectura',
                                      bd=5,
                                      command=self.write_date).place(x=50,
                                                                     y=250)

        self.b_save = Button(master,
                             text='Guardar datos',
                             bd=5,
                             command=self.save).place(x=50, y=350)
        self.b_show = Button(master,
                             text='Mostrar datos',
                             bd=5,
                             command=self.show).place(x=350, y=400)

    def save(self):
        ''' Creamos la conexion con la bbdd. Creamos una tabla donde la clave primaria es compuesta y esta formada por 2 ajenas una de cada tabla:
        libros y clientes. Debemos activar las claves ajenas con PRAGMA no solo en la tabla hija sino en cada una de las conexiones de las tablas padre.
        Restringimos las claves foraneas a la modificacion o eliminacion en casacada desde las tablas padre.
        Recogemos los valores del registro introducido por el usuario y los introducimos en la tabla siempre que la fecha no sea posterior al dia de hoy.
        Borramos los campos de entrada creados por el usuario.
        Creamos una excepcion si las claves ajenas (DNI y ISBN) introducidas por el usuario, no existen. O si esas claves ajenas,
        que es la primaria de esta tabla, ya han sido introducidas (mismo libro y mismo cliente).
        '''
        try:
            c = sqlite3.connect('Hemeroteca.db')
            cursor = c.cursor()
            cursor.execute('PRAGMA foreign_keys=ON')
            #cursor.execute ('DROP TABLE LibrosLeidos')
            cursor.execute(
                '''CREATE TABLE IF NOT EXISTS LibrosLeidos (DNI_Cliente INTEGER,
                ISBN_Libro INTEGER , Puntuacion INTEGER, Fecha TEXT,
                PRIMARY KEY(DNI_Cliente, ISBN_Libro),
                FOREIGN KEY (DNI_Cliente) REFERENCES Clientes(DNI) ON UPDATE CASCADE ON DELETE CASCADE ,
                FOREIGN KEY(ISBN_Libro) REFERENCES Libros(ISBN) ON UPDATE CASCADE ON DELETE CASCADE)'''
            )

            if ((datetime.strptime(self.calendar.get_date(),
                                   '%m/%d/%y').date()) <= date.today()):

                cursor.execute(
                    '''INSERT INTO LibrosLeidos ( DNI_Cliente,
                            ISBN_Libro, Puntuacion, Fecha) VALUES (?,?,?,?)''',
                    (self.e_customer.get(), self.e_book.get(),
                     self.score.get(), self.calendar.get_date()))

                self.e_customer.delete(0, END)
                self.e_book.delete(0, END)
                self.e_score.delete(0, END)
                self.calendar_label = Label(self.master,
                                            text='                  ',
                                            bg='light slate grey',
                                            fg='white').place(x=100, y=300)

                c.commit()
                c.close()
            else:
                showwarning(
                    title='CUIDADO!',
                    message='Debes introducir una fecha anterior a hoy o hoy')

        except Exception as excep:
            showerror(
                title='SE HA PRODUCIDO UN  ERROR',
                message='Ese cliente con ese mismo libro ya existen. ' + '\n' +
                'O bien, estas introduciendo un cliente o un libro inexistentes'
            )

    def show(self):
        '''Volvemos a crear la conexion. Seleccionamos todos los registros de la tabla creada y
        les recogemos en una etiqueta separados por salto de linea. Recogemos la excepcion si la tabla esta todavia vacia. '''
        try:
            connection = sqlite3.connect('Hemeroteca.db')
            cursor = connection.cursor()
            cursor.execute('PRAGMA foreign_keys=ON')
            cursor.execute('SELECT * FROM LibrosLeidos')
            records = cursor.fetchall()
            print(records)
            print_records = ''

            for record in records:
                print_records += str(record) + '\n'

            self.records_label = Label(self.master,
                                       text=print_records,
                                       font=('Helvetica', 10),
                                       bg='light slate grey',
                                       fg='white').place(x=50, y=400)

            connection.commit()
            connection.close()
        except Exception as warning:
            showwarning(
                title='ATENCION',
                message=
                'Todavia no has introducido la preferencia de ningun cliente por ningun libro'
            )

    def get_score(self):
        '''Rellenamos el campo de entrada de puntuacion automaticamente con la seleccion de puntuacion presionando el radiobutton por el usuario.'''
        self.e_score.delete(0, END)
        self.e_score.insert(0, self.score.get())

    def write_date(self):
        '''Creamos una etiqueta que recoja la fecha escrita seleccionada por el usuario al pulsar en el calendario.  '''
        self.calendar_label = Label(self.master,
                                    text=self.calendar.get_date() + '   ',
                                    bg='light slate grey',
                                    fg='white').place(x=100, y=300)
Пример #14
0
class Funçoes(Validadores):
    def conecta_bd(self):
        self.conn = sqlite3.connect("AGENDAMENTOS.db")
        self.cursor = self.conn.cursor()
        print("Conectando ao banco de dados")

    def desconecta_bd(self):
        self.conn.close()
        print("Desconectando ao banco de dados")

    def montaTabelas(self):
        self.conecta_bd()
        ### Criar tabela
        self.cursor.execute("""
            CREATE TABLE IF NOT EXISTS Agendas (
                COD INTEGER PRIMARY KEY,
                NOME_CLIENTE CHAR(40) NOT NULL,
                TELEFONE INTEGER(20),
                DATA date,
                HORA time              
            );
        """)
        self.conn.commit()
        print("Banco de dados criado")
        self.desconecta_bd()

    def Calendario(self):
        self.cal = Calendar(self.Main, fg='black', locale='pt_br')
        self.cal.place(relx=0.75, rely=0.08)
        self.btsalva = Button(self.Main,
                              text='Salvar',
                              command=self.Salvar,
                              bg='#00FF7F')
        self.btsalva.place(relx=0.75, rely=0.27, relwidth=0.15)
        self.bt_fechar = Button(self.Main,
                                text='Sair',
                                command=self.Fechar,
                                bg='red')
        self.bt_fechar.place(relx=0.90, rely=0.27, relwidth=0.05)

    def Fechar(self):
        self.cal.destroy()
        self.btsalva.destroy()
        self.bt_fechar.destroy()

    def Agendar(self):
        self.conecta_bd()
        self.montaTabelas()

        self.entry_cod = Entry(self.Main)
        self.entry_cod.place(relx=0.15, rely=0.05, relwidth=0.04)

        self.entrynome = Entry(self.Main)
        self.entrynome.place(relx=0.25, rely=0.10, relwidth=0.40)
        self.lbnome = Label(self.Main, text='Nome', background='white')
        self.lbnome.place(relx=0.15, rely=0.10)

        self.entrytele = Entry(self.Main,
                               validate='key',
                               validatecommand=self.vdTele)
        self.entrytele.place(relx=0.25, rely=0.20, relwidth=0.40)
        self.lbtele = Label(self.Main, text='Telefone', background='white')
        self.lbtele.place(relx=0.15, rely=0.20)

        self.entryhora = Entry(self.Main,
                               validate='key',
                               validatecommand=self.vdhora)
        self.entryhora.place(relx=0.25, rely=0.30, relwidth=0.05)
        self.lbhora = Label(self.Main, text='Hora', background='white')
        self.lbhora.place(relx=0.15, rely=0.30)

        self.entrydata = Entry(self.Main)
        self.entrydata.place(relx=0.40, rely=0.30, relwidth=0.10)
        self.lbdata = Label(self.Main, text='Data', background='white')
        self.lbdata.place(relx=0.35, rely=0.30)

        self.bt_calendario = Button(self.Main,
                                    text='Calendario',
                                    command=self.Calendario)
        self.bt_calendario.place(relx=0.55, rely=0.30)

        self.bt_altera = Button(self.Main,
                                text='Alterar',
                                command=self.Alteraagenda)
        self.bt_altera.place(relx=0.65, rely=0.30)

    def Salvar(self):
        dataini = self.cal.get_date()
        self.entrydata.delete(0, END)
        self.entrydata.insert(END, dataini)
        self.conecta_bd()
        self.conn.execute(
            '''
        insert into Agendas (NOME_CLIENTE,TELEFONE,DATA,HORA) values (?,?,?,?)''',
            (self.entrynome.get(), self.entrytele.get(), self.entrydata.get(),
             self.entryhora.get()))
        self.conn.commit()
        self.desconecta_bd()
        self.limpa_cliente()
        self.entrynome.destroy()
        self.lbnome.destroy()
        self.entryhora.destroy()
        self.lbhora.destroy()
        self.entrytele.destroy()
        self.lbtele.destroy()
        self.entrydata.destroy()
        self.lbdata.destroy()
        self.bt_calendario.destroy()
        self.btsalva.destroy()
        self.cal.destroy()
        self.entry_cod.destroy()
        self.bt_altera.destroy()
        self.bt_fechar.destroy()
        self.Tarefas()

    def OnDoubleClick(self, event):
        self.limpa_cliente()
        self.listaCli.selection()

        for n in self.listaCli.selection():
            col1, col2, col3, col4, col5 = self.listaCli.item(n, 'values')
            self.entry_cod.insert(END, col1)
            self.entrynome.insert(END, col2)
            self.entrytele.insert(END, col3)
            self.entrydata.insert(END, col4)
            self.entryhora.insert(END, col5)

    def Tarefas(self):
        self.listaCli.delete(*self.listaCli.get_children())
        self.conecta_bd()
        dia = self.data_e_hora = strftime('%d/%m/%Y')
        lista = self.conn.execute('''
       SELECT * FROM Agendas where data like ('%s')ORDER BY NOME_CLIENTE ASC'''
                                  % dia)
        for i in lista:
            self.listaCli.insert("", END, values=i)
        self.desconecta_bd()
        self.limpa_cliente()

    def VerMes(self):
        self.Agendar()
        self.listaCli.delete(*self.listaCli.get_children())
        self.conecta_bd()
        meses = self.data_e_hora = strftime('/%m/%Y')
        mes = ('%') + meses
        lista = self.conn.execute('''
        SELECT * FROM Agendas where data like ('%s')ORDER BY data ASC''' % mes)
        for i in lista:
            self.listaCli.insert("", END, values=i)
        self.desconecta_bd()

    def Notas(self):
        print('Atualizando')

    def Validaentrada(self):
        self.vdhora = (self.root.register(self.ValidaHora), "%P")
        self.vdTele = (self.root.register(self.ValidaTele), "%P")

    def Alteraagenda(self):

        self.conecta_bd()
        self.conn.execute(
            '''UPDATE Agendas set NOME_CLIENTE=?,TELEFONE=?,DATA=?,HORA=? where COD=?''',
            (self.entrynome.get(), self.entrytele.get(), self.entrydata.get(),
             self.entryhora.get(), self.entry_cod.get()))
        self.conn.commit()
        self.desconecta_bd()
        self.limpa_cliente()
        self.Tarefas()

    def limpa_cliente(self):
        self.entry_cod.delete(0, END)
        self.entrynome.delete(0, END)
        self.entrytele.delete(0, END)
        self.entrydata.delete(0, END)
        self.entryhora.delete(0, END)
def dateEntryPage(*args):
    hourString = StringVar()
    minString = StringVar()

    #Function to retrieve the custom date and time values from the user
    def getDateValues():
        try:
            day = cal.selection_get()
            hour = hourString.get()
            minute = minString.get()
            SetDateToCustom(day.strftime("%A"), hour, minute)
        except ValueError:
            pass

    global flag
    flag = True

    today = datetime.date.today()
    mindate = datetime.date(
        today.year, today.month,
        today.day)  #sets minimum date on the calendar as todays date
    maxdate = datetime.date(year=2030, month=12,
                            day=30)  #sets maximum date on the calendar

    #commands to retrive an image from the system which will be used to design the various widgets present in the GUI
    selDate_back_img = Image.open(
        "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/OtherDates/selectdate.png"
    )
    Enter_Button_img = Image.open(
        "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/OtherDates/Enter_Button.png"
    )
    set_button_img = Image.open(
        "/Users/aneez.jah/Desktop/Y1S1 Coursework/Introduction to Computational Thinking/Mini Project/NSCanteenSystem/OtherDates/Set_Button.png"
    )
    selDate_Background = ImageTk.PhotoImage(selDate_back_img)
    Enter_Button = ImageTk.PhotoImage(Enter_Button_img)
    Set_Button = ImageTk.PhotoImage(set_button_img)

    s = ttk.Style()
    s.theme_use('clam')

    #initialization block for the widgets to be displayes to the user. Defines the various widgets and places them at an arbitrary location on the window
    customFrame = ttk.Frame(root, padding="0")
    background_label = Label(root, image=selDate_Background)
    background_label.image = selDate_Background  # this is to keep a copy of the image in the file
    enterButton = Button(root,
                         text="",
                         command=curStoresPage,
                         image=Enter_Button)
    setButton = Button(root,
                       text="Set",
                       command=getDateValues,
                       image=Set_Button)
    backButton = Button(root,
                        text="Go Back",
                        command=mainScreen,
                        image=back_button)
    cal = Calendar(root,
                   font="Arial 14",
                   selectmode='day',
                   locale='en_US',
                   mindate=mindate,
                   maxdate=maxdate,
                   disabledforeground='red',
                   cursor="hand1",
                   year=2018,
                   month=2,
                   day=5)
    hourEntry = ttk.Combobox(root,
                             values=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
                                     13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                                     23),
                             width=10,
                             textvariable=hourString,
                             state="readonly")
    hourEntry.current(9)  #sets the default value of the combobox
    minuteEntry = ttk.Combobox(
        root,
        values=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
                19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
                35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
                51, 52, 53, 54, 55, 56, 57, 58, 59),
        width=10,
        textvariable=minString,
        state="readonly")
    minuteEntry.current(29)  #sets default value of combobox
    endProg = Button(root, text="", command=leavePage, image=CloseButton)

    #Placement block for the widgets to be displayed to the user. Defines the coordinates on the window at which each widget should be placed
    customFrame.place()
    background_label.place(x=0, y=0, relwidth=1, relheight=1)
    enterButton.place(x=650, y=340, height=146, width=128)
    setButton.place(x=520, y=340, height=146, width=128)
    backButton.place(x=30, y=400, height=50, width=50)
    cal.pack(expand=False)
    cal.place(x=250, y=150)
    hourEntry.place(x=250, y=380)
    minuteEntry.place(x=420, y=380)
    endProg.place(x=740, y=20, height=34, width=40)
Пример #16
0
    def tab3_work():
        global tree2, net_var
        ntb.select(tab3)

        Label(tab3,
              text="Name",
              font=("Bahnschrift semiLight SemiCondensed", 17),
              relief=GROOVE,
              width=17,
              bd=3).place(x=100, y=10)
        Label(tab3,
              text="ID",
              font=("Bahnschrift semiLight SemiCondensed", 17),
              relief=GROOVE,
              width=17,
              bd=3).place(x=100, y=60)
        Label(tab3,
              text="Post",
              font=("Bahnschrift semiLight SemiCondensed", 17),
              relief=GROOVE,
              width=17,
              bd=3).place(x=100, y=110)
        Label(tab3,
              text="Total Working Days",
              font=("Bahnschrift semiLight SemiCondensed", 17),
              relief=GROOVE,
              width=17,
              bd=3).place(x=100, y=160)
        Label(tab3,
              text="Absent",
              font=("Bahnschrift semiLight SemiCondensed", 17),
              relief=GROOVE,
              width=17,
              bd=3).place(x=100, y=210)
        Label(tab3,
              text="Deduction/day",
              font=("Bahnschrift semiLight SemiCondensed", 17),
              relief=GROOVE,
              width=17,
              bd=3).place(x=100, y=260)
        Label(tab3,
              text="Total Deductions",
              font=("Bahnschrift semiLight SemiCondensed", 17),
              relief=GROOVE,
              width=17,
              bd=3).place(x=100, y=310)
        Label(tab3,
              text="Base Salary",
              font=("Bahnschrift semiLight SemiCondensed", 17),
              relief=GROOVE,
              width=17,
              bd=3).place(x=100, y=360)
        Label(tab3,
              text="Medical Pay",
              font=("Bahnschrift semiLight SemiCondensed", 17),
              relief=GROOVE,
              width=17,
              bd=3).place(x=100, y=410)
        Label(tab3,
              text="Bonus",
              font=("Bahnschrift semiLight SemiCondensed", 17),
              relief=GROOVE,
              width=17,
              bd=3).place(x=100, y=460)
        Label(tab3,
              text="Advance",
              font=("Bahnschrift semiLight SemiCondensed", 17),
              relief=GROOVE,
              width=17,
              bd=3).place(x=100, y=510)
        Label(tab3,
              text="Net Salary",
              font=("Bahnschrift semibold SemiCondensed", 17),
              relief=GROOVE,
              width=17,
              bd=3).place(x=720, y=250)

        cal = Calendar(tab3)
        cal.place(x=700, y=30, width=270, height=200)

        name_var = StringVar()
        id_var = StringVar()
        post_var = StringVar()
        deduct_per_day = IntVar()
        total_deduct = IntVar()
        absent = IntVar()
        base_var = IntVar()
        adv_var = IntVar()
        med_var = IntVar()
        bon_var = IntVar()
        net_var = IntVar()

        name_ent = Entry(tab3,
                         textvariable=name_var,
                         font=("Bahnschrift semiLight SemiCondensed", 17),
                         relief=SUNKEN,
                         state="readonly",
                         bd=3)
        id_ent = Entry(tab3,
                       textvariable=id_var,
                       font=("Bahnschrift semiLight SemiCondensed", 17),
                       relief=SUNKEN,
                       state="readonly",
                       bd=3)
        post_ent = Entry(tab3,
                         textvariable=post_var,
                         font=("Bahnschrift semiLight SemiCondensed", 17),
                         relief=SUNKEN,
                         state="readonly",
                         bd=3)
        total_days_ent = Entry(tab3,
                               font=("Bahnschrift semiLight SemiCondensed",
                                     17),
                               relief=SUNKEN,
                               bd=3)
        absent_ent = Entry(tab3,
                           textvariable=absent,
                           font=("Bahnschrift semiLight SemiCondensed", 17),
                           relief=SUNKEN,
                           bd=3)
        deduct_per_day_ent = Entry(tab3,
                                   textvariable=deduct_per_day,
                                   font=("Bahnschrift semiLight SemiCondensed",
                                         17),
                                   relief=SUNKEN,
                                   bd=3)
        total_deduct_ent = Entry(tab3,
                                 textvariable=total_deduct,
                                 state="readonly",
                                 font=("Bahnschrift semiLight SemiCondensed",
                                       17),
                                 relief=SUNKEN,
                                 bd=3)
        base_ent = Entry(tab3,
                         textvariable=base_var,
                         font=("Bahnschrift semiLight SemiCondensed", 17),
                         relief=SUNKEN,
                         bd=3)
        med_ent = Entry(tab3,
                        textvariable=med_var,
                        font=("Bahnschrift semiLight SemiCondensed", 17),
                        relief=SUNKEN,
                        bd=3)
        adv_ent = Entry(tab3,
                        textvariable=adv_var,
                        font=("Bahnschrift semiLight SemiCondensed", 17),
                        relief=SUNKEN,
                        bd=3)
        bon_ent = Entry(tab3,
                        textvariable=bon_var,
                        font=("Bahnschrift semiLight SemiCondensed", 17),
                        relief=SUNKEN,
                        bd=3)
        net_ent = Entry(tab3,
                        textvariable=net_var,
                        state="readonly",
                        font=("Bahnschrift semiLight SemiCondensed", 17),
                        relief=SUNKEN,
                        bd=3)
        name_ent.place(x=400, y=10)
        id_ent.place(x=400, y=60)
        post_ent.place(x=400, y=110)
        total_days_ent.place(x=400, y=160)
        absent_ent.place(x=400, y=210)
        deduct_per_day_ent.place(x=400, y=260)
        total_deduct_ent.place(x=400, y=310)
        base_ent.place(x=400, y=360)
        med_ent.place(x=400, y=410)
        adv_ent.place(x=400, y=460)
        bon_ent.place(x=400, y=510)
        net_ent.place(x=700, y=300)

        Button(tab3,
               text='Generate Slip',
               font=("Bahnschrift semiLight SemiCondensed", 17),
               command=pay_slip).place(x=740, y=350)
        select = tree2.item(tree2.selection())['values']

        emp_pers_data = sql_use.fetch_data(
            "emp_data", condition=f"emp_id='{select[1]}'")[0]
        emp_sal_data = sql_use.fetch_data("emp_salary",
                                          condition=f"id='{select[1]}'")[0]
        name_var.set(emp_pers_data[0])
        id_var.set(emp_pers_data[1])
        post_var.set(emp_pers_data[2])
        base_var.set(emp_sal_data[2])
        med_var.set(emp_sal_data[3])
        adv_var.set(emp_sal_data[4])
        bon_var.set(emp_sal_data[5])
        net_sal = base_var.get() + med_var.get() - adv_var.get() + bon_var.get(
        ) - total_deduct.get()
        net_var.set(net_sal)
        deduct_per_day_ent.bind(
            "<Key>", lambda event: total_deduct.set(absent.get() *
                                                    deduct_per_day.get()))
        absent_ent.bind(
            "<Key>", lambda event: total_deduct.set(absent.get() *
                                                    deduct_per_day.get()))
Пример #17
0
class Window(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)

        # initializing for input how many periods in a day
        self.period_input = Spinbox(from_=3, to=8, wrap=True)

        # initializing for putting the start day for the calendar.
        self.start_date_input = Calendar(font='Arial 10',
                                         showweeknumbers=False)
        self.skip_days_input = Calendar(font='Arial 10', showweeknumbers=False)
        self.skip_days_input.bind("<<CalendarSelected>>", self.date_add)

        self.skip_days = []

        # variable for the start date
        self.start_date = datetime.datetime

        self.teach_names = ""
        self.teach_input = Entry(textvariable=self.teach_names, width=20)

        # to create input for the title of the spreadsheet.
        self.title = ""
        self.title_input = Entry(
            textvariable=self.title,
            width=20,
        )
        self.title_input_label = Label(text='Name for the file.')

        # for day cycle amount
        self.day_cycle = Spinbox(from_=1, to=8, wrap=True)
        self.day_cycle_window = 1

        self.schedule_day_full = {}
        self.repeating_window_cycle = 1

        week_counter_default = StringVar()
        week_counter_default.set("44")
        self.week_counter = Spinbox(from_=1,
                                    to=52,
                                    wrap=True,
                                    textvariable=week_counter_default)
        self.week_counter_label = Label(text='Number of weeks:')

        self.master = master
        self.init_window()

    # Creation of window
    def init_window(self):
        # changing the title of our master widget
        self.master.title("Computer Lab Booking Generator")

        self.pack(fill=BOTH, expand=1)

        # creating a button to quit the program
        quit_button = Button(self, text="Quit", command=self.client_exit)
        quit_button.place(x=9, y=590)

        # To input the amount of periods in a school day.
        self.period_input.place(x=150, y=50, width=30)
        period_input_label = Label(text='Number of Periods')
        period_input_label.place(x=1, y=50)

        # button to run the generate the spreadsheet.
        generate_button = Button(self,
                                 text='Generate',
                                 command=self.open_window)
        generate_button.place(x=250, y=590)

        # placing the calendar to pick start date.
        self.start_date_input.place(x=25, y=150)
        self.skip_days_input.place(x=25, y=375)
        start_date_label = Label(
            text='Please select a day to start your schedule on.')
        start_date_label.place(x=1, y=125)

        # placing the input for teacher names and it's label.
        self.teach_input.place(x=150, y=25)
        teach_input_label = Label(text='Teachers Names: ')
        teach_input_label.place(x=1, y=25)

        skip_days_input_label = Label(
            text=
            ' Select days that there is no school(ie PD Days, Holidays, etc) ',
            justify='left')
        skip_days_input_label.place(x=1, y=350)

        self.title_input.place(x=150, y=1)
        self.title_input_label.place(x=1, y=1)
        self.title_input.insert(END, 'Lab Booking')

        self.day_cycle.place(x=150, y=75, width=30)
        day_cycle_label = Label(text='Number of days in a cycle:')
        day_cycle_label.place(x=1, y=73)

        # Check box. Will show the day on each date if checked.
        self.show_day_number_check = IntVar()
        show_day_number = Checkbutton(root,
                                      text="Show day number on each day",
                                      variable=self.show_day_number_check,
                                      onvalue=1,
                                      offvalue=0,
                                      height=1,
                                      width=25)
        show_day_number.place(x=1, y=557)

        # Spinbox for selecting how many weeks the program will run for
        self.week_counter.place(x=150, y=100, width=30)
        self.week_counter_label.place(x=1, y=100)

    @staticmethod
    def client_exit():
        exit()

    # to convert from a datetime to excels epoch time.
    def excel_date(self):
        offset = 693594
        self.start_date = datetime.datetime.strptime(
            self.start_date_input.get_date(), '%Y-%m-%d')
        n = self.start_date.toordinal()
        return n - offset

    # excel epoch for skip list.
    def excel_date_skip_list(self):
        offset = 693594
        self.start_date = datetime.datetime.strptime(
            self.skip_days_input.get_date(), '%Y-%m-%d')
        n = self.start_date.toordinal()
        return n - offset

    # displays the dates beside the calendar used to pick dates with no school.
    def display_dates(self):
        date_list = []
        for dates in self.skip_days:
            date_list.append(self.regular_date(self, dates))
            dates_list_label = Label(text=date_list,
                                     wraplength=225,
                                     justify='center').place(x=275, y=425)

    # converts from an excel epoch time to datetime.
    @staticmethod
    def regular_date(self, date):
        offset = 693594
        new_date = date + offset
        final_date = datetime.datetime.strftime(
            datetime.datetime.fromordinal(new_date), '%b %d %Y')
        return final_date

    # makes a list of teachers names that was input into the GUI.
    def make_teach_list(self):
        self.teach_names = self.teach_input.get()
        teach_list = self.teach_names
        teach_list = [x.strip() for x in teach_list.split(',')]

    # adds days to a list in excel format to check against for formatting and day cycle counts.
    def date_add(self, date):
        added_date = self.excel_date_skip_list()
        if added_date in self.skip_days:
            self.skip_days.remove(added_date)
            self.display_dates()
            return
        if added_date not in self.skip_days:
            self.skip_days.append(added_date)
            self.display_dates()

    # Opens window for modifying each day individually.
    def open_window(self):
        self.repeating_window = Toplevel(root)
        repating_sched_label = Label(
            self.repeating_window,
            text='Repeating Schedule for Day {}'.format(
                self.day_cycle_window)).grid(row=1, column=1)
        self.p1_input = Entry(self.repeating_window)
        self.p2_input = Entry(self.repeating_window)
        self.p3_input = Entry(self.repeating_window)
        self.p4_input = Entry(self.repeating_window)
        self.p5_input = Entry(self.repeating_window)
        self.p6_input = Entry(self.repeating_window)
        self.p7_input = Entry(self.repeating_window)
        self.p8_input = Entry(self.repeating_window)

        self.repeating_window.geometry("300x200+300+300")
        placement_y = 2
        next_day_button = Button(self.repeating_window,
                                 text='Next Day',
                                 command=self.next_day).grid(row=19, column=2)

        for i in range(1, int(self.period_input.get()) + 1):
            period_label_new_window = Label(self.repeating_window,
                                            text='Period {}'.format(i)).grid(
                                                row=placement_y, column=1)
            if i == 1:
                self.p1_input.grid(row=placement_y, column=2)
                self.p1_input.insert(END, "Name:")

            if i == 2:
                self.p2_input.grid(row=placement_y, column=2)
                self.p2_input.insert(END, "Name:")

            if i == 3:
                self.p3_input.grid(row=placement_y, column=2)
                self.p3_input.insert(END, "Name:")

            if i == 4:
                self.p4_input.grid(row=placement_y, column=2)
                self.p4_input.insert(END, "Name:")

            if i == 5:
                self.p5_input.grid(row=placement_y, column=2)
                self.p5_input.insert(END, "Name:")

            if i == 6:
                self.p6_input.grid(row=placement_y, column=2)
                self.p6_input.insert(END, "Name:")

            if i == 7:
                self.p7_input.grid(row=placement_y, column=2)
                self.p7_input.insert(END, "Name:")

            if i == 8:
                self.p8_input.grid(row=placement_y, column=2)
                self.p8_input.insert(END, "Name:")

            placement_y += 2

    # Brings up the next day, and stores the values into a dict.
    def next_day(self):
        self.schedule_day = {
            1: self.p1_input.get(),
            2: self.p2_input.get(),
            3: self.p3_input.get(),
            4: self.p4_input.get(),
            5: self.p5_input.get(),
            6: self.p6_input.get(),
            7: self.p7_input.get(),
            8: self.p8_input.get()
        }

        for i in range(1, len(self.schedule_day) + 1):
            if self.schedule_day.get(i) == 'Name:' or self.schedule_day.get(
                    i) == '':
                self.schedule_day.update({i: 'default'})
            i += 1
        self.schedule_day_full[self.repeating_window_cycle] = self.schedule_day
        self.repeating_window_cycle += 1
        self.day_cycle_window += 1
        self.repeating_window.destroy()
        self.open_window()

        if self.day_cycle_window == int(self.day_cycle.get()) + 1:
            self.repeating_window.destroy()
            self.generate()
            self.day_cycle_window = 1
            self.schedule_day_full = {}
            self.repeating_window_cycle = 1
            return 'None'

    # generates the excel spreadsheet.
    def generate(self):
        # Create a workbook and add a worksheet.
        workbook = xlsxwriter.Workbook('{}.xlsx'.format(
            self.title_input.get()))
        link_page = workbook.add_worksheet('Link Page')
        worksheet = workbook.add_worksheet("Week1")
        self.start_date = datetime.datetime.strptime(
            self.start_date_input.get_date(), '%Y-%m-%d')
        self.make_teach_list()
        # Start from the first cell. Rows and columns are zero indexed.
        first_date_link_page = 0
        row = 1
        col = 1

        # Starts Weeks at num 1
        week = 1

        day = 1

        # getting the excel epoch time for the start date.
        start_date_excel = self.excel_date()
        # Cell formats
        date_format = workbook.add_format({'num_format': 'd mmm yyy'})
        center_format = workbook.add_format()
        colour_format = workbook.add_format()
        bold_format = workbook.add_format()
        justify_format = workbook.add_format()
        center_format.set_center_across()
        colour_format.set_bg_color('red')
        bold_format.set_bold(True)
        justify_format.set_align('left')

        # variables to format the period cells.
        period_row = 2
        period_number = int(self.period_input.get())

        link_page_row = 1
        link_page_column = 0
        link_page.write("A1", "Click These")
        link_page.set_column(0, 0, width=15)
        link_page.set_column(1, 1, width=30)

        # Checks to see if the start day falls between a monday and friday.
        if self.start_date.isoweekday() <= 5:

            # title for the week.
            worksheet.write(0, 0, 'Week {}'.format(week))

            # writes all the periods along the side at the top.
            for p in range(1, (period_number + 1)):
                worksheet.write(period_row, 0, 'Period {}'.format(p))
                period_row += 1

            for q in range(self.start_date.isoweekday(), 6):
                worksheet.write(row, col, start_date_excel, date_format)
                worksheet.set_column(col, col, 18, center_format)

                # checks if this is the first day of the week.
                if q == self.start_date.isoweekday():
                    first_date_link_page = start_date_excel

                # sets for putting the information in the periods.
                period_row = 3

                # formats to a red column if no school that day.
                if start_date_excel in self.skip_days:
                    worksheet.write(2, col, 'No School', colour_format)
                    for h in range(0, period_number - 1):
                        worksheet.write(period_row, col, " ", colour_format)
                        period_row += 1
                        h += 1

                # formats cells to use a list provided by user.
                if start_date_excel not in self.skip_days:
                    period = 1
                    for j in range(0, period_number - 1):
                        if int(self.day_cycle.get()) == 1 or day > int(
                                self.day_cycle.get()):
                            day = 1
                        if self.schedule_day_full[day][period] == 'default':
                            if self.teach_names:
                                worksheet.data_validation(
                                    period_row - 1, col, period_row, col, {
                                        'validate': 'list',
                                        'source': [self.teach_names]
                                    })
                            period_row += 1
                            period += 1

                        else:
                            worksheet.write(
                                period_row - 1, col,
                                self.schedule_day_full[day][period],
                                justify_format)
                            period_row += 1
                            period += 1

                    if self.show_day_number_check.get() == 1:
                        worksheet.write(period_row, col, "Day {}".format(day),
                                        justify_format)
                    day += 1
                col += 1
                start_date_excel += 1
                q += 1

                # Adds internal link so that you can navigate from the first page of the document.
                if q == 5:
                    second_date_link_page = start_date_excel
                    link_page.write_url(link_page_row, link_page_column,
                                        "internal:Week{}!A1".format(week),
                                        center_format, 'Week{}'.format(week))

                    link_page.write_rich_string(
                        link_page_row, link_page_column + 1, date_format,
                        '{}'.format(
                            self.regular_date(self, first_date_link_page)),
                        ' until ', date_format, '{}'.format(
                            self.regular_date(self, second_date_link_page)))
                    link_page_row += 1

                # adds link to first page with all the links to pages.
                worksheet.write_url('A12', "internal:'Link Page'!A1",
                                    bold_format, "First Page")

            # creates new worksheet for the next week.
            week += 1
            worksheet = workbook.add_worksheet('Week{}'.format(week))

            # Adds two to account for the weekend.
            start_date_excel += 2

            # Resets variables for the next round. Because they need to be back in the same cells.
            row = 1
            col = 1
            period_row = 2

        #if the day picked is a saturday or sunday.
        elif self.start_date.isoweekday() == 6:
            start_date_excel += 2

        elif self.start_date.isoweekday() == 7:
            start_date_excel += 1

        # This is for all the following weeks.
        for r in range(1, int(self.week_counter.get())):
            # title for the week.
            worksheet.write(0, 0, 'Week {}'.format(week))

            # writes all the dates at the top.
            for p in range(1, (period_number + 1)):
                worksheet.write(period_row, 0, 'Period {}'.format(p))
                period_row += 1

            for i in range(0, 5):
                worksheet.write(row, col, start_date_excel, date_format)
                worksheet.set_column(col, col, 18, justify_format)
                # checks if this is the first day of the week.
                if i == 0:
                    first_date_link_page = start_date_excel

                # sets for putting the information in the periods.
                period_row = 3

                # formats to a red column if no school that day.
                if start_date_excel in self.skip_days:
                    worksheet.write(2, col, 'No School', colour_format)
                    for h in range(0, period_number - 1):
                        worksheet.write(period_row, col, " ", colour_format)
                        period_row += 1
                        h += 1

                # formats cells to use a list provided by user.
                if start_date_excel not in self.skip_days:
                    period = 1

                    for j in range(0, period_number - 1):
                        if int(self.day_cycle.get()) == 1 or day > int(
                                self.day_cycle.get()):
                            day = 1

                        if self.schedule_day_full[day][period] == 'default':
                            if self.teach_names:
                                worksheet.data_validation(
                                    period_row - 1, col, period_row, col, {
                                        'validate': 'list',
                                        'source': [self.teach_names]
                                    })
                            period_row += 1
                            period += 1

                        else:
                            worksheet.write(
                                period_row - 1, col,
                                self.schedule_day_full[day][period])
                            period_row += 1
                            period += 1

                    if self.show_day_number_check.get() == 1:
                        worksheet.write(period_row, col, "Day {}".format(day))
                    day += 1

                # iterates variables
                col += 1
                start_date_excel += 1
                i += 1

                # Adds internal link so that you can navigate from the first page of the document.
                if i == 4:
                    second_date_link_page = start_date_excel
                    link_page.write_url(link_page_row, link_page_column,
                                        "internal:Week{}!A1".format(week),
                                        center_format, 'Week{}'.format(week))

                    link_page.write_rich_string(
                        link_page_row, link_page_column + 1, date_format,
                        '{}'.format(
                            self.regular_date(self, first_date_link_page)),
                        ' until ', date_format, '{}'.format(
                            self.regular_date(self, second_date_link_page)))
                    link_page_row += 1

            week += 1

            # adds link to first page with all the links to pages.
            worksheet.write_url('A12', "internal:'Link Page'!A1", bold_format,
                                "First Page")

            # creates new worksheet for the next week.
            worksheet = workbook.add_worksheet('Week{}'.format(week))

            # Adds two to account for the weekend.
            start_date_excel += 2

            r += 1

            # Resets variables for the next round. Because they need to be back in the same cells.
            row = 1
            col = 1
            period_row = 2

        link_page.activate()
        try:
            workbook.close()

        except PermissionError:
            messagebox.showinfo(
                message=
                'There has been an error. Try closing the excel spreadsheet and trying again.'
            )
            return 'None'
        messagebox.showinfo(message='Completed. Thank you!')
        self.client_exit()
def init():#..........................................................................................................

	#-- GETTING THE DATE HERE THAT'S ALL
	with open('entered_data.txt', 'r') as text:  # create an output text file
		for line in text:
			entry = line

	items = line.split()

	entered_day = int(items[0].strip())  # remove whitespace characters i.e. '\n' at the start/end
	entered_mon = int(items[1].strip())
	entered_year = int(items[2].strip())
	date = datetime.datetime(entered_year, entered_mon, entered_day)  # year , month , day
	cal_selected_date = str(date.date())


	# -- MAKING GUI

	se_window.title('Search Engine')    	#Main window title
	x_screen = (se_window.winfo_screenwidth() // 2) - (css.frame_center_W)
	y_screen = (se_window.winfo_screenheight() // 2) - (css.frame_center_H) - 140

	width = css.frame_width + 140


	se_window.geometry("{}x{}+{}+{}".format( width , 970 , x_screen , y_screen ))	#Main window size & position
	se_window.config(bg=css.color_bg_newSession)
	se_window.resizable(False,False)

	x=120

	logo1 = PhotoImage(file = 'se.png')
	l_logo = Label(se_window, image=logo1, bg=css.color_bg_currentDate)
	l_logo.image = logo1
	l_logo.place(x=width/2, y = 15+x, anchor='center')

	# --- WELCOME INSTRUCTIONS LABEL widget ---
	label_1 = Label( se_window , width=60 , text='' , fg=css.color_text , bg=css.color_bg_newSession )
	label_1.place( x=width/2 , y=160+x , anchor='center' )
	label_1.config( font=( "Helvetica", 20 , "normal" ) )	# normal, bold, roman, italic, underline, and overstrike
	label_1.config( text=str('Please select the airports and date, then click search') )


	# --- SELECT FROM AIRPORT OPTION MENU widget ---
	#CONNECT TO DATABASE AND UPDATE THE FLIGHT LIST
	#conn = sqlite3.connect('Flight.db');

	conn = db.db_connect()
	sqlcode = "SELECT AIRPORTNAME FROM AIRPORTS"
	cursor = conn.execute(sqlcode).fetchall()
	from_option_List = []
	for row in cursor:
		from_option_List.append(row[0])
	conn.close()
	#from_option_List = ["all", "JFK", "LAG", "LAX", "DC", "DUB", "DFW"]	##### this must be populated from the SQLite3

	##### NEED THIS FUNCTION ################################################
	#PLEASE hardcode "all" as the 1st menu option
	#from_option_List = get_FROM_Airports()
	#########################################################################
	from_option_List.insert(0,'all')

	variable1 = StringVar(se_window)
	variable1.set("FROM")  # default value
	from_airport = OptionMenu(se_window, variable1, *from_option_List , command=from_selection )
	from_airport.config( font=( "Helvetica", 15 ) )
	from_airport.config( bg=css.color_bg_newSession , width=12 , fg=css.color_text)
	from_airport.place(x=width/3-15, y=200+x, anchor='center')


	# --- SELECT TO AIRPORT OPTION MENU widget ---
	# CONNECT TO DATABASE AND UPDATE THE FLIGHT LIST
	#conn = sqlite3.connect('Flight.db');

	conn = db.db_connect()
	sqlcode = "SELECT AIRPORTNAME FROM AIRPORTS"
	cursor = conn.execute(sqlcode).fetchall()
	to_option_List = []
	for row in cursor:
		to_option_List.append(row[0])
	conn.close()
	#to_option_List = ["all", "JFK", "LAG", "LAX", "DC", "DUB", "DFW"]	##### this must be populated from the SQLite3

	##### NEED THIS FUNCTION ################################################
	#PLEASE hardcode "all" as the 1st menu option
	#to_option_List = get_TO_Airports()
	#########################################################################
	to_option_List.insert(0,'all')

	variable2 = StringVar(se_window)
	variable2.set("TO")
	to_airport = OptionMenu(se_window, variable2, *to_option_List , command=to_selection )
	to_airport.config( font=( "Helvetica", 15 ) )
	to_airport.config( bg=css.color_bg_newSession , width=12 , fg=css.color_text)
	to_airport.place(x=width/2, y=200+x, anchor='center')


	# --- SELECT SORTING OPTION MENU widget ---
	flights_table_names = get_table_colNames() ;
	sort_option_List = flights_table_names #e.g. sort_option_List = ["Airline_ID", "From_Airport" , "To_Airport" , "Airline" ]
	variable3 = StringVar(se_window)
	variable3.set("SORT BY")
	sort = OptionMenu(se_window, variable3, *sort_option_List , command=sort_selection  )
	sort.config( font=( "Helvetica", 15 ) )
	sort.config( bg=css.color_bg_newSession , width=12 , fg=css.color_text)
	sort.place(x=width-(width/3)+15, y=200+x, anchor='center')


	# CALENDAR SECTION ..................................................
	cal = Calendar(se_window,
				   font="Arial 14", selectmode='day',
				   year=entered_year, month=entered_mon, day=entered_day, showweeknumbers=False, mindate= date)


	# style = ttk.Style(cal)
	# style.theme_use('calm')
	cal.place(x = width/2, y=320+x, anchor='center')


	results = Text(se_window, width=90, height=10, fg=css.color_text, bg=css.color_bg_reservations, yscrollcommand = set())
	results.config(font=("Helvetica", 16, "normal"))
	results.config(state=NORMAL)
	results.place(x=width/2, y=575 + x, anchor='center')
	results.insert(END,"RESULTS WILL PRINT HERE")
	results.configure(state='disabled')

	def calendar_select():
		global cal_selected_date
		cal_selected_date = str(cal.selection_get())
		print(cal_selected_date)

	def print_search_results(): # MAKES THE SEARCH RESULTS AND ADDS IT TO THE MAIN GUI WINDOW
		calendar_select()
		content = populate_window()
		results.config(state=NORMAL)
		results.delete('1.0', END)
		results.insert(END,content)
		results.configure(state='disabled')	
		book_Btn.config(text='Book Flight')
		book_Btn.config(state='normal')		# must be active, disabled, or normal
	# END CALENDAR SECTION .............................................


	# --- ENTER FLIGHT ID widget
	label_2 = Label( se_window , width=20 , text='' , fg=css.color_text , bg=css.color_bg_newSession )
	label_2.place( x=(width/2)-60 , y=706+x , anchor='center' )
	label_2.config( font=( "Helvetica", 20 , "normal" ) )	# normal, bold, roman, italic, underline, and overstrike
	label_2.config( text=str('Enter Flight ID') )


	# --- FLIGHT ID ENTRY widget ---
	entry_ID = Entry( se_window, show=None, width=5, bg='#FFFFFF', fg=css.color_placeholder, exportselection=0, justify='center')
	entry_ID.config( font=( "Helvetica", 20 , "normal" ) )
	entry_ID.bind('<Return>', lambda args: enter_keyboardkKey(entry_ID) )
	#entry_ID.bind('<KeyRelease>', lambda args: enter_keyboardkKey(entry_ID) ) # for dynamic realtime feedback capture
	entry_ID.bind("<FocusIn>", lambda args: entry_ID_click( entry_ID))
	entry_ID.bind("<FocusOut>", lambda args: entry_ID_check(entry_ID,label_3,book_Btn))
	entry_ID.insert(0, '0')
	entry_ID.place( x=(width/2)+48 , y=705+x , anchor='center') # alternative to entry_ID.pack()
	#entry_ID.focus_set() # to automatically focus on the widget at start up


	# --- SELECTED FLIGHT ID widget ---
	label_3 = Label( se_window , width=85 , text='' , fg=css.color_text , bg=css.color_bg_newSession )
	label_3.place( x=width/2 , y=747+x , anchor='center' )
	label_3.config( font=( "Helvetica", 16 , "normal" ) )	# normal, bold, roman, italic, underline, and overstrike
	label_3.config( text='' )


	# --- SEARCH BUTTON widget ---
	searchButton = Button( se_window , width=15, text='SEARCH', fg=css.color_text, bg=css.color_btn )
	searchButton.config( highlightbackground=css.color_bg_newSession )
	searchButton.config( font=( "Helvetica", 20 , "bold" ) )
	searchButton.config( bd=8, relief='raised' )
	searchButton.config( command=print_search_results )
	searchButton.place( x=width/2 , y=445+x , anchor='center')


	# --- BOOK FLIGHT BUTTON widget ---
	book_Btn = Button( se_window , width=15, text='Book Flight', fg=css.color_text, bg=css.color_btn, relief='ridge' )
	book_Btn.config( highlightbackground=css.color_bg_newSession )
	book_Btn.config( font=( "Helvetica", 20 , "bold" ) )
	book_Btn.config( bd=8, relief='raised' )					# flat, groove, raised, ridge, solid, or sunken
	book_Btn.config( command=lambda: btn_click_bookFlight(label_3,book_Btn) )
	#book_Btn.config( command=book)
	#book_Btn.bind('<Button-1>', hide_me)
	#book_Btn.place( x=css.frame_center_W , y=785+x , anchor='center')
	btn_visibility_toggle( book_Btn , False)


	# --- LOG-IN BUTTON widget ---
	login_Btn = Button(se_window, width=10, text='admin', fg=css.color_text, bg=css.color_btn)
	login_Btn.config( highlightbackground=css.color_bg_newSession )
	login_Btn.config(font=("Helvetica", 15, "bold"))
	login_Btn.config(bd=8, relief='raised')  # flat, groove, raised, ridge, solid, or sunken
	login_Btn.config(command=btn_click_LogIn)  # calls btn_click_LogIn() when the button is clicked
	login_Btn.place(x=100, y=26, anchor='center')

	# --- LOGGED IN USER LABEL widget ---
	label_user = Label( se_window , width=15 , text='' , fg=css.color_text , bg=css.color_bg_newSession )
	label_user.place( x=width-100 , y=26 , anchor='center' )
	label_user.config( font=( "Helvetica", 16 , "bold" ) )	# normal, bold, roman, italic, underline, and overstrike
	label_user.config( text=str("user: "******"WM_DELETE_WINDOW", on_closing)