Exemple #1
0
    def test_calendar_virtual_events(self):
        widget = Calendar(self.window, year=2010, month=1, day=3)
        widget.pack()
        self.window.update()

        self.event_triggered = False

        def binding(event):
            self.event_triggered = True

        widget.bind('<<CalendarSelected>>', binding)
        widget._on_click(TestEvent(widget=widget._calendar[2][1]))
        self.window.update()
        self.assertTrue(self.event_triggered)

        widget.bind('<<CalendarMonthChanged>>', binding)
        self.event_triggered = False
        widget._l_month.invoke()
        self.window.update()
        self.assertTrue(self.event_triggered)
        self.event_triggered = False
        widget._r_month.invoke()
        self.window.update()
        self.assertTrue(self.event_triggered)
        self.event_triggered = False
        widget._l_year.invoke()
        self.window.update()
        self.assertTrue(self.event_triggered)
        self.event_triggered = False
        widget._r_year.invoke()
        self.window.update()
        self.assertTrue(self.event_triggered)
Exemple #2
0
 def bind(self, *args):
     Calendar.bind(self, *args)
     header = self._header_month.master.master
     header.bind(*args)
     for widget in header.children.values():
         widget.bind(*args)
         for w in widget.children.values():
             w.bind(*args)
class MyCalendar(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        #Create calendar
        self.cal = Calendar(self,
                            font="Arial 14",
                            selectmode='day',
                            tooltipforeground='black',
                            tooltipbackground='pink',
                            tooltipalpha='1',
                            tooltipdelay='0')
        date = self.cal.datetime.today()

        #Add in events
        self.cal.c1 = self.cal.calevent_create(
            date + self.cal.timedelta(days=5), "F**k me in the ass", 'message')
        self.cal.calevent_create(date, 'Bake cookies at 3am', 'reminder')
        self.cal.calevent_create(date + self.cal.timedelta(days=-2),
                                 'Date at McDonalds', 'reminder')
        self.cal.calevent_create(date + self.cal.timedelta(days=3),
                                 'Mine Diamonds with Jimothy', 'message')

        #Set calendar and adjust colours
        self.cal.tag_config('reminder', background='red', foreground='yellow')
        self.cal.pack(fill="both", expand=True)

        #Set status/tool tip bar
        self.l2 = tk.Label(self,
                           text="Click on a date to check for events!",
                           width=40)
        self.l2.pack(side="bottom")

        #Executes "set_date" when a day is clicked
        self.cal.bind("<<CalendarSelected>>", self.set_date)

    def set_date(self, event):

        #Get the date clicked
        self.date = self.cal.get_date()

        #Convert date from string format to datetime object format
        self.DTObject = datetime.strptime(self.date, '%m/%d/%y')

        #Get tuple of events on the date clicked
        self.eventslist = self.cal.get_calevents(self.DTObject)

        #If there >0 events, display first event on status/tool tip bar
        if len(self.eventslist) > 0:
            self.l2.configure(
                text=self.cal.calevents[self.eventslist[0]]["text"])

        #Display no events
        else:
            self.l2.configure(text="No events for " + self.date)
class AddNewProjection(Tk):
    def __init__(self, userdetails={}):
        Tk.__init__(self)

        self.userdetails = userdetails

        self.listOfMovies = getAllMovie()
        self.listOfMoviesNames = []

        self.listOfAuditorium = getAllScreens()
        self.listOfAuditoriumIDS = []

        self.selectedStartDate = str(datetime.datetime.today().date())

        if self.listOfMovies == None:
            messagebox.showerror(
                'Error',
                "No Moive Exits ,Please add movie before adding projection")
            self.destroy()

        elif self.listOfAuditorium == None:
            messagebox.showerror(
                'Error',
                "No Auditorium Exits ,Please add Auditorium before adding projection"
            )
            self.destroy()
        else:
            for row in self.listOfMovies:
                self.listOfMoviesNames.append(row[1])

            for row in self.listOfAuditorium:
                self.listOfAuditoriumIDS.append(row[0])
            self.onCreate()

    def onCreate(self):
        HEIGHT = 800
        WIDTH = 800
        canvas = Canvas(self, height=HEIGHT, width=WIDTH)
        canvas.pack()
        frame = Frame(canvas, bg="grey")
        frame.place(relx=0.01, rely=0.01, relwidth=0.98, relheight=0.98)

        Label(frame, text="Add New Projection",
              font=("Helvetica", 12)).grid(row=0,
                                           columnspan=2,
                                           pady=15,
                                           padx=15)

        Label(frame, text="Select Movie: ").grid(row=1, pady=10)
        Label(frame, text="Select Auditorium/Screen: ").grid(row=2, pady=10)
        Label(frame, text="Select Date : ").grid(row=3, pady=10)
        Label(frame, text="Select Start Time: ").grid(row=4, pady=10)
        Label(frame, text="Select End Time: ").grid(row=5, pady=10)

        self.moviesChkbox = ttk.Combobox(master=frame)
        self.moviesChkbox['values'] = self.listOfMoviesNames
        self.moviesChkbox.grid(row=1, column=1, pady=10)

        self.auditoriumChkbox = ttk.Combobox(master=frame)
        self.auditoriumChkbox['values'] = self.listOfAuditoriumIDS
        self.auditoriumChkbox.grid(row=2, column=1, pady=10)

        self.date_picker = Calendar(master=frame,
                                    date_pattern='y-mm-dd',
                                    mindate=datetime.datetime.today())
        self.date_picker.bind('<<CalendarSelected>>', self.setStartDate)
        self.date_picker.grid(row=3, column=1, pady=10)

        self.startVariable = StringVar(master=frame, value="HH:MM:SS")
        self.endVariable = StringVar(master=frame, value="HH:MM:SS")

        self.startTime_entry = Entry(master=frame,
                                     textvariable=self.startVariable)
        self.endTime_entry = Entry(master=frame, textvariable=self.endVariable)

        self.startTime_entry.grid(row=4, column=1, pady=10)
        self.endTime_entry.grid(row=5, column=1, pady=10)

        Label(frame,
              text="24Hrs Format (%H:%M:%S) eg (16:30:00)").grid(row=4,
                                                                 column=2,
                                                                 pady=10)
        Label(frame,
              text="24Hrs Format (%H:%M:%S) eg(12:00:00)").grid(row=5,
                                                                column=2,
                                                                pady=10)

        submit_btn = Button(master=frame,
                            text=" Submit ",
                            command=self.onSubmitPressed)
        submit_btn.grid(row=6, column=0, columnspan=3, pady=10)

    def onSubmitPressed(self):
        if self.selectedStartDate == None or self.startVariable.get(
        ) == "HH:MM:SS" or self.endVariable.get() == "HH:MM:SS":
            messagebox.showerror(
                "Invalid Input",
                "All fields are mandatory plaese fill them correctly")

        else:
            startdatetime_str = str(self.selectedStartDate) + " " + str(
                self.startVariable.get())
            enddatetime_str = str(self.selectedStartDate) + " " + str(
                self.endVariable.get())

            try:
                startdatetime = datetime.datetime.strptime(
                    startdatetime_str, "%Y-%m-%d %H:%M:%S")
                enddatetime = datetime.datetime.strptime(
                    enddatetime_str, "%Y-%m-%d %H:%M:%S")
            except:
                messagebox.showerror("Invalid Time Input",
                                     "PLease enter times carefully")
                return
            movieID = self.listOfMovies[self.moviesChkbox.current()][0]
            auditorium_ID = self.listOfAuditoriumIDS[
                self.auditoriumChkbox.current()]
            available_seats = self.listOfAuditorium[
                self.auditoriumChkbox.current()][1]

            msg = AddNewProjectionToDB(movie_ID=movieID,
                                       auditorium_ID=auditorium_ID,
                                       startTime=startdatetime,
                                       endTime=enddatetime,
                                       available_seats=available_seats,
                                       total_seats=available_seats)
            if msg[0] == 0:
                messagebox.showinfo("Success", msg[1])
                self.destory()

            if msg[0] == 1:
                messagebox.showerror("Error", msg[1])

    def setStartDate(self, *args):
        self.selectedStartDate = self.date_picker.get_date()
        print(self.selectedStartDate)

    def start(self):
        self.mainloop()

    def destory(self):
        self.destroy()
Exemple #5
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()
               font="fixedsys 14",
               selectmode="day",
               locale="en_US",
               cursor="sizing",
               background="white",
               disabledbackground="white",
               bordercolor="pink",
               headersbackground="bisque2",
               normalbackground="black",
               foreground="bisque4",
               normalforeground="bisque4",
               headersforeground="bisque4")

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

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

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

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

#Scrollbar Settings
scrollBar = tk.Scrollbar(root, orient="vertical", command=treev.yview)
scrollBar.grid(row=0, column=3, sticky="ENS", rowspan=4)
treev.configure(yscrollcommand=scrollBar.set)
Exemple #7
0
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)

cal = Calendar(
    root,
    font="Arial 25",
    locale='en_US',
    showweeknumbers=False,
    showothermonthdays=False,
)
entry = ttk.Entry(root)
btn = ttk.Button(root, text="Choose file", command=OnChooseFile)
btn_parse = ttk.Button(root, text="Parse", command=OnParse)

cal.grid(row=0,
         column=0,
         rowspan=8,
         columnspan=8,
         sticky=tk.N + tk.S + tk.W + tk.E)
entry.grid(row=8, column=0, columnspan=7, sticky=tk.W + tk.E)
btn.grid(row=8, column=7)
btn_parse.grid(row=9, column=0, rowspan=1, columnspan=8)

cal.bind("<<CalendarSelected>>", OnSelected)
cal.bind("<<CalendarMonthChanged>>", OnMonthChanged)

cal.tag_config('reminder', background='deep pink',
               foreground='white')  #background='royal blue'

root.mainloop()
Exemple #8
0
class Page4(tk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller

        #assignment functions to make variables out of user selection
        def date_assign(e):
            global vacDay
            vacDay = str(self.cal.get_date())
            return

        def time_assign(e):
            global vacTime
            vacTime = str(self.cb1.get())
            return

        def loc_assign(e):
            global vacLoc
            vacLoc = str(self.cb2.get())
            return

        tk.Frame.__init__(self, parent)
        self.configure(bg="#000000")
        self.button1 = ImageTk.PhotoImage(Image.open("images/greybutton.png"))
        #Calendar section, set to day selection
        self.cal = Calendar(self, selectmode='day', date_pattern='y/mm/dd')
        self.cal.pack(fill="both", expand=True)

        #Time Slot section
        self.var1 = tk.StringVar()
        self.var2 = tk.StringVar()
        options = ["none"]
        places = ["What Site?", "Location1", "Location2"]
        self.cb1 = ttk.Combobox(self, textvariable=self.var1, values=options)
        self.cb2 = ttk.Combobox(self, textvariable=self.var2, values=places)
        self.cb1.current(0)
        self.cb2.current(0)

        #both the calender and combobox are bound to selection events
        self.cal.bind("<<CalendarSelected>>", date_assign)
        self.cb1.bind("<<ComboboxSelected>>", time_assign)
        self.cb2.bind("<<ComboboxSelected>>", loc_assign)

        # button to show frame 2 with text
        # layout2
        button1 = tk.Button(self,
                            text="StartPage",
                            image=self.button1,
                            bd=0,
                            bg="#000000",
                            highlightthickness=0,
                            compound="center",
                            command=lambda: controller.show_frame(StartPage))

        # putting the button in its place
        # by using pack
        button1.pack(side="left")
        self.cb1.pack(side="left")
        # button to show frame 2 with text
        # layout2
        button2 = tk.Button(self,
                            text="Next",
                            image=self.button1,
                            bd=0,
                            bg="#000000",
                            highlightthickness=0,
                            compound="center",
                            command=lambda: controller.show_frame(Page12))

        # putting the button in its place by
        # using pack
        button2.pack(side="right")
        self.cb2.pack(side="right")
Exemple #9
0
class DateFrame(Frame):
    """
     DateFrame class creates:
    | ◉ Today     ○ Pick Date  |      # Pick Date displays a calendar
    |    Date: 04/06/2021      |
    """
    def __init__(self, root):
        self.root = root
        super().__init__(self.root, bg=BACKGROUND_COLOR)
        self.date_pattern = DATE_PATTERN
        self.date_to_pixela = pixela_today  # '20210406'
        self.calendar = Calendar(self,
                                 font='Arial 8',
                                 background='#000080',
                                 showweeknumbers=False,
                                 weekendforeground='#000000',
                                 weekendbackground='#ffffff',
                                 date_pattern=self.date_pattern,
                                 othermonthwebackground='#ffffff',
                                 othermonthbackground='#ffffff')
        # ◉Today
        self.today = Radiobutton(self,
                                 command=self.set_today,
                                 text="Today ",
                                 value=0,
                                 variable=radio_state,
                                 bg=BACKGROUND_COLOR)
        self.today.grid(row=0, column=0, sticky='w')

        # ◉Pick Date
        self.pick_date = Radiobutton(self,
                                     command=self.show_calendar,
                                     text="Pick Date",
                                     value=1,
                                     variable=radio_state,
                                     bg=BACKGROUND_COLOR)
        self.pick_date.grid(row=0, column=1, sticky='w')

        # Date:  {04/06/2021}
        Label(self, text="Date: ", bg=BACKGROUND_COLOR, padx=10).grid(row=1,
                                                                      column=0)
        self.main_date = Label(self,
                               text="",
                               bg=BACKGROUND_COLOR,
                               font=('Arial', 12, 'bold'))
        self.main_date.grid(row=1, column=1, sticky='w')

        self.set_today()  # output today's date right away

    def change_date_pattern(self, option):  # to be used by Options in MainMenu
        self.date_pattern = option
        self.calendar = Calendar(self,
                                 font='Arial 8',
                                 background='#000080',
                                 showweeknumbers=False,
                                 weekendforeground='#000000',
                                 weekendbackground='#ffffff',
                                 date_pattern=option,
                                 othermonthwebackground='#ffffff',
                                 othermonthbackground='#ffffff')

        keep_format = messagebox.askyesno(
            title="Keep Format",
            message="Do you wish to keep this date format \n"
            "for the next times you open this program?")
        if keep_format:
            with shelve.open(filename="user_options") as sf:
                sf["date_pattern"] = option

        self.set_today()

    def display(self, date):
        self.calendar.grid_forget()
        self.main_date.config(text=date)

    def set_today(self):
        self.date_to_pixela = pixela_today  # set back TODAY for pixe.la and display it
        if self.date_pattern == 'mm/dd/yyyy':
            self.display(today.strftime("%m/%d/%Y"))
        elif self.date_pattern == 'dd/mm/yyyy':
            self.display(today.strftime("%d/%m/%Y"))
        else:
            self.display(today.strftime("%Y/%m/%d"))

    def show_calendar(
            self
    ):  # displays new date label, at every click, and hides calendar
        self.calendar.grid(row=2, column=0, columnspan=2, sticky='w')

        def format_day_from_calendar(event):  # won't work without "event" (?)
            date = self.get_pixela_date_from_calendar()
            self.display(date)

        self.calendar.bind("<<CalendarSelected>>", format_day_from_calendar)

    def get_pixela_date_from_calendar(self):
        get_date = self.calendar.get_date(
        )  # format retrieved depends on self.date_pattern
        date = get_date.split('/')
        if self.date_pattern == 'mm/dd/yyyy':
            self.date_to_pixela = ''.join([date[2], date[0], date[1]])
        elif self.date_pattern == 'dd/mm/yyyy':
            self.date_to_pixela = ''.join([date[2], date[1], date[0]])
        else:  # asian
            self.date_to_pixela = ''.join(date)
        return get_date
Exemple #10
0
class CallLogWindow:
    
    edit_track = 'N'                    #This variable storing stste, to allow us to track if text is disbaled (N) or normal (Y)
    cur_active = None               #We start in neutral selection mode ---- (there is no  activated Listbox)
    
    
    def __init__(self, parent, *args, **kwargs):
        self.parent = parent 
        #self.database_init()
      
        
        #Menu Creation 
        #----------------------------------------------------------------------------------------------------------
        self.calllog_menu = tk.Menu(self.parent, background = '#0C1021', foreground='white', activebackground= DGR, activeforeground='white')

        self.writemenu = tk.Menu(self.calllog_menu, tearoff=0, background='#0C1021', foreground='white', activebackground='dark goldenrod', activeforeground='white')
        self.writemenu.add_command(label="Write Log to File", command = lambda: self.write_to_file()) 

        self.calllog_menu.add_cascade(label="Write Log", menu = self.writemenu)

        
        #STATE CHOICE 
        #---------------------------------------------------------------------------------------------------------
        self.resetmenu = tk.Menu(self.calllog_menu, tearoff = 0, background='#0C1021', foreground='white', activebackground='dark goldenrod', activeforeground='white')
        self.resetmenu.add_command(label = "Reset Call File", command = lambda: None) #self.reset_log_protocol())

        self.calllog_menu.add_cascade(label = "Reset", menu = self.resetmenu)


        #LOAD DATABASE
        #---------------------------------------------------------------------------------------------------------
        self.loadmenu = tk.Menu(self.calllog_menu, tearoff = 0, background='#0C1021', foreground='white', activebackground='dark goldenrod', activeforeground='white')
        self.loadmenu.add_command(label = "New DB", command = lambda:  None)  #self.ask_db_filename())      #self.new_database())
        self.loadmenu.add_command(label = "Load Database", command = lambda: None)  #self.open_db_file())           #self.Database('START'))
        self.loadmenu.add_command(label = "Add Note", command = lambda: None) #self.check_if_db_open())       #add_note_to_db())
        
        self.calllog_menu.add_cascade(label = "Load", menu = self.loadmenu)
        
        #Help Menu 
        #--------------------------------------------------------------------------------------------------------
        self.helpmenu = tk.Menu(self.calllog_menu, tearoff = 0, background='#0C1021', foreground='white', activebackground='dark goldenrod', activeforeground='white')
        self.helpmenu.add_command(label = "Tips on Apps Usage", command = lambda: None) 
        
        self.calllog_menu.add_cascade(label = "Help", menu = self.helpmenu)


        #Testing - Print feature
        #--------------------------------------------------------------------------------------------------------
        self.testmenu = tk.Menu(self.calllog_menu, tearoff = 0, background='#0C1021', foreground='white', activebackground='dark goldenrod', activeforeground='white')
        self.testmenu.add_command(label = "Print Mon", command = lambda: self.test_print('MONDAY')) 
        self.testmenu.add_command(label = "Print Tue", command = lambda: self.test_print('TUESDAY'))
        self.testmenu.add_command(label = "Print Wed", command = lambda: self.test_print('WED'))
        self.testmenu.add_command(label = "Print Thur", command = lambda: self.test_print('THURSDAY')) 
        self.testmenu.add_command(label = "Print Fri", command = lambda: self.test_print('FRIDAY'))        
        
        self.calllog_menu.add_cascade(label = "Test", menu = self.testmenu)        




        #LOAD TO WINDOW
        # ----------------------------------------------------------------------------------------------------------
        self.parent.config(bg='#0C1021', menu = self.calllog_menu)
        
       
       
       
       
        #Widget Frames
        # ----------------------------------------------------------------------------------------------------------
        self.display_frame = tk.Frame(self.parent,  bg = BG)
        self.display_frame.grid(row = 0, column = 0, sticky = tk.NS)
        
        self.selection_frame = tk.Frame(self.parent,  bg =  BG)
        self.selection_frame.grid(row = 0, column = 1, columnspan = 2,  sticky = tk.NS)        
                
        self.todo_frame = tk.Frame(self.parent,  bg =  BG)
        self.todo_frame.grid(row = 0, column = 3, columnspan = 2,  sticky = tk.NS)            
       
    
    
    
    
        #Label Creation
        # ----------------------------------------------------------------------------------------------------------
        self.lab_accounts = tk.Label(self.display_frame, text = 'Accounts',  bg = BG, fg = FG, 
                              font = ('Verdana', 20, 'bold'))
        self.lab_accounts.grid(row = 0, column = 0 , padx = 5, pady = 5, sticky = tk.EW)
        
        self.lab_selection= tk.Label(self.selection_frame, text = 'Selection',  bg = BG, fg = FG,
                               font = ('Verdana', 20, 'bold'))        
        self.lab_selection.grid(row = 0, column = 0 , columnspan = 2,  padx = 5, pady = 5, sticky = tk.EW) 
        
        
        
        ### Automate labelframe creation w/ widget
        #-----------------------------------------------------------------------------------------------------------
        self.mon_labelframe = tk.LabelFrame(self.display_frame, text = 'MONDAY', 
                                            bg =  BG,  fg =  FG, font = ('Verdana',8,'bold'), cursor = 'hand2')
        self.mon_labelframe.grid(row = 1, padx = 3, pady = 3, sticky = tk.NS)
        self.mon_lbox = tk.Listbox(self.mon_labelframe, height = 5, width = 30, bg = BG, fg = FG)
        self.mon_lbox.grid(padx = 5, pady = 5)
        
        self.tue_labelframe = tk.LabelFrame(self.display_frame, text = 'TUESDAY', 
                                            bg =  BG,  fg =  FG, font = ('Verdana',8,'bold'), cursor = 'hand2')
        self.tue_labelframe.grid(row = 2 ,padx = 3, pady = 3, sticky =  tk.NS)
        self.tue_lbox = tk.Listbox(self.tue_labelframe, height = 5, width = 30, bg = BG, fg = FG)
        self.tue_lbox.grid(padx = 5, pady = 5)
        
        self.wed_labelframe = tk.LabelFrame(self.display_frame, text = 'WED', 
                                            bg =  BG,  fg =  FG,  font = ('Verdana',8,'bold'), cursor = 'hand2')
        self.wed_labelframe.grid(row = 3, padx = 3, pady = 3, sticky =  tk.NS)
        self.wed_lbox = tk.Listbox(self.wed_labelframe, height = 5, width = 30, bg = BG, fg = FG)
        self.wed_lbox.grid(padx = 5, pady = 5)        
        
        self.thur_labelframe = tk.LabelFrame(self.display_frame, text = 'THURSDAY', 
                                             bg =  BG,  fg =  FG,  font = ('Verdana',8,'bold'), cursor = 'hand2')
        self.thur_labelframe.grid(row = 4, padx = 3, pady = 3, sticky =  tk.NS)
        self.th_lbox = tk.Listbox(self.thur_labelframe, height = 5, width = 30, bg = BG, fg = FG)
        self.th_lbox.grid(padx = 5, pady = 5)        
        
        self.fri_labelframe = tk.LabelFrame(self.display_frame, text = 'FRIDAY', 
                                            bg =  BG,  fg =  FG,  font = ('Verdana',8,'bold'), cursor = 'hand2')
        self.fri_labelframe.grid(row = 5, padx = 3, pady = 3, sticky =  tk.NS)        
        self.f_lbox = tk.Listbox(self.fri_labelframe, height = 5, width = 30, bg = BG, fg = FG)
        self.f_lbox.grid(padx = 5, pady = 5) 
        
        
        
        
        
        #To DO labelframe
        #---------------------------------------------------------------------------------------------------------
        self.todo_lab = tk.Label(self.todo_frame, text = "TODO's", bg = BG, fg = FG,
                                 font = ('Verdana', 20, 'bold'))
        self.todo_lab.grid(row = 0, padx = 5, pady = 5)
        
        self.cal = Calendar(self.todo_frame, font="Arial 14", selectmode='day', locale='en_US',
                            background = BG, foreground = FG, headersbackground = BG, headersforeground = DGR,
                            bordercolor = DGR,normalbackground = BG, normalforeground = FG, 
                            weekendbackground = BG, weekendforeground = FG,
                            selectbackground = DGR, selectforeground = 'black',
                            othermonthforeground = 'dim gray', othermonthbackground = BG, 
                            othermonthweforeground = 'dim gray', othermonthwebackground = BG, 
                            mindate=mindate, maxdate=maxdate, disabledforeground='red',
                            tooltipbackground = BG, tooltipforeground = DGR,
                            cursor="hand1", year=int(y), month=int(m), day=int(d))
        
        self.cal.grid(row = 1, padx = 5, pady = 5., sticky = tk.NSEW)
        self.cal.bind('<<CalendarMonthChanged>>', None)#self.on_change_month)        
        
        self.todo_lframe = tk.LabelFrame(self.todo_frame, text = 'Detail Window',
                                         bg = BG, fg = FG, font = ('Verdana', 8, 'bold'), cursor = 'hand2')
        self.todo_lframe.grid(row = 2, padx = 5, pady = 5)
        
        
        
        
        
        
        #$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
        self.nbook = ttk.Notebook(self.todo_lframe)
        self.nbook.bind('<3>', None) #self.undo_disable)
                  
        #s = ttk.Style()
        #default_vals = ('winnative', 'clam', 'alt', 'default', 'classic', 'vista', 'xpnative')
        #s.theme_use('clam')
        
        self.framehold = {}
        
        self.frame1 = ttk.Frame(self.nbook, relief = tk.SUNKEN)#width = 400, height = 400, relief = tk.SUNKEN)
        self.frame2 = ttk.Frame(self.nbook, relief = tk.SUNKEN)#width = 400, height = 400, relief = tk.SUNKEN)
        self.frame3 = ttk.Frame(self.nbook, relief = tk.SUNKEN)#width = 400, height = 400, relief = tk.SUNKEN)
        
        self.nbook.add(self.frame1, text = 'Not Started')
        self.nbook.add(self.frame2, text = 'In Progress')
        self.nbook.add(self.frame3, text = 'Completed')
        
        self.nbook.grid(row = 0, column = 0, columnspan = 2, padx = 5, pady = 5)
        #$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$        
        
        
        
        
        
        #NOTEBOOK FRAME 1 WIDGETS
        self.todo_scroll1 = tk.Scrollbar(self.frame1, bg = BG, highlightcolor = BG,  highlightbackground = BG,  troughcolor = BG)
        self.todo_scroll1.grid(row = 0, column = 1 , sticky = tk.NS)       
        self.todo_text1 = tk.Text(self.frame1, height = 15, width = 70, bg = BG, fg = FG, yscrollcommand = self.todo_scroll1.set,
                                 selectbackground = DGR, selectforeground = 'black')
        self.todo_text1.grid(row = 0, column = 0, padx = 5, pady = 5)        
        self.todo_scroll1.config(command = self.todo_text1.yview)
        
        #NOTEBOOK FRAME 2 WIDGETS
        self.todo_scroll2 = tk.Scrollbar(self.frame2, bg = BG, highlightcolor = BG,  highlightbackground = BG,  troughcolor = BG)
        self.todo_scroll2.grid(row = 0, column = 1 , sticky = tk.NS)       
        self.todo_text2 = tk.Text(self.frame2, height = 15, width = 70, bg = BG, fg = FG, yscrollcommand = self.todo_scroll2.set,
                                 selectbackground = DGR, selectforeground = 'black')
        self.todo_text2.grid(row = 0, column = 0, padx = 5, pady = 5)        
        self.todo_scroll2.config(command = self.todo_text2.yview)
        
        #NOTEBOOK FRAME 3 WIDGETS
        self.todo_scroll3 = tk.Scrollbar(self.frame3, bg = BG, highlightcolor = BG,  highlightbackground = BG,  troughcolor = BG)
        self.todo_scroll3.grid(row = 0, column = 1 , sticky = tk.NS)       
        self.todo_text3 = tk.Text(self.frame3, height = 15, width = 70, bg = BG, fg = FG, yscrollcommand = self.todo_scroll3.set,
                                 selectbackground = DGR, selectforeground = 'black')
        self.todo_text3.grid(row = 0, column = 0, padx = 5, pady = 5)        
        self.todo_scroll3.config(command = self.todo_text3.yview)  
        
        
        self.buttonleft = tk.Button(self.todo_lframe, text = '<', bg = BG, fg = FG,
                                    font = ('Verdana', 16, 'bold'), command = None)
        self.buttonleft.grid(row = 1, column = 0, padx = 5, pady = 5, sticky = tk.EW)
        self.buttonright = tk.Button(self.todo_lframe, text = '>', bg = BG, fg = FG,
                                    font = ('Verdana', 16, 'bold'), command = None)
        self.buttonright.grid(row = 1, column = 1, padx = 5, pady = 5, sticky = tk.EW)        
         
        
        
        
        
        #INSERTING DATA INTO THE FRAME FIELDS -----------------------------------------
               
        # with open(r'C:\Users\kinse\Anaconda3\DXPE Sales Tool\SalesTool-master\SalesTool-master\pump_applications.txt', 'r')as F:
        #     lines = F.readlines()
        #     for line in lines:
        #         self.todo_text1.insert(tk.END, line)
        
        # for conts in customer:
        #     self.todo_text2.insert(tk.END, '{}\n'.format(conts))
        
        
        
        
        
        #Edit mode button --------------------------------------------------------------------------------------------------
        self.edit_entry_button = tk.Button(self.display_frame, text = 'Edit Entries', bg = BG, 
                                           fg = FG,  font = ('Verdana',8,'bold'), cursor = 'hand2')
        self.edit_entry_button.grid(row = 6, padx = 3, pady = 5, sticky = tk.EW)
        
        self.unitholdr = [(self.mon_labelframe, 'a', self.mon_lbox),
                                   (self.tue_labelframe, 'a', self.tue_lbox),
                                   (self.wed_labelframe, 'a', self.wed_lbox),
                                   (self.thur_labelframe, 'a', self.th_lbox),
                                   (self.fri_labelframe, 'a', self.f_lbox),
                                   (self.selection_frame, 's', None)]
        
        
        
        
        #Iterate through dictionary to add binding functionality -----------------------------------
        for i in self.unitholdr:                                                              
            self.bind_enter_leave(i[1],i[0])
            
            if i[0] == self.selection_frame:
                pass            
            else:
                    self.bind_clicking_widge(i[-1])
                    
                    
        #Selection Frame Side
        #------------------------------------------------------------------------------------------------------------------
        
        #Top Section------------------
        self.det_labelframe_1 = tk.LabelFrame(self.selection_frame, text = 'Enter Info', 
                                            bg =  BG,  fg =  FG,  font = ('Verdana',9,'bold'))
        self.det_labelframe_1.grid(row = 1, padx = 3, pady = 5, sticky =  tk.NS) 
        
        #Spinbox to assign and send data to correct field for viewing--------------------------
        self.choices = ('MONDAY', 'TUESDAY', 'WED', 'THURSDAY', 'FRIDAY')
        self.cb = tk.StringVar()
        self.spinbox = tk.Spinbox(self.det_labelframe_1, values = self.choices, bg =  '#0C1021', fg = DGR,
                                  font = ('Verdana',8), cursor = 'hand2', justify = tk.CENTER, textvariable = self.cb)
        self.spinbox.grid(row = 0, column =1, columnspan = 2, padx = 3, pady = 3, sticky = tk.EW)
        self.cb.trace('w', self.select_changes)
        
        #self.cb = tk.StringVar()
        #self.combox = ttk.Combobox(self.det_labelframe_1, values = self.choices, 
        #self.combox.grid(row = 0, column =1, columnspan = 2, padx = 3, pady = 3, sticky = tk.EW)
        
        #Company name-------------------------------
        self.complab = tk.Label(self.det_labelframe_1, text = 'Company Name', bg = BG, fg = FG, font = ('Verdana',8))         #some type of auto populate
        self.complab.grid(row = 1 , column = 1, padx = 3, pady = 3, sticky = tk.W)
        self.comp_ent =  tk.Entry(self.det_labelframe_1, bg = BG, fg = FG, font = ('Verdana',8), width = 50,
                               cursor = 'xterm', selectbackground = 'dark goldenrod', insertbackground = 'white')
        self.comp_ent.grid(row = 1 , column = 2, padx = 3, pady = 3, sticky = tk.E)
        self.comp_ent.bind('<Button-1>', self.compchg)
        
        
        #Contact Info------------------------------------
        self.contlab = tk.Label(self.det_labelframe_1, text = 'Contact Name', bg = BG, fg = FG, font = ('Verdana',8))
        self.contlab.grid(row = 2 , column = 1, padx = 3, pady = 3, sticky = tk.W)
        self.cont_ent =  tk.Entry(self.det_labelframe_1, bg = BG, fg = FG,  font = ('Verdana',8), width = 50,
                               cursor = 'xterm', selectbackground = 'dark goldenrod', insertbackground = 'white' )
        self.cont_ent.grid(row = 2 , column = 2, padx = 3, pady = 3, sticky = tk.E) 
        self.cont_ent.bind('<Button-1>', self.contchg)
        
        
        #Medium used i.e. email, phone call, meeting , etc.--------------------------------------
        self.medlab = tk.Label(self.det_labelframe_1, text = 'Medium Used', bg = BG, fg = FG, font = ('Verdana',8))           #Think about using a spinbox
        self.medlab.grid(row = 3 , column = 1, padx = 3, pady = 3, sticky = tk.W)
        self.med_ent =  tk.Entry(self.det_labelframe_1, bg = BG, fg = FG, font = ('Verdana',8), width = 50,
                              cursor = 'xterm', selectbackground = 'dark goldenrod', insertbackground = 'white' )
        self.med_ent.grid(row = 3 , column = 2, padx = 3, pady = 3, sticky = tk.E)
        self.med_ent.bind('<Button-1>', self.medchg)
        
        
        #Description of transaction-------------------------------------
        self.desclab = tk.Label(self.det_labelframe_1, text = 'Description', bg = BG, fg = FG, font = ('Verdana',8))
        self.desclab.grid(row = 4 , column = 1, padx = 3, pady = 3, sticky = tk.W)
        
        self.desc_scroll = tk.Scrollbar(self.det_labelframe_1, bg = BG, highlightcolor = BG,  highlightbackground = BG,  troughcolor = BG)
        self.desc_scroll.grid(row = 4, column = 3 , sticky = tk.NS)
        self.desc_text = tk.Text(self.det_labelframe_1, bg = BG, fg = FG, font = ('Verdana',8), height = 5, width = 50,
                                 cursor = 'xterm', selectbackground = 'dark goldenrod', selectforeground = 'black', insertbackground = 'white')
        self.desc_text.grid(row = 4, column = 2, padx = 3, pady = 3) 

        #Assigning binding events to the text widget-------------------------------------------
        self.desc_text.bind('<Button-3>', self.copy_highlighted_text)           
        self.desc_text.bind('<Button-1>', self.display_widge_shrink)


        #Going forward what to do---------------------------------------------------
        self.fwdlab = tk.Label(self.det_labelframe_1, text = 'Forward', bg = BG, fg = FG, font = ('Verdana',8))
        self.fwdlab.grid(row = 5, column = 1, padx = 3, pady = 3, sticky = tk.W)

        
        
        self.fwd_scroll = tk.Scrollbar(self.det_labelframe_1, bg = BG, highlightcolor = BG,  highlightbackground = BG,  troughcolor = BG)
        self.fwd_scroll.grid(row = 5, column = 3 , sticky = tk.NS)        
        self.fwd_text = tk.Text(self.det_labelframe_1, bg = BG, fg = FG, font = ('Verdana',8), height = 5, width = 50,
                                cursor = 'xterm', selectbackground = 'dark goldenrod', selectforeground = 'black', insertbackground = 'white')
        self.fwd_text.grid(row = 5, column = 2, padx = 3, pady = 3, sticky = tk.E)  
        
        
        #Assigning binding events to the text widget-------------------------------------------
        self.fwd_text.bind('<Button-3>', self.copy_highlighted_text)            
        self.fwd_text.bind('<Button-1>', self.display_widge_shrink)
        
        
        #BUTTON WIDGET -----------------------------------------------------------------------------------------------------
        self.submitbutton = tk.Button(self.det_labelframe_1, bg = BG, fg = FG, font = ('Verdana',8), cursor = 'hand2',
                                   text = 'SUBMIT', command = lambda: self.pull_entry_data())   #self.enter_new_entry())     
        self.submitbutton.grid(row = 6, column = 1, columnspan = 2,  padx = 3, pady = 3, sticky = tk.EW)
        
        
        #Bottom Section-------------- 
        self.det_labelframe_2 = tk.LabelFrame(self.selection_frame, text = 'Detail Window 2', 
                                            bg =  BG,  fg =  FG,  font = ('Verdana',9,'bold'))
        self.det_labelframe_2.grid(row = 2, padx = 3, pady = 5, sticky =  tk.NS) 
        
        
        #Have decided to make this the notes section for displaying stored DB notes for whatever day of the wek listbox has the current focus
        self.det_scroll = tk.Scrollbar(self.det_labelframe_2, bg = BG, highlightcolor = BG,  highlightbackground = BG,  troughcolor = BG)
        self.det_scroll.grid(row = 0, column = 1 , sticky = tk.NS)                
        self.det_text = tk.Text(self.det_labelframe_2, bg = BG, fg = FG, font = ('Verdana',8), height = 20, width = 65,
                                cursor = 'xterm', selectbackground = 'dark goldenrod', selectforeground = 'black', insertbackground = 'white')
        self.det_text.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = tk.NS) 
        
        
        self.det_text.config(state = tk.DISABLED)                                       #Disabled the text box. Will have to check edit radiobutton to return NORMAL state
        self.det_text.bind('<Button-3>', self.copy_highlighted_text)          #Add binding event to the text widget
        
        
        #Radio button to toggle on and off editability to the text widget--------------------------------
        self.edit_note_switch = tk.Radiobutton(self.det_labelframe_2, text = 'Edit Mode', command = self.det_text_state_change, value = 1, fg = FG, bg = BG)
        self.edit_note_switch.grid(row = 1, column = 0, columnspan = 2,  sticky = tk.EW)
    
    

    #----------------------------------------------------------------------------------------------
    def compchg(self, event):
        """
    
        """
        self.complab.config(fg = DGR)
        self.contlab.config(fg = FG)
        self.medlab.config(fg = FG)
        
        
    #----------------------------------------------------------------------------------------------
    def contchg(self, event):
        """
    
        """
        self.complab.config(fg = FG)
        self.contlab.config(fg = DGR)
        self.medlab.config(fg = FG)
        
    #----------------------------------------------------------------------------------------------
    def medchg(self, event):
        """
    
        """
        self.complab.config(fg = FG)
        self.contlab.config(fg = FG)
        self.medlab.config(fg = DGR)    
        
        
    
    #----------------------------------------------------------------------------------------------
    def select_changes(self, *args):
        """
        Temporary testing function to see whats in the database for each of the assigned days
        Depending on current selected day. we need to pass along to function altering the size of the listbox widgets
        to make the ACTIVE one the most pronounced
        """
        
        day_current = self.cb.get()
        self.lbox_size_change(day_current)
        return
    
    
    
    
    #----------------------------------------------------------------------------------------------
    def lbox_size_change(self, day):
        """
        Func to resize the clicked listbox (enlarge) as well as the other 4 listboxes (shrink)
        """
        
        #ADD FUNCTIONALITY------\
        #make is so when widget is focused you see the text. Otherwise when small you only see the count of 
        #the widget containers entries
        
       #Dictionary storing the day in string form as keys and the listbox associated with the data cooresponding to it
        fields = {'MONDAY': self.mon_lbox,
                  'TUESDAY': self.tue_lbox,
                  'WED': self.wed_lbox,
                  'THURSDAY': self.th_lbox,
                  'FRIDAY':self.f_lbox}
        
        for k,v in fields.items():
            
            if fields[k] == day:
                
                self.pull_current_acc_text(k)                     #Pull current text whether edited or not and replace with current entry. Then proceed to pull next data
                v.config(height = 12)
                v.master.config(fg = DGR)   
                self.widge_content_display(k)
                self.change_text_acc_lbox(k)                    #Pass along the day
                
        
            else:
                v.config(height = 2)
                v.master.config(fg = FG)

        return    
    
    
    
    
    #----------------------------------------------------------------------------------------------
    def test_print(self, day_of_week):
        """
        Temporary testing function to see whats in the database for each of the assigned days
        """
        
        c = self.conn.cursor()
        log = self.conn.cursor()
        cnt = self.conn.cursor()
        
        #Priniting all the notes for the day of the week
        c.execute('SELECT * FROM {}'.format(day_of_week))
        
        for row in c.fetchall():
            print(row)
            
        cnt.execute('SELECT COUNT(*) FROM calllog WHERE day = ?',(day_of_week,))
        numb = cnt.fetchone()
        
        print(numb[0])
            
        log.execute('SELECT * FROM calllog WHERE day = ?',(day_of_week,))
        
        for row in log.fetchall():
            print(row)
            
        return       



    
    #----------------------------------------------------------------------------------------------
    def det_text_state_change(self):
        """
        
        """
        if CallLogWindow.edit_track == 'N':
            self.det_text.config(state = tk.NORMAL)
            CallLogWindow.edit_track = 'Y'
            
        else:
            self.det_text.config(state = tk.DISABLED)
            CallLogWindow.edit_track = 'N'
            
        return
          
    
    
    
    #----------------------------------------------------------------------------------------------
    def database_init(self):
        """ 
        
        """
        
        db_dir = r'C:\Users\kinse\Anaconda3\DB\Test_1.db'
        self.conn = sq3.connect(db_dir)                                                  #:memory:')
        self.create_db_tables()
        print('SQL Connection and table created Successfully')
        
        return
    
    
    

    #----------------------------------------------------------------------------------------------
    def create_db_tables(self):
        """ 
        
        """
        
        #Call log entries database
        self.conn.execute("""CREATE TABLE IF NOT EXISTS calllog (day TEXT, comp TEXT, cont TEXT, med TEXT, desc TEXT, fwd TEXT) """)  
        self.conn.commit()

        #Days Notes database
        self.conn.execute("""CREATE TABLE IF NOT EXISTS  notes (day TEXT,  daynote TEXT) """)  
        self.conn.commit()
        
        #Creating table for each day will prove to be easier and less messy to handle
        choices = ('MONDAY', 'TUESDAY', 'WED', 'THURSDAY', 'FRIDAY')
        
        for chc in choices:
            
            self.conn.execute("""CREATE TABLE IF NOT EXISTS  {}(daynote TEXT) """.format(chc))  
            self.conn.commit()
            print('TABLE {} SUCCESFULLY CREATED'.format(chc))
        
        return
    
        
        
    #----------------------------------------------------------------------------------------------
    def db_entry_print(self):
        """ 
        
        """
        
        c = self.conn.cursor()
        c.execute("""SELECT * FROM calllog""")
        
        try: 
            
            for row in c.fetchall():
                print(row)
                
        except AttributeError as e:
            
            print(e)
            print(c.fetchone())
        
        
        c.close()
        return
        
    
    
    #-----START WIDGET CREATION-----------------------------------------------------------------------------------------
    ####################################################################################################
    def create_labels(self, w):
        """
        To aid in cleanup of the __init__ function. Cleaner and easier to read code is the goal.
        Create Label widget 
        """
        
        pass
    
    
    
    
    #----------------------------------------------------------------------------------------------
    def create_entries(self, w):
        """
        To aid in cleanup of the __init__ function. Cleaner and easier to read code is the goal.
        Create Entry widget 
        """
        
        pass
    
    
    
    
    #----------------------------------------------------------------------------------------------
    def create_labframe(self, w):
        """
        To aid in cleanup of the __init__ function. Cleaner and easier to read code is the goal.
        Create LabelFrame widget 
        """
        
        return tk.LabelFrame(self.display_frame, text = 'MONDAY', 
                                                    bg =  BG,  fg =  FG, font = ('Verdana',8,'bold'), cursor = 'hand2')





    #---START--------------Functions for GUI Functionality --------------------------------------------------------------
    #####################################################################################################
    def pull_entry_data(self, *args):
        """
        Func - called by submit button. Pull all the data from the widgets and send to perspective day of the week storage 
        and viewing  on left side of screen widgets
        """
        
        sbox = self.spinbox.get()
        comp_E = self.comp_ent.get()
        cont_E = self.cont_ent.get()
        med_E = self.med_ent.get()
        desc_T = self.desc_text.get(1.0, tk.END)
        fwd_T = self.fwd_text.get(1.0, tk.END)
        
        self.pulled_data_array = [sbox, comp_E, cont_E, med_E, desc_T, fwd_T]
        self.write_data_to_db(*self.pulled_data_array)

        self.add_entry_data_to_field(*self.pulled_data_array)
        self.clear_entry_widgets()
        
    
    
    
    #----------------------------------------------------------------------------------------------
    def write_data_to_db(self,*args):
        """ 
        Func - takes all the arguments from the pulled entry fields and writes them to the aooprpriate 
        listbox, by splitting them amongst days
        """
        
        self.conn.execute("""INSERT INTO calllog (day, comp, cont, med, desc, fwd) VALUES (?,?,?,?,?,?)""", (args))
        self.conn.commit()
        self.db_entry_print()
        
        return    




    #---------------------------------------------------------------------
    def add_entry_data_to_field(self, *args):
        """
        Func - to take pulled data from entry fields and input to appropriate
        """
        
        fields = {'MONDAY': self.mon_lbox,
                  'TUESDAY': self.tue_lbox,
                  'WED': self.wed_lbox,
                  'THURSDAY': self.th_lbox,
                  'FRIDAY':self.f_lbox}

        fields[args[0]].insert(tk.END, '{} Entry:'.format(args[0]))         
        
        for i in args[1::]:
            
            j = str(i).strip('\n')
            fields[args[0]].insert(tk.END, j)

        return
    
        
        
    #------------------------------------------------------------------------------------------------    
    def clear_entry_widgets(self):
        """
        After widgets text has been pulled this function clears the widgets so there ready
        for the next entry
        """
        
        self.comp_ent.delete(0, tk.END)
        self.cont_ent.delete(0, tk.END)
        self.med_ent.delete(0, tk.END)
        self.desc_text.delete(1.0, tk.END)
        self.fwd_text.delete(1.0, tk.END)
    
        return
    
    
    #-----END--------------Functions for GUI Functionality --------------------------------------------------------------
    #####################################################################################################
    
    
    #----------------------------------------------------------------------------------------------
    def bind_enter_leave(self, c, widge):
        """
         c - catagory, either 'a' for account or 's' for selection_frames
         widge - widget being passed to get assigned a binding action
        """
        
        if c == 'a':
            widge.bind('<Enter>', self.change_acc_color)
            widge.bind('<Leave>', self.change_acc_def_color)
            
        if c == 's':
            widge.bind('<Enter>', self.change_select_color)
            widge.bind('<Leave>', self.change_select_def_color)
        
        return      
    
    
    #----------------------------------------------------------------------------------------------
    def bind_clicking_widge(self, widge):
        """ 
        widge is given bind method to call resizing function when it is clicked
        """
        
        widge.bind('<Button-1>', self.widge_enlarge_shrink)                                        #Each listbox widget will be passed to this function assigning them click event instruction
                 
        return
    
    
    
    #----------------------------------------------------------------------------------------------
    def widge_enlarge_shrink(self, event):
        """
        Func to resize the clicked listbox (enlarge) as well as the other 4 listboxes (shrink)
        """
        
        #ADD FUNCTIONALITY------\
        #make is so when widget is focused you see the text. Otherwise when small you only see the count of 
        #the widget containers entries
        
       #Dictionary storing the day in string form as keys and the listbox associated with the data cooresponding to it
        fields = {'MONDAY': self.mon_lbox,
                  'TUESDAY': self.tue_lbox,
                  'WED': self.wed_lbox,
                  'THURSDAY': self.th_lbox,
                  'FRIDAY':self.f_lbox}
        
        for k,v in fields.items():
            
            if fields[k] == event.widget:
                
                self.pull_current_acc_text(k)                     #Pull current text whether edited or not and replace with current entry. Then proceed to pull next data
                event.widget.config(height = 12)
                event.widget.master.config(fg = DGR)   
                self.widge_content_display(k)
                self.change_text_acc_lbox(k)                    #Pass along the day
                
        
            else:
                v.config(height = 2)
                v.master.config(fg = FG)

        return

    
   
    #----------------------------------------------------------------------------------------------
    def widge_content_display(self, d):
        """ 
        When one of the day of week listboxes is selected, we want to pull all the data from our database that has the same matching
        day, ex. 'MONDAY'
        """
        
        #Pull the data from the associated day
        c = self.conn.cursor()        
        c.execute("""SELECT * FROM {}""".format(d))                                   
        
        self.det_text.delete(1.0, tk.END)
        
        try:            
            for row in c.fetchall():
                if row[0] == 'MONDAY':
                    print('monday')
                print(row)
                self.det_text.insert(tk.END, row)
    
        except AttributeError as e:
            self.det_text.insert(tk.END, c.fetchone())
    
    
        #Get the count of entries for the day currently focused on
        cnt = c.execute("""SELECT COUNT(*) FROM calllog WHERE day == ?""",(d[0],))
        self.det_labelframe_2.config(text = '{} Notepad -----  Entries: {}'.format(d[0],cnt.fetchone()[0]))
        
        c.close()
        return    
    
        
    
    
    
    #----------------------------------------------------------------------------------------------
    def display_widge_shrink(self, event):
        """ 
        Func to make active text widget larger to ease users writability with app. Other text box shrinks in size to maintain
        the window size
        """
        
        widgs = [self.desc_text, self.fwd_text]         #Store the widgets
        d1 = self.desclab.grid_info()                         #Check each of there grid coordinates
        d2 = self.fwdlab.grid_info()
        chk = event.widget.grid_info()
        
        
        self.contlab.config(fg = FG)
        self.complab.config(fg = FG)
        self.medlab.config(fg = FG)        
        
        
        if d1['row'] == chk['row']:
            self.desclab.config(fg = DGR, text = 'DESC', font = 16)
            self.fwdlab.config(text = 'Forward', fg = FG, font = ('Verdana',8))
            
        else:
            self.fwdlab.config(fg = DGR,  text = 'FWD', font = 16)
            self.desclab.config(text = 'Description', fg = FG, font = ('Verdana',8))
        
        for i in widgs:
            
            if i == event.widget:
                event.widget.config(height = 8)
                
            else:
                i.config(height = 3)
                
        return
    
    
    
    #----------------------------------------------------------------------------------------------
    def pull_current_acc_text(self, d):
        """ 
        Func to take current text at time of click and add it to the DB.
        """
        
        widge_text = self.desc_text.get(1.0, tk.END)
        if len(widge_text) <= 1:
            return
        
        else:
            c = self.conn.cursor()
            c.execute("""INSERT INTO ? VALUES(?)""", (d, widge_text,))
            self.conn.commit()

        return
    
    
    
    #----------------------------------------------------------------------------------------------
    def change_text_acc_lbox(self, d):
        """ 
        d - day of the week that will correlate with the note in database (long string entry that gets added on)
        Pull the data entry and pass to the text box where users can view it or opt to press edit button and edit entry.
        After edit user can load new edoited string
        
        If user clicks to another days box --- before that switch, need func to pull whats there and replace existing. Then delete and
        fill with what day was chosen next
        """
        
        c = self.conn.cursor()
        c.execute("""SELECT * FROM notes WHERE day = ?""",(d,))
        print(d)
        
    
    
    #----------------------------------------------------------------------------------------------
    def change_acc_color(self, event):
        """ 
        
        """
        
        self.lab_accounts.config(fg = DGR)
        self.lab_selection.config(fg = 'white')
        
        return
    
    
    #----------------------------------------------------------------------------------------------
    def change_select_color(self, event):
        """ 
        
        """
        
        self.lab_accounts.config(fg = 'white')
        self.lab_selection.config(fg = DGR)
        
        return  
    
    
    #----------------------------------------------------------------------------------------------
    def change_acc_def_color(self, event):
        """ 
        
        """
        
        self.lab_selection.config(fg = 'white')
        
        return
    
    
    #----------------------------------------------------------------------------------------------
    def change_select_def_color(self, event):
        """ 
        
        """
        
        self.lab_selection.config(fg = 'white')
        
        return
    
    
    #----------------------------------------------------------------------------------------------
    def copy_highlighted_text(self, event):
        """
        Func - the widgets have been binded to this function to take all the highlighted text and copy it to
        the computers clipboard
        
        Binded to Button-2 - which is Middle Mouse Button
        """
        
        try:
            copytext = event.widget.selection_get()                                      #Pull the text that is currently selected by highlight in widget
            
            if len(copytext) <= 1:                                                                   #Check if length is too short and should warn user
                self.clipboard_warning()
                
            else:
                self.parent.clipboard_append(copytext)
                print('Succesful copy of selected text to Clipboard')
            
        except Exception:
            self.clipboard_error_warning()
        
        return
    
    
    #----------------------------------------------------------------------------------------------
    def clipboard_warning(self):
        """ 
        Func is called to warn users that it has been detected nothing was actually copied to clipboard
        """
        
        mb.showwarning(title = 'Warning', message =  'App detected its possible that\nno text was actually selected')
        
        return
    
    
    
    #----------------------------------------------------------------------------------------------
    def clipboard_error_warning(self):
        """ 
        Func - error message box popup to let user know there was an error attempting to copy text.        
        FORWARD - Move to a double cliick (some users may accidently right click and become a nusence.
        - or - 
        Make it a turn on or off functionality
        """
        
        mb.showerror(title = 'Error with Clipboard', message = 'No items highlighted. Please try again.\n(Text needs to be highlighted before right click is applied)')
        
        return
    
    
    
    #----------------------------------------------------------------------------------------------
    def write_to_file(self):
        """ 
        Source: https://automatetheboringstuff.com/chapter8/
        """
        
        self.parent.iconify()
        
        self.writefile_window = tk.Toplevel()
        self.wfile = tk.Frame(self.writefile_window, bg = BG)
        self.wfile.grid()
        
        current_dir = os.getcwd()
        tstr = 'Testing.txt'
        self.wfile_lab = tk.Label(self.wfile,  bg = BG, fg = FG, font = ('Verdana', 14, 'bold'),
                                  text = 'Current Directory:\n{}'.format(os.path.join(current_dir, tstr)))
        self.wfile_lab.grid(padx = 5, pady = 5)
        
        self.writefile_window.protocol('WM_DELETE_WINDOW', self.wfile_win_destroy)
        self.writefile_window.mainloop()
    
    
    
    #----------------------------------------------------------------------------------------------
    def wfile_win_destroy(self):
        """ 
        Destroy the write file window and bring back to view the parent window so user 
        can continue with workflow
        """
        
        self.writefile_window.destroy()
        self.parent.deiconify()
Exemple #11
0
class Window:
    def __init__(self,
                 width,
                 height,
                 title='Change rates',
                 resizable=(False, False),
                 icon=None):
        self.root = tk.Tk()
        self.root.title(title)
        self.root.geometry(f'{width}x{height}+200+50')
        self.root.resizable(resizable[0], resizable[1])

    def run(self):
        self.create_widgets()
        self.root.mainloop()

    def create_widgets(self):
        # create widgets of main window
        self.start_date_label = tk.Label(self.root, text='Start date: ').grid(
            row=0, column=1, columnspan=2)
        self.start_date_label = tk.Label(self.root,
                                         text='End date: ').grid(row=0,
                                                                 column=3,
                                                                 columnspan=2)
        self.start_date = Calendar(self.root,
                                   font="Arial 8",
                                   selectmode='day',
                                   year=2000,
                                   month=1,
                                   day=1,
                                   mindate=datetime.date(2000, 1, 1),
                                   maxdate=datetime.date.today())
        self.end_date = Calendar(self.root,
                                 font="Arial 8",
                                 selectmode='day',
                                 year=2000,
                                 month=1,
                                 day=2,
                                 mindate=datetime.date(2000, 1, 2),
                                 maxdate=datetime.date.today())
        self.end_date.bind("<<CalendarSelected>>", self.DateCheck)
        self.start_date.bind("<<CalendarSelected>>", self.DateCheck)
        self.start_date.grid(column=1, row=1, padx=10, pady=10, columnspan=2)
        self.end_date.grid(column=3, row=1, padx=10, pady=10, columnspan=2)
        self.step = tk.Label(self.root, text='Step ').grid(row=2, column=1)
        # years = self.setTimeInterval(start_year, end_year)
        # self.yy1 = ttk.Combobox(self.root, values=years, height =10, width=5)
        # self.yy1.set(years[0])
        # self.yy1.grid(row=1, column=2)
        # self.yy1['state'] = 'readonly'
        # self.yy1.bind("<<ComboboxSelected>>", self.YearCheck)
        #
        # months = self.setTimeInterval(1, 12)
        # self.mm1 = ttk.Combobox(self.root, values=months, height =12, width=3)
        # self.mm1.set(months[0])
        # self.mm1.grid(row=1, column=3)
        # self.mm1['state'] = 'readonly'
        # self.mm1.bind("<<ComboboxSelected>>", self.CheckMonth)
        #
        # daysInMonth = calendar.monthrange(int(self.yy1.get()), int(self.mm1.get()))[1]
        # self.days = self.setTimeInterval(1, daysInMonth)
        # self.dd1 = ttk.Combobox(self.root, values = self.days, height =10, width=3)
        # self.dd1.set(self.days[0])
        # self.dd1.grid(row=1, column=4)
        # self.dd1.bind("<<ComboboxSelected>>", self.DayValidate)
        # self.dd1['state'] = 'readonly'
        #
        # self.yy2 = ttk.Combobox(self.root, values=years, height =10, width=5)
        # self.yy2.set(years[0])
        # self.yy2.grid(row=2, column=2)
        # self.yy2.bind("<<ComboboxSelected>>", self.YearCheck)
        # self.yy2['state'] = 'readonly'
        #
        # self.mm2 = ttk.Combobox(self.root, values=months, height =12, width=3)
        # self.mm2.set(months[0])
        # self.mm2.grid(row=2, column=3)
        # self.mm2.bind("<<ComboboxSelected>>", self.CheckMonth)
        # self.mm2['state'] = 'readonly'
        #
        # self.dd2 = ttk.Combobox(self.root, values=self.days, height=10, width=3)
        # self.dd2.set(self.days[0])
        # self.dd2.grid(row=2, column=4)
        # self.dd2.bind("<<ComboboxSelected>>", self.DayValidate)
        # self.dd2['state'] = 'readonly'
        self.interval = tk.Scale(self.root,
                                 orient='horizontal',
                                 length=300,
                                 from_=1,
                                 to=365,
                                 tickinterval=50,
                                 resolution=1)
        self.interval.grid(row=2, column=2, columnspan=4)
        self.check_dates = tk.Button(self.root,
                                     text='Get list of money',
                                     command=self.createMoneyList)
        self.check_dates.grid(row=4, column=2, columnspan=2, pady=10)
        self.quit = tk.Button(self.root,
                              text="QUIT",
                              fg="red",
                              command=self.root.destroy).grid(row=4,
                                                              column=4,
                                                              columnspan=1,
                                                              pady=10)

    # def setTimeInterval(self, start, end):
    #     interval = []
    #     for i in range(int(start), int(end)+1):
    #         interval.append(i)
    #     return interval
    #
    # def YearCheck(self, event):
    #     if int(self.yy1.get())>int(self.yy2.get()):
    #         self.yy2.set(self.yy1.get())
    #     self.DayValidate()
    #
    # def CheckMonth(self, event):
    #     if int(self.yy1.get())==int(self.yy2.get()) and int(self.mm1.get())>int(self.mm2.get()):
    #         self.mm2.set(self.mm1.get())
    #     self.DayValidate()
    #
    # def DayValidate(self):
    #     daysInMonth1 = calendar.monthrange(int(self.yy1.get()), int(self.mm1.get()))[1]
    #     daysInMonth2 = calendar.monthrange(int(self.yy2.get()), int(self.mm2.get()))[1]
    #     if len(self.dd1['value']) != daysInMonth1:
    #         days = self.setTimeInterval(1, daysInMonth1)
    #         self.dd1['value'] = days
    #     elif len(self.dd2['value']) != daysInMonth2:
    #         days = self.setTimeInterval(1, daysInMonth2)
    #         self.dd2['value'] = days
    #     else:
    #         pass
    #     if int(self.dd1.get()) > daysInMonth1:
    #         self.dd1.set(daysInMonth1)
    #     elif int(self.dd2.get()) > daysInMonth2:
    #         self.dd2.set(daysInMonth2)
    #     if int(self.yy1.get()) == int(self.yy2.get()) and int(self.mm1.get()) == int(self.mm2.get()) and\
    #             int(self.dd1.get()) == int(self.dd2.get()) and int(self.dd1.get())<daysInMonth1:
    #         self.dd2.set(int(self.dd2.get())+1)
    #     elif int(self.yy1.get()) == int(self.yy2.get()) and int(self.mm1.get()) == int(self.mm2.get()) and \
    #             int(self.dd1.get()) >= int(self.dd2.get()):
    #         if int(self.mm2.get()) < 12:
    #             self.mm2.set(int(self.mm2.get()) + 1)
    #             self.dd2.set(1)
    #         else:
    #             self.yy2.set(int(self.yy2.get())+1)
    #             self.mm2.set(1)
    #             self.dd2.set(1)

    def DateCheck(self, event):
        # Function validating of Calendar
        delta = timedelta(days=1)
        if self.start_date.selection_get() == datetime.date.today():
            self.start_date.selection_set(self.start_date.selection_get() -
                                          delta)
        if self.start_date.selection_get() >= self.end_date.selection_get():
            self.end_date.selection_set(self.start_date.selection_get() +
                                        delta)

    def createMoneyList(self):
        # Function to create child window
        moneyList = ChildWindow(self.root, 500, 350, 'money list')
        start_date = self.start_date.selection_get()
        end_date = self.end_date.selection_get()
        step = timedelta(days=self.interval.get())
        moneyList.run(start_date, end_date, step)
class Application(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title('User Info for L2 & L3')
        self.createWidgets()
        tkinter.ttk.Separator(self, orient="horizontal").grid(row=1,
                                                              column=1,
                                                              columnspan=100,
                                                              padx=10,
                                                              pady=10,
                                                              sticky='ew')

    def updateMovies(self, event=None):
        self.movieCombo['values'] = movies[self.genreCombo.get()]
        self.movieCombo1['values'] = movies1[self.genreCombo.get()]
        Listbox1 = []
        Listbox2 = []
        for item in self.movieCombo['values']:
            self.Listbox1.insert('end', item)
        for item1 in self.movieCombo1['values']:
            self.Listbox2.insert('end', item1)

    def createWidgets(self):
        headingLabel = tk.Label(self,
                                text="User Info for L2 & L3",
                                font="Roboto 12 bold")
        headingLabel.grid(row=0,
                          column=2,
                          columnspan=5,
                          padx=10,
                          pady=10,
                          sticky="w")

        tk.Label(self, text="SELECT START DATE",
                 font="Roboto 8 bold").grid(row=2, column=1, padx=(5, 0))
        self.cal1 = Calendar(font="Arial 14",
                             selectmode='day',
                             cursor="hand1",
                             year=2020,
                             month=1,
                             day=1)
        self.cal1.bind('<<ComboboxSelected>>')
        self.cal1.grid(row=3, column=1, padx=10, pady=10)

        tk.Label(self, text="SELECT END DATE",
                 font="Roboto 8 bold").grid(row=2, column=3, padx=(5, 0))
        self.cal2 = Calendar(font="Arial 14",
                             selectmode='day',
                             cursor="hand1",
                             year=2020,
                             month=1,
                             day=1)
        self.cal2.bind('<<ComboboxSelected>>')
        self.cal2.grid(row=3, column=3, padx=10, pady=10)

        tk.Label(self, text="SELECT CATEGORY 1",
                 font="Roboto 8 bold").grid(row=5, column=1, padx=(5))
        self.genreCombo = tkinter.ttk.Combobox(self,
                                               width=30,
                                               values=list(movies.keys()),
                                               state="readonly")
        self.genreCombo.set("SELECT")
        self.genreCombo.bind('<<ComboboxSelected>>', self.updateMovies)
        self.genreCombo.grid(row=6, column=1, padx=10, pady=10)

        tk.Label(self, text="SELECT CATEGORY 2",
                 font="Roboto 8 bold").grid(row=5, column=2, padx=(5, 0))
        self.movieCombo = tkinter.ttk.Combobox(width=30, state="readonly")
        self.movieCombo.bind('<<ComboboxSelected>>')
        self.movieCombo.set("SELECT")

        tk.Label(self, text="SELECT CATEGORY 3",
                 font="Roboto 8 bold").grid(row=5, column=3, padx=(5, 0))
        self.movieCombo1 = tkinter.ttk.Combobox(width=30, state="readonly")
        self.movieCombo1.bind('<<ComboboxSelected>>')
        self.movieCombo1.set("SELECT")

        self.Listbox1 = tkinter.Listbox(self,
                                        activestyle='dotbox',
                                        selectbackground='blue',
                                        selectborderwidth=1,
                                        height=10,
                                        width=30,
                                        selectmode='multiple',
                                        exportselection=0)
        self.Listbox1.grid(row=6, column=2, padx=(0, 10))

        self.Listbox2 = tkinter.Listbox(self,
                                        activestyle='dotbox',
                                        selectbackground='blue',
                                        selectborderwidth=1,
                                        height=10,
                                        width=30,
                                        selectmode='multiple',
                                        exportselection=0)
        self.Listbox2.grid(row=6, column=3, padx=(0, 10))

        self.Execute_button = tkinter.ttk.Button(
            text="Execute", width=30, command=self.createTimeButtons)
        self.Execute_button.grid(row=9, column=2, padx=(0, 10))

        tk.Label(self, text="Enter File Name",
                 font="Roboto 8 bold").grid(row=8, column=1, padx=10, pady=10)
        self.file_name = tkinter.ttk.Entry(width=30, state="writeonly")
        self.file_name.grid(row=8, column=2, padx=10, pady=10)

        self.Execute_button = tkinter.ttk.Button(text="Reset",
                                                 width=30,
                                                 command=self.resetbutton)
        self.Execute_button.grid(row=9, column=3, padx=(0, 5))

        tk.Label(
            self,
            text=
            "** Categoy L3 must be selected according to category L2 & category L1 selection",
            font="Roboto 11 bold",
            foreground="red").grid(row=10, column=1, padx=20, pady=20)

        tkinter.ttk.Separator(self, orient="horizontal").grid(row=11,
                                                              column=1,
                                                              columnspan=100,
                                                              padx=10,
                                                              pady=10,
                                                              sticky='ew')

    def resetbutton(self, event=None):
        # self.cal1.insert(0, x)
        # self.cal2.insert(0, x)
        self.genreCombo.set('SELECT')
        self.Listbox1.delete(0, 'end')
        self.Listbox2.delete(0, 'end')
        self.file_name.delete(0, 'end')

    def createTimeButtons(self, event=None):
        start_date_select = self.cal1.selection_get().strftime("%Y%m%d")
        end_date_select = self.cal2.selection_get().strftime("%Y%m%d")
        cat1_select = self.genreCombo.get()
        cat2_select = [
            self.Listbox1.get(v) for v in self.Listbox1.curselection()
        ]
        cat3_select = [
            self.Listbox2.get(a) for a in self.Listbox2.curselection()
        ]
        file_name = str(self.file_name.get())

        print(start_date_select)
        print(end_date_select)
        print(cat1_select)
        print(cat2_select)
        print(cat3_select)
        print(file_name)

        # Web Hooks

        o = ODPS('', '', '', endpoint='')
        options.tunnel.endpoint = '**API URL**'
        query = """SELECT  DISTINCT buyer_id
                        ,email_address
                        ,phone_number
                        ,venture_category1_name_en
                        ,venture_category2_name_en
                        ,venture_category3_name_en
                  FROM   Table Name AS t
                  WHERE  venture = ""
                  AND    order_status_esm NOT IN ('invalid')
                  AND    category1_name_en in ('""" + cat1_select + """')
                  AND    category2_name_en in (""" + "'" + "','".join(
            cat2_select) + "'" + """)
                  AND    category3_name_en in (""" + "'" + "','".join(
                cat3_select) + "'" + """)
                  AND    TO_CHAR(t.order_create_date,'yyyymmdd') BETWEEN '""" + start_date_select + """'
                  AND    '""" + end_date_select + """'
                  """
        # Executing the query and set the data into a dataframe
        df = o.execute_sql(query).open_reader().to_result_frame().to_pandas()
        df.columns = df.columns.str.upper()
        date_string = arrow.now().format('YYYYMMDD') + ' ' + file_name
        df.to_csv(str(str(date_string) + '.csv'), index=False)
        print(query)