Example #1
0
#-------------------------------------------#scroll frame ---------------------------------
scrolltab2 = ScrolledFrame(tablayout, height=40)
scrolltab2.pack(side="top", expand=1, fill="both")
#------------------------------------------tab2 body---------------------------------------
tab1 = scrolltab2.display_widget(tk.Frame)
#-----------------------------------------180mlmrp120 entry------------------------------------

#-------------------------------- ----for 2------------------------------------------------------------
#-------------------------------------------------tab2 body end---------------------
#-----------------------------------------------tab2 scroll tab layout---------------
tablayout.add(scrolltab2, text="ML350")

tablayout.pack(fill="both")
#-----------------------------------------------binding arrow keys--------------------

scrolltab2.bind_arrow_keys(tablayout)
#----------------------------------------------binding wheels------------------------
scrolltab2.bind_scroll_wheel(tablayout)
#-------------------------------------------------------------------------------------
#-----------------------------------------------button function call------------------


def sentdata():
    obj = test()  #class object declared
    obj.calculate()  #class object initiated
    obj.getdata(entries, entries2, opbtentry120_var, totentry120_var,
                clbtentry120_var, clvlentry120_var, mrpentry120_var,
                slvlentry120_var)
    #argument passed using object to test class
    obj.display()
    #using class object---->invoke display method in class test
Example #2
0
def weekly_rateing(handle_for_rate):
    try:
        phase = get_all(handle_for_rate)
        phase.get_problem()
        phase.get_probelms_for_phase()

        def search_max_problem(id, level):
            webbrowser.open("http://codeforces.com/problemset/problem/" +
                            level + '/' + str(id))

        weekly_window = Toplevel()
        weekly_window.geometry("505x700")
        weekly_window.title('weekly raiting')
        week_scroll = ScrolledFrame(
            weekly_window,
            width=494,
            height=700,
            bg="#231e1e",
            scrollbars="vertical",
        )
        week_scroll.pack(
            expand=1,
            fill="y",
        )
        week_scroll.bind_arrow_keys(weekly_window)
        week_scroll.bind_scroll_wheel(weekly_window)
        inner_week_frame = week_scroll.display_widget(Frame)  ## main window
        inner_week_frame.config(background="black", )
        ##############################################
        info_fr = Frame(inner_week_frame,
                        height=350,
                        width=490,
                        background="#231e1e")
        phase.get_info()
        image = wget.download("http:" + str(phase.image))
        image = ImageTk.PhotoImage(size=20,
                                   image=Image.open(
                                       phase.image.split('/')[-1]))
        # l = Button(info_fr,image=image).place(rely=0)
        picture = Label(info_fr, image=image).place(rely=0.25, relx=0.05)
        system("del /f " + str(phase.image.split('/')[-1]))
        account_name = Label(info_fr,
                             text="name: " + str(phase.name)).place(rely=0.05,
                                                                    relx=0.3)
        country = Label(info_fr, text="country: " +
                        (str(phase.country))).place(rely=0.15, relx=0.3)
        city = Label(info_fr,
                     text="city: " + (str(phase.city))).place(rely=0.25,
                                                              relx=0.3)
        organization = Label(info_fr,
                             text="Organization: " +
                             (str(phase.Organization))).place(rely=0.35,
                                                              relx=0.3)
        friends = Label(info_fr, text="friend of: " +
                        (str(phase.friends))).place(rely=0.45, relx=0.3)
        rank = Label(info_fr,
                     text="Rank: " + (str(phase.Rank))).place(rely=0.55,
                                                              relx=0.3)
        rating = Label(info_fr,
                       text="Rating: " + (str(phase.Rating))).place(rely=0.65,
                                                                    relx=0.3)
        register = Label(info_fr,
                         text="registered: " + (str(phase.registered))).place(
                             rely=0.75, relx=0.3)
        info_fr.pack(pady=1)
        info_fr.pack(pady=1)
        phase.phase1_info()
        phase1_fr = Frame(
            inner_week_frame,
            width=490,
            height=300,
            bg="#231e1e",
        )
        cur1 = Label(phase1_fr,
                     text="Phase1:",
                     font=('arial', 30),
                     bg='#231e1e',
                     fg='red').place(relx=0, rely=0.05)

        solved1 = Label(phase1_fr,
                        text="problems solved: " +
                        str(len(phase.phase1_solved)),
                        bg="#231e1e").place(relx=0, rely=0.22)
        submittions1 = Label(phase1_fr,
                             text="Submitions: " +
                             str(phase.phase1_submitions),
                             bg="#231e1e").place(relx=0, rely=0.32)
        mxrated1 = Label(phase1_fr,
                         text="Matx Rate Problem: " +
                         str(phase.phase1_max_rated_problem),
                         bg="#231e1e").place(relx=0, rely=0.42)
        av1 = Label(phase1_fr,
                    text="problems Average Rate : " + str(phase.phase1_av),
                    bg="#231e1e").place(relx=0, rely=0.52)
        const1 = Label(phase1_fr,
                       text="contests Participation: " +
                       str(phase.phase1_contestcount),
                       bg="#231e1e").place(relx=0, rely=0.62)
        vir1 = Label(phase1_fr,
                     text="virtual participation: " +
                     str(phase.phase1_virtual_count),
                     bg="#231e1e").place(relx=0, rely=0.72)

        phase1_fr.pack(pady=1)

        #######################################################################################
        phase.phase2_info()
        phase2_fr = Frame(
            inner_week_frame,
            width=490,
            height=300,
            bg="#231e1e",
        )
        cur2 = Label(phase2_fr,
                     text="Phase2:",
                     font=('arial', 30),
                     bg='#231e1e',
                     fg='red').place(relx=0, rely=0.05)

        solved2 = Label(phase2_fr,
                        text="problems solved: " +
                        str(len(phase.phase2_solved)),
                        bg="#231e1e").place(relx=0, rely=0.22)
        submittions2 = Label(phase2_fr,
                             text="Submitions: " +
                             str(phase.phase2_submitions),
                             bg="#231e1e").place(relx=0, rely=0.32)
        mxrated2 = Label(phase2_fr,
                         text="Matx Rate Problem: " +
                         str(phase.phase2_max_rated_problem),
                         bg="#231e1e").place(relx=0, rely=0.42)
        av2 = Label(phase2_fr,
                    text="problems Average Rate : " + str(phase.phase2_av),
                    bg="#231e1e").place(relx=0, rely=0.52)
        conts2 = Label(phase2_fr,
                       text="contests Participation: " +
                       str(phase.phase2_contestcount),
                       bg="#231e1e").place(relx=0, rely=0.62)
        vir2 = Label(phase2_fr,
                     text="virtual participation: " +
                     str(phase.phase2_virtual_count),
                     bg="#231e1e").place(relx=0, rely=0.72)

        phase2_fr.pack(pady=1)

        ###############################################

        phase.phase3_info()
        phase3_fr = Frame(inner_week_frame,
                          width=490,
                          height=300,
                          bg="#231e1e")
        cur3 = Label(phase3_fr,
                     text="Phase3:",
                     font=('arial', 30),
                     bg='#231e1e',
                     fg='red').place(relx=0, rely=0.05)
        solved3 = Label(phase3_fr,
                        text="problems solved: " +
                        str(len(phase.phase3_solved)),
                        bg='#231e1e').place(relx=0, rely=0.22)
        submittions3 = Label(phase3_fr,
                             text="Submitions: " +
                             str(phase.phase3_submitions),
                             bg='#231e1e').place(relx=0, rely=0.32)
        mxrated3 = Label(phase3_fr,
                         text="Matx Rate Problem: " +
                         str(phase.phase3_max_rated_problem),
                         bg='#231e1e').place(relx=0, rely=0.42)
        av3 = Label(phase3_fr,
                    text="problems Average Rate : " + str(phase.phase3_av),
                    bg='#231e1e').place(relx=0, rely=0.52)
        const3 = Label(phase3_fr,
                       text="contests Participation: " +
                       str(phase.phase3_contestcount),
                       bg='#231e1e').place(relx=0, rely=0.62)
        vir3 = Label(phase3_fr,
                     text="virtual participation: " +
                     str(phase.phase3_virtual_count),
                     bg='#231e1e').place(relx=0, rely=0.72)

        phase3_fr.pack(pady=1)

        weekly_window.mainloop()
    except HTTPError:
        warnning = Tk()
        warnning.geometry("300x100")
        warnning.title('warnning')
        warnning.configure(bg="pink")
        warnning.iconbitmap('error.ico')
        l = Label(warnning,
                  text="not valid handle ",
                  font=('arial', 20),
                  fg='red',
                  bg="pink").pack()
        warnning.mainloop()
    except URLError:
        warnning = Tk()
        warnning.geometry("300x100")
        warnning.configure(bg="gray")
        warnning.iconbitmap('error.ico')
        warnning.title('warnning')
        l = Label(warnning,
                  text="please check internet",
                  font=('arial', 20),
                  fg='red',
                  bg='gray').pack()
        warnning.mainloop()
Example #3
0
    def run(self):
        def open_button_path_fun(path):
            return path

        tk.Label(self.window, text='File Size Inspector', font=font.Font(family='Helvetica', size=14, weight='bold')).grid(row=0, column=0)
        tk.Label(self.window, text='').grid(row=1, column=0)

        frame = tk.Frame(self.window)
        tk.Label(frame, text=f'Current path: {Path(self.data_prepare_object.current_path).shorten_path_if_necessary()}', font=font.Font(family='Helvetica', size=12, weight='normal')).grid(row=0, column=0)
        tk.Label(frame, text='   ').grid(row=0, column=1)
        tk.Button(frame, text='CHANGE', command=lambda: [self.change_button_function()]).grid(row=0, column=2)
        frame.grid(row=2, column=0)

        tk.Label(self.window, text='').grid(row=3, column=0)

        sf = ScrolledFrame(self.window, width=520, height=425)
        sf.grid(row=5, column=0)

        sf.bind_arrow_keys(self.window)
        sf.bind_scroll_wheel(self.window)
        sf.focus()

        inner_frame = sf.display_widget(tk.Frame)
        frame = tk.Frame(inner_frame)

        i = 0

        for header_name in list(self.fields_width_dictionary.keys()):
            l_box = tk.Listbox(frame, bg=self.window['bg'], justify=tk.CENTER, relief=tk.GROOVE, width=self.fields_width_dictionary[header_name], height=1, font=font.Font(family='Helvetica', size=10, weight='bold'))
            l_box.insert(0, header_name)
            l_box.grid(row=0, column=i)
            i += 1

        frame.grid(row=5, column=0, sticky='W')

        if len(list(self.data_prepare_object.selected_elements_dictionary.keys())) > self.max_number_of_elements_on_screen:
            tk.Label(self.window, text=f'Showing {self.max_number_of_elements_on_screen} largest elements from this directory.', fg='#e67300', font=font.Font(family='Helvetica', size=10, weight='normal')).grid(row=4, column=0)

        i = 0
        paths = list(self.data_prepare_object.selected_elements_dictionary.keys())
        for entry_path in paths:
            frame = tk.Frame(inner_frame)
            content_dictionary = dict(zip(self.fields, [self.data_prepare_object.selected_elements_dictionary[entry_path].name,
                                                        self.data_prepare_object.selected_elements_dictionary[entry_path].type,
                                                        f'{self.data_prepare_object.selected_elements_dictionary[entry_path].size} {self.data_prepare_object.selected_elements_dictionary[entry_path].size_unit}']))
            j = 0
            for column_name in list(content_dictionary.keys()):
                l_box_name = tk.Listbox(frame, width=self.fields_width_dictionary[column_name], height=1, font=font.Font(family='Helvetica', size=10, weight='normal'))
                l_box_name.insert(0, content_dictionary[column_name])
                l_box_name.grid(row=0, column=j)
                j += 1

            if self.data_prepare_object.selected_elements_dictionary[entry_path].can_open:
                button = tk.Button(frame, text='OPEN', command=lambda c=i: [self.move_function(partial(open_button_path_fun, paths[c]).args[0])])
                button.grid(row=0, column=i+3)

            frame.grid(row=i+7, column=0, sticky='W')
            i += 1

            if i > self.max_number_of_elements_on_screen:
                break

        previous_location = Path(self.data_prepare_object.current_path).get_path_previous_location()
        if previous_location is not None:
            tk.Button(self.window, text='BACK', font=10, command=lambda: [self.move_function(previous_location)]).grid(row=i+8, column=0)

        self.window_on_top_update()
        self.adjust_window_position()
        self.window.mainloop()
Example #4
0
def compare_result(handle1, handle2):
    #url = "https://userpic.codeforces.com/591099/avatar/e5d251220ca54303.jpg"
    try:
        account1 = get_all(handle1)
        account1.get_info()
        account2 = get_all(handle2)
        account2.get_info()
        compare_window = Toplevel()
        compare_window.geometry("810x700")
        compare_scroll = ScrolledFrame(
            compare_window,
            width=800,
            height=700,
            bg="#231e1e",
            scrollbars="vertical",
        )
        compare_scroll.pack(
            expand=1,
            fill="y",
        )
        compare_scroll.bind_arrow_keys(compare_window)
        compare_scroll.bind_scroll_wheel(compare_window)
        inner_compare_frame = compare_scroll.display_widget(
            Frame)  ## main window
        inner_compare_frame.config(background="black", )
        ##############################################              1           ###########################################################
        info1_fr = Frame(
            inner_compare_frame,
            width=390,
            height=250,
            bg="#231e1e",
        )
        image = wget.download("http:" + str(account1.image))
        image = ImageTk.PhotoImage(size=20,
                                   image=Image.open(
                                       account1.image.split('/')[-1]))
        # l = Button(info1_fr,image=image).place(rely=0)
        picture = Label(info1_fr, image=image).place(rely=0.25, relx=0.05)
        system("del /f " + str(account1.image.split('/')[-1]))
        account_name = Label(info1_fr, text="name: " +
                             str(account1.name)).place(rely=0.05, relx=0.3)
        country = Label(info1_fr, text="country: " +
                        (str(account1.country))).place(rely=0.15, relx=0.3)
        city = Label(info1_fr,
                     text="city: " + (str(account1.city))).place(rely=0.25,
                                                                 relx=0.3)
        organization = Label(info1_fr, text="Organization: ").place(rely=0.35,
                                                                    relx=0.3)
        orgnization_info = Label(info1_fr, text=(str(
            account1.Organization))).place(rely=0.45, relx=0.38)
        friends = Label(info1_fr, text="friend of: " +
                        (str(account1.friends))).place(rely=0.55, relx=0.3)
        rank = Label(info1_fr,
                     text="Rank: " + (str(account1.Rank))).place(rely=0.65,
                                                                 relx=0.3)
        rating = Label(info1_fr, text="Rating: " +
                       (str(account1.Rating))).place(rely=0.75, relx=0.3)
        register = Label(info1_fr,
                         text="registered: " +
                         (str(account1.registered))).place(rely=0.85, relx=0.3)
        info1_fr.grid(column=0, row=0, pady=1, padx=1)
        ####################2#################
        info2_fr = Frame(
            inner_compare_frame,
            width=390,
            height=250,
            bg="#231e1e",
        )
        image2 = wget.download("http:" + str(account2.image))
        image2 = ImageTk.PhotoImage(size=20,
                                    image=Image.open(
                                        account2.image.split('/')[-1]))
        # l = Button(info2_fr,image=image).place(rely=0)
        picture = Label(info2_fr, image=image2).place(rely=0.25, relx=0.05)
        system("del /f " + str(account2.image.split('/')[-1]))
        account_name = Label(info2_fr, text="name: " +
                             str(account2.name)).place(rely=0.05, relx=0.3)
        country = Label(info2_fr, text="country: " +
                        (str(account2.country))).place(rely=0.15, relx=0.3)
        city = Label(info2_fr,
                     text="city: " + (str(account2.city))).place(rely=0.25,
                                                                 relx=0.3)
        organization = Label(info2_fr, text="Organization: ").place(rely=0.35,
                                                                    relx=0.3)
        organization_info = Label(info2_fr, text=(str(
            account2.Organization))).place(rely=0.45, relx=0.38)
        friends = Label(info2_fr, text="friend of: " +
                        (str(account2.friends))).place(rely=0.55, relx=0.3)
        rank = Label(info2_fr,
                     text="Rank: " + (str(account2.Rank))).place(rely=0.65,
                                                                 relx=0.3)
        rating = Label(info2_fr, text="Rating: " +
                       (str(account2.Rating))).place(rely=0.75, relx=0.3)
        register = Label(info2_fr,
                         text="registered: " +
                         (str(account2.registered))).place(rely=0.85, relx=0.3)

        info2_fr.grid(column=1, row=0, pady=1, padx=1)
        ####################################################################################################################
        account1.get_problem()
        account2.get_problem()
        languages1_fr = Frame(
            inner_compare_frame,
            width=390,
            height=30 * max(len(account2.languages), len(account1.languages)) +
            80,
            bg="#231e1e",
        )
        v = Label(languages1_fr,
                  text="languages:",
                  font=('arial', 20),
                  fg='red',
                  bg="#231e1e").place(rely=0.0, relx=0)

        i = 4
        for language in account1.languages:
            Label(languages1_fr,
                  text=str(language) + ":    " +
                  str(account1.languages[language]),
                  bg='#231e1e',
                  fg='white').place(relx=0.1, rely=0.05 * i)
            i += 2
        languages1_fr.grid(column=0, row=1, pady=1, padx=1)
        #######################################
        languages2_fr = Frame(
            inner_compare_frame,
            width=390,
            height=30 * max(len(account2.languages), len(account1.languages)) +
            80,
            bg="#231e1e",
        )
        l2 = Label(languages2_fr,
                   text="languages:",
                   font=('arial', 20),
                   fg='red',
                   bg="#231e1e").place(rely=0.0, relx=0)

        i = 4
        for language in account2.languages:
            Label(languages2_fr,
                  text=str(language) + ":" + str(account2.languages[language]),
                  bg='#231e1e',
                  fg='white').place(relx=0.1, rely=0.05 * i)
            i += 2
        languages2_fr.grid(column=1, row=1, pady=1, padx=1)
        ####################################################################################################################
        verdicts1_fr = Frame(
            inner_compare_frame,
            width=390,
            height=30 * max(len(account2.verdict), len(account1.verdict)) + 60,
            bg="#231e1e",
        )
        v = Label(verdicts1_fr,
                  text="verdicts:",
                  font=('arial', 20),
                  fg='red',
                  bg="#231e1e").place(rely=0.0, relx=0)

        i = 3
        if "OK" in account1.verdict:
            Label(verdicts1_fr,
                  text="accepted" + ":" + str(account1.verdict["OK"]),
                  bg='#231e1e',
                  fg='white').place(relx=0.1, rely=0.05 * i)
        else:
            Label(verdicts1_fr, text="accepted:   0", bg='#231e1e',
                  fg='white').place(relx=0.1, rely=0.05 * i)
        i = 5
        for verdict in account1.verdict:
            if verdict != "OK":
                Label(verdicts1_fr,
                      text=str(verdict) + ":" + str(account1.verdict[verdict]),
                      bg='#231e1e',
                      fg='white').place(relx=0.1, rely=0.05 * i)
                i += 2
        verdicts1_fr.grid(column=0, row=2, pady=1, padx=1)
        ##################################################
        verdicts2_fr = Frame(
            inner_compare_frame,
            width=390,
            height=30 * max(len(account2.verdict), len(account1.verdict)) + 60,
            bg="#231e1e",
        )
        v = Label(verdicts2_fr,
                  text="verdicts:",
                  font=('arial', 20),
                  fg='red',
                  bg="#231e1e").place(rely=0.0, relx=0)

        i = 3
        if "OK" in account2.verdict:
            Label(verdicts2_fr,
                  text="accepted" + ":" + str(account2.verdict["OK"]),
                  bg='#231e1e',
                  fg='white').place(relx=0.1, rely=0.05 * i)
        else:
            Label(verdicts2_fr, text="accepted:   0", bg='#231e1e',
                  fg='white').place(relx=0.1, rely=0.05 * i)
        i = 5
        for v in account2.verdict:
            if v != "OK":
                Label(verdicts2_fr,
                      text=str(v) + ":" + str(account2.verdict[v]),
                      bg='#231e1e',
                      fg='white').place(relx=0.1, rely=0.05 * i)
                i += 2

        verdicts2_fr.grid(column=1, row=2, pady=1, padx=1)
        ####################################################################################################################
        level1_fr = Frame(
            inner_compare_frame,
            width=390,
            height=60 *
            max(len(account2.solved_level), len(account1.solved_level)),
            bg="#231e1e")
        l1 = Label(level1_fr,
                   text="levels:",
                   font=('arial', 20),
                   fg='red',
                   bg="#231e1e").place(rely=0.0, relx=0)

        i = 4
        for level in account1.solved_level:
            Label(level1_fr,
                  text=str(level) + ":" + str(account1.solved_level[level]),
                  bg='#231e1e',
                  fg='white').place(relx=0.1, rely=0.05 * i)
            i += 1
        level1_fr.grid(row=3, column=0, pady=1, padx=1)
        ###############################################
        level2_fr = Frame(
            inner_compare_frame,
            width=390,
            height=60 *
            max(len(account2.solved_level), len(account1.solved_level)),
            bg="#231e1e",
        )
        l2 = Label(level2_fr,
                   text="levels:",
                   font=('arial', 20),
                   fg='red',
                   bg="#231e1e").place(rely=0.0, relx=0)
        i = 3
        for level in account2.solved_level:
            Label(level2_fr,
                  text=str(level) + ":" + str(account2.solved_level[level]),
                  bg='#231e1e',
                  fg='white').place(relx=0.1, y=20 * i)
            i += 1
        level2_fr.grid(row=3, column=1, pady=1, padx=1)
        ####################################################################################################################
        account1.get_problem()
        account2.get_problem()
        t_height = 100 * max(len(account2.solved_tages),
                             len(account1.solved_tages)) / 6
        tags1_fr = Frame(
            inner_compare_frame,
            width=390,
            height=t_height,
            bg="#231e1e",
        )
        t = Label(tags1_fr,
                  text="tags:",
                  font=('arial', 20),
                  fg='red',
                  bg="#231e1e").place(rely=0.0, relx=0)
        i = 3
        j = 0
        for tag in account1.solved_tages:
            Label(tags1_fr,
                  text=str(tag),
                  bg='#2' + str(i * j + 10) + 'e1e',
                  fg='#F' + str(i * j + 10) + 'e1e').place(y=(0.02 / 300) * h *
                                                           i * 400,
                                                           x=0.5 * j * 400)
            if j < 1:
                j += 1
            else:
                j = 0
                i += 1
        tags1_fr.grid(row=4, column=0, pady=1, padx=1)
        ################################################

        tags2_fr = Frame(
            inner_compare_frame,
            width=390,
            height=t_height,
            bg="#231e1e",
        )
        t = Label(tags2_fr,
                  text="tags:",
                  font=('arial', 20),
                  fg='red',
                  bg="#231e1e").place(rely=0.0, relx=0)
        #t1=Frame(tags2_fr,bg='#231e1e')
        i = 3
        j = 0
        for tag in account2.solved_tages:
            Label(tags2_fr,
                  text=str(tag),
                  bg='#2' + str(i * j + 10) + 'e1e',
                  fg='#F' + str(i * j + 10) + 'e1e').place(y=(0.02 / 300) * h *
                                                           i * 400,
                                                           x=0.5 * j * 400)
            if j < 1:
                j += 1
            else:
                j = 0
                i += 1
        #t1.pack()
        tags2_fr.grid(row=4, column=1, pady=1, padx=1)
        ####################################################################################################################
        extras1_fr = Frame(
            inner_compare_frame,
            width=390,
            height=300,
            bg="#231e1e",
        )
        account1.get_contest()
        Label(extras1_fr,
              text='tryed: ' + str(account1.tryed_problem),
              fg='red',
              bg="#231e1e").place(rely=0.05)
        Label(extras1_fr,
              text='solved problems: ' +
              str(account1.tryed_problem - len(account1.unsolved_problem)),
              fg='red',
              bg="#231e1e").place(rely=0.15)
        Label(extras1_fr,
              text='nomber of contests: ' + str(account1.number_of_contests),
              fg='red',
              bg="#231e1e").place(rely=0.25)
        Label(extras1_fr,
              text='Best rank: ' + str(account1.Best_Rank),
              fg='red',
              bg="#231e1e").place(rely=0.35)
        Label(extras1_fr,
              text='worst rank: ' + str(account1.worst_Rank),
              fg='red',
              bg="#231e1e").place(rely=0.45)
        Label(extras1_fr,
              text='max up: ' + str(account1.max_up),
              fg='red',
              bg="#231e1e").place(rely=0.55)
        Label(extras1_fr,
              text='max down: ' + str(account1.max_down),
              fg='red',
              bg="#231e1e").place(rely=0.65)
        extras1_fr.grid(row=5, column=0, pady=1, padx=1)
        ############################################
        extras2_fr = Frame(
            inner_compare_frame,
            width=390,
            height=300,
            bg="#231e1e",
        )
        account2.get_contest()
        Label(extras2_fr,
              text='tryed: ' + str(account2.tryed_problem),
              fg='red',
              bg="#231e1e").place(rely=0.05)
        Label(extras2_fr,
              text='solved problems: ' +
              str(account2.tryed_problem - len(account2.unsolved_problem)),
              fg='red',
              bg="#231e1e").place(rely=0.15)
        Label(extras2_fr,
              text='nomber of contests: ' + str(account2.number_of_contests),
              fg='red',
              bg="#231e1e").place(rely=0.25)
        Label(extras2_fr,
              text='Best rank: ' + str(account2.Best_Rank),
              fg='red',
              bg="#231e1e").place(rely=0.35)
        Label(extras2_fr,
              text='worst rank: ' + str(account2.worst_Rank),
              fg='red',
              bg="#231e1e").place(rely=0.45)
        Label(extras2_fr,
              text='max up: ' + str(account2.max_up),
              fg='red',
              bg="#231e1e").place(rely=0.55)
        Label(extras2_fr,
              text='max down: ' + str(abs(account2.max_down)),
              fg='red',
              bg="#231e1e").place(rely=0.65)
        extras2_fr.grid(row=5, column=1, pady=1, padx=1)
        ####################################################################################################################
        unsolved1_fr = Frame(
            inner_compare_frame,
            width=390,
            height=30 * max(len(account1.unsolved_problem),
                            len(account2.unsolved_problem)) / 1.5 + 40,
            bg="#231e1e",
        )
        i = 4

        def serach_problem(index, contestid):
            webbrowser.open("http://codeforces.com/problemset/problem/" +
                            str(contestid) + '/' + str(index))

        un1 = Label(unsolved1_fr,
                    text='unsolved:',
                    font=('arial', 20),
                    bg="#231e1e",
                    fg='red').place(rely=0.0, relx=0)
        j = 0
        for problem in account1.unsolved_problem:
            Button(unsolved1_fr,
                   text=str(problem['index']) + '-' +
                   str(problem['contestId']),
                   bg='brown',
                   command=lambda: serach_problem(problem['index'], problem[
                       'contestId'])).place(y=0.4 * i * 10, relx=0.5 * j)
            if j == 1: j = -1
            j += 1
            if j == 0: i += 1
        unsolved1_fr.grid(row=6, column=0, pady=1, padx=1)
        ####################################
        unsolved2_fr = Frame(
            inner_compare_frame,
            width=390,
            height=30 * max(len(account1.unsolved_problem),
                            len(account2.unsolved_problem)) / 1.5 + 40,
            bg="#231e1e",
        )
        i = 4

        def serach_problem(index, contestid):
            webbrowser.open("http://codeforces.com/problemset/problem/" +
                            str(contestid) + '/' + str(index))

        un2 = Label(unsolved2_fr,
                    text='unsolved:',
                    font=('arial', 20),
                    bg="#231e1e",
                    fg='red').place(rely=0.0, relx=0)
        j = 0
        for problem in account2.unsolved_problem:
            Button(unsolved2_fr,
                   bg='brown',
                   text=str(problem['index']) + '-' +
                   str(problem['contestId']),
                   command=lambda: serach_problem(problem['index'], problem[
                       'contestId'])).place(y=0.4 * i * 10, relx=0.5 * j)
            if j == 1: j = -1
            j += 1
            if j == 0: i += 5
        unsolved2_fr.grid(row=6, column=1, pady=1, padx=1)

        compare_window.mainloop()
    except HTTPError:
        warnning = Tk()
        warnning.geometry("300x100")
        warnning.title('warnning')
        warnning.configure(bg="pink")
        warnning.iconbitmap('error.ico')
        l = Label(warnning,
                  text="not valid handle ",
                  font=('arial', 20),
                  fg='red',
                  bg="pink").pack()
        warnning.mainloop()
    except URLError:
        warnning = Tk()
        warnning.geometry("300x100")
        warnning.configure(bg="gray")
        warnning.iconbitmap('error.ico')
        warnning.title('warnning')
        l = Label(warnning,
                  text="please check internet",
                  font=('arial', 20),
                  fg='red',
                  bg='gray').pack()
        warnning.mainloop()
Example #5
0
def search_result(handle):  ##### pop up of search window
    #url = "https://userpic.codeforces.com/591099/avatar/e5d251220ca54303.jpg"
    try:
        account = get_all(handle)
        res_file = Toplevel()
        res_file.geometry("520x700")
        res_sf = ScrolledFrame(
            res_file,
            width=500,
            height=700,
            bg="#231e1e",
            scrollbars="vertical",
        )
        res_sf.pack(
            expand=1,
            fill="y",
        )
        res_sf.bind_arrow_keys(res_file)
        res_sf.bind_scroll_wheel(res_file)
        inner_frame = res_sf.display_widget(Frame)  ## main window
        inner_frame.config(background="black", )
        ##############################################################################
        info_fr = Frame(inner_frame,
                        height=350,
                        width=490,
                        background="#231e1e")
        account.get_info()
        image = wget.download("http:" + str(account.image))
        image = ImageTk.PhotoImage(size=20,
                                   image=Image.open(
                                       account.image.split('/')[-1]))
        # l = Button(info_fr,image=image).place(rely=0)
        picture = Label(info_fr, image=image).place(rely=0.25, relx=0.05)
        system("del /f " + str(account.image.split('/')[-1]))
        account_name = Label(info_fr, text="name: " + str(account.name)).place(
            rely=0.05, relx=0.3)
        country = Label(info_fr, text="country: " +
                        (str(account.country))).place(rely=0.15, relx=0.3)
        city = Label(info_fr,
                     text="city: " + (str(account.city))).place(rely=0.25,
                                                                relx=0.3)
        organization = Label(info_fr,
                             text="Organization: " +
                             (str(account.Organization))).place(rely=0.35,
                                                                relx=0.3)
        friends = Label(info_fr, text="friend of: " +
                        (str(account.friends))).place(rely=0.45, relx=0.3)
        rank = Label(info_fr,
                     text="Rank: " + (str(account.Rank))).place(rely=0.55,
                                                                relx=0.3)
        rating = Label(info_fr, text="Rating: " + (str(account.Rating))).place(
            rely=0.65, relx=0.3)
        register = Label(info_fr,
                         text="registered: " +
                         (str(account.registered))).place(rely=0.75, relx=0.3)
        info_fr.pack(pady=1)
        ###############################################################################
        account.get_problem()
        languages_fr = Frame(inner_frame,
                             height=30 * len(account.languages) + 20,
                             width=490,
                             background="#231e1e")
        i = 3
        Label(languages_fr,
              text="languages:",
              font=('arial', 20),
              fg='red',
              bg="#231e1e").place(rely=0, relx=0)
        for language in account.languages:
            Label(languages_fr,
                  text=str(language) + ":" + str(account.languages[language]),
                  fg='white',
                  bg="#231e1e").place(relx=0.1,
                                      rely=0.5 / len(account.languages) * i)
            i += 1
        languages_fr.pack(pady=1)
        ##############################################
        vlen = 50 * len(account.verdict) + 10
        verdicts_fr = Frame(inner_frame,
                            height=vlen,
                            width=490,
                            background="#231e1e")
        i = 3
        Label(verdicts_fr,
              text="verdicts:",
              font=('arial', 20),
              fg='red',
              bg="#231e1e").place(rely=0, relx=0)
        for verdict in account.verdict:
            if verdict == "OK":
                Label(verdicts_fr,
                      text="accepted" + ":" + str(account.verdict["OK"]),
                      fg='white',
                      bg="#231e1e").place(relx=0.1,
                                          rely=0.3 / len(account.verdict) * i)
            if verdict != "OK":
                Label(verdicts_fr,
                      text=str(verdict) + ":" + str(account.verdict[verdict]),
                      fg='white',
                      bg="#231e1e").place(relx=0.1,
                                          rely=0.3 / len(account.verdict) * i)
            i += 2
        verdicts_fr.pack(pady=1)
        #################################################
        llen = 50 * len(account.solved_level) + 10
        levels_fr = Frame(inner_frame,
                          height=llen,
                          width=490,
                          background="#231e1e")
        i = 5
        Label(levels_fr,
              text="levels:",
              font=('arial', 20),
              fg='red',
              bg="#231e1e").place(rely=0, relx=0)
        for level in account.solved_level:
            Label(levels_fr,
                  fg='white',
                  bg="#231e1e",
                  text=str(level) + ":" +
                  str(account.solved_level[level])).place(
                      relx=0.1, rely=0.3 / (len(account.solved_level)) * i)
            i += 2
        levels_fr.pack(pady=1)
        #####################################################
        t_height = 100 * len(account.solved_tages) / 6
        tags_fr = Frame(
            inner_frame,
            width=490,
            height=t_height,
            bg="#231e1e",
        )
        t = Label(tags_fr,
                  text="tags:",
                  font=('arial', 20),
                  fg='red',
                  bg="#231e1e").place(rely=0.0, relx=0)
        i = 2
        j = 0
        for tag in account.solved_tages:
            Label(tags_fr,
                  text=str(tag),
                  bg='#2' + str(i * j + 10) + 'e1e',
                  fg='#F' + str(i * j + 10) + 'e1e').place(
                      rely=(1.5 / len(account.solved_tages)) * i, relx=0.5 * j)
            if j < 1:
                j += 1
            else:
                j = 0
                i += 1
        tags_fr.pack(pady=1)
        ######################################################
        extras_fr = Frame(inner_frame,
                          height=350,
                          width=490,
                          background="#231e1e")
        account.get_contest()
        t = Label(extras_fr,
                  text="Extra:",
                  font=('arial', 20),
                  fg='red',
                  bg="#231e1e").place(rely=0.0, relx=0)
        Label(extras_fr,
              text='tryed: ' + str(account.tryed_problem),
              fg='white',
              bg="#231e1e").place(rely=0.15)
        Label(
            extras_fr,
            fg='white',
            bg="#231e1e",
            text='solved problems: ' +
            str(account.tryed_problem - len(account.unsolved_problem))).place(
                rely=0.25)

        Label(extras_fr,
              fg='white',
              bg="#231e1e",
              text='nomber of contests: ' +
              str(account.number_of_contests)).place(rely=0.35)
        Label(extras_fr,
              fg='white',
              bg="#231e1e",
              text='Best rank: ' + str(account.Best_Rank)).place(rely=0.45)
        Label(extras_fr,
              fg='white',
              bg="#231e1e",
              text='worst rank: ' + str(account.worst_Rank)).place(rely=0.55)
        Label(extras_fr,
              fg='white',
              bg="#231e1e",
              text='max up: ' + str(account.max_up)).place(rely=0.65)
        Label(extras_fr,
              fg='white',
              bg="#231e1e",
              text='max down: ' + str(account.max_down)).place(rely=0.75)
        extras_fr.pack(pady=1)
        ##############################################
        unslen = 30 * (len(account.unsolved_problem) + 1) / 2 + 100

        unsolved_fr = Frame(inner_frame,
                            width=490,
                            height=unslen,
                            background="#231e1e")
        i = 5

        def serach_problem(index, contestid):
            webbrowser.open("http://codeforces.com/problemset/problem/" +
                            str(contestid) + '/' + str(index))

        j = 0
        unstext = Label(unsolved_fr,
                        text="unsolved practice problems:",
                        font=('arial', 20)).place(rely=0, relx=0)
        print(len(account.unsolved_problem))
        for problem in account.unsolved_problem:
            Button(unsolved_fr,
                   bg='brown',
                   text=str(problem['index']) + '-' +
                   str(problem['contestId']),
                   command=lambda: serach_problem(problem['index'], problem[
                       'contestId'])).place(rely=0.05 * i, relx=0.5 * j)
            if j == 1:
                j = -1
            if j == -1:
                i += 3

            j += 1

        unsolved_fr.pack(pady=1)
        # image = wget.download("http:"+str(account.image))
        # image=ImageTk.PhotoImage(Image.open(account.image.split('/')[-1]))
        # cann = Label(fr, width=20, height=10, borderwidth=0, highlightthickness=0, relief='ridge', text='hi', bg='white')
        # cann.pack()
        # cann.place(relx=0.01, rely=0.2)
        # system("rm "+account.image.split('/')[-1])
        # can = Canvas(inner_frame,bg='black')
        # can.create_window(0, 0, anchor=NW, window=fr)
        # can.pack(pady=0, padx=0)

        # can.pack()
        res_file.mainloop()
        # inner_frame.
        ###############################################################
    # get_all(handle)

    except HTTPError:
        warnning = Tk()
        warnning.geometry("300x100")
        warnning.title('warnning')
        warnning.configure(bg="pink")
        warnning.iconbitmap('error.ico')
        l = Label(warnning,
                  text="not valid handle ",
                  font=('arial', 20),
                  fg='red',
                  bg="pink").pack()
        warnning.mainloop()
    except URLError:
        warnning = Tk()
        warnning.geometry("300x100")
        warnning.configure(bg="gray")
        warnning.iconbitmap('error.ico')
        warnning.title('warnning')
        l = Label(warnning,
                  text="please check internet",
                  font=('arial', 20),
                  fg='red',
                  bg='gray').pack()
        warnning.mainloop()
def print_news():
    news_data = []
    files = glob.glob("*.json")
    for data_file in files:
        f = open(data_file)
        try:
            data = json.load(f)
            # data1= json.dump(data)
            if data["status"] == "ok" and data["totalResults"] > 0:
                news_data.append(data)

        except:
            print('Error')

    # GUI
    data_frame = tk.Frame(window)
    data_frame.pack(side="left", expand=0, fill="y")

    sf = ScrolledFrame(data_frame, width=1178, bg='#ffffff')
    sf.pack(side="left", expand=1, fill="y")

    # Bind the arrow keys and scroll wheel
    sf.bind_arrow_keys(window)
    sf.bind_scroll_wheel(window)

    frame = sf.display_widget(tk.Frame)
    frame['bg'] = '#E8E7F7'
    frame['bd'] = 15
    frame['relief'] = 'sunken'

    for news_list in news_data:
        for news in news_list['articles']:
            # Title Label
            l = tk.Label(text=news['title'].title(),
                         fg='#3f0052',
                         wraplength=1120,
                         master=frame,
                         font="-size 18 -weight bold",
                         justify='left',
                         pady='10')
            l.pack()

            # Description Label
            l = tk.Label(text=news['description'],
                         bg='#DEDEDE',
                         fg='#3f0052',
                         wraplength=1120,
                         master=frame,
                         font="-size 14",
                         justify='left',
                         padx='15')
            l.pack()

            # Separator
            l = tk.Label(
                text=
                '--------------------------------------------------------------------------------------------------',
                fg='#3f0052',
                wraplength=1120,
                master=frame,
                font="-size 14",
                justify='left',
                pady='25')
            l.pack()

    window.mainloop()
frame1=Frame(master2,bd=10,height=500,padx=10,pady=10,width=1500)
v = StringVar(frame1)
frame1.pack()
slotA=[]
slotB=[]
slotC=[]
slotD=[]
slotE=[]
slotF=[]
slotG=[]
slotH=[]
sf = ScrolledFrame(master2, width=640, height=480)
sf.pack(side="top", expand=1, fill="both")

# Bind the arrow keys and scroll wheel
sf.bind_arrow_keys(master2)
sf.bind_scroll_wheel(master2)

# Create a frame within the ScrolledFrame
frame2 = sf.display_widget(Frame)

classes=['No Classroom','A1-3','A1-NKN','A5-1','A5-2','A5-4','A5-5','A9-1','SC-NKN','G-106,107','A10-1a','A10-1b','A10-1c','A10-1d','A10-2a','A10-2b','A10-2c','A10-3a','A10-3b','A10-3c','Hall A','Hall B','Hall C','A13-1A','A13-3A','A13-2A','A13-2B','A13-2C','A13-2D']
def ConstraintCheck(var,i,name,slot,*args):
    for j in range(len(slot)):
        if(i==j):
            continue
        elif(var.get()!="No Classroom" and var.get()==slot[j][1]):
            messagebox.showerror("Error", var.get() + " is twice time and it will not be saved so please change ") 
            var.set(slot[i][1])
            return
    slot[i][1]=var.get()
Example #8
0
class CardsArea(tk.Frame):
    def __init__(self, master, app, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)
        self.app = app
        self.currentPageNumber = 1
        self.numberOfPages = 1
        self.areaMode = FULL_MODE  # or 'simple'
        self.TABLE_HEIGHT = int(self.app.winfo_screenheight() * 0.5)
        self.TABLE_WIDTH = int(self.app.winfo_screenwidth() * 0.4)

        # self.table = CardsGrid(self)
        self.scrolledFrameContainter = tk.Frame(self)
        self.scrolledFrameContainter.pack(fill=tk.BOTH, expand=1)
        self.scrolledFrame = ScrolledFrame(self.scrolledFrameContainter,
                                           height=self.TABLE_HEIGHT,
                                           width=self.TABLE_WIDTH)
        self.scrolledFrame.pack(fill=tk.BOTH, expand=1)
        self.scrolledFrame.bind_arrow_keys(self)
        self.scrolledFrame.bind_scroll_wheel(self.scrolledFrameContainter)

        self.table = self.scrolledFrame.display_widget(tk.Frame)

        self.statusPanel = tk.LabelFrame(self)
        self.statusPanel.pack(fill=tk.X, anchor=tk.E, side=tk.BOTTOM)

        self.statusPanel.toLeftButton = tk.Button(self.statusPanel, text='\u21E6 Prev',
                                                  font='Helvetica 12 bold',
                                                  command=self.to_prev_page)
        self.statusPanel.toRightButton = tk.Button(self.statusPanel, text='\u21E8 Next',
                                                   font='Helvetica 12 bold',
                                                   command=self.to_next_page)
        self.statusPanel.currentPageLabel = tk.Label(self.statusPanel,
                                                     text='Page %d of %d' %
                                                          (self.currentPageNumber, self.numberOfPages)
                                                     )

    def set_mode_full(self):
        self.areaMode = FULL_MODE

    def set_mode_simple(self):
        self.areaMode = SIMPLE_MODE

    def init_panels(self):
        if self.table.winfo_exists() == 0:
            # self.table = CardsGrid(self)
            self.table = self.table = ScrolledFrame(self, width=self.TABLE_WIDTH, height=self.TABLE_HEIGHT)
            self.table.pack(fill=tk.BOTH)
        if self.statusPanel.winfo_exists() == 0:
            self.statusPanel = tk.LabelFrame(self)
            self.statusPanel.pack(fill=tk.X)

    def show_page(self, page_number=1):
        rows_per_page = self.app.userCardsControlPanel.rowsPerPageVar.get()
        cols_per_page = self.app.userCardsControlPanel.colsPerPageVar.get()

        if self.areaMode == FULL_MODE:
            # number_of_records = self.app.userCards.size
            number_of_records = self.app.userCards.arrFilterSize
        elif self.areaMode == SIMPLE_MODE:
            number_of_records = self.app.simpleCards.size()
        else:
            number_of_records = self.app.simpleCards.size()

        left_index = (page_number - 1) * rows_per_page * cols_per_page
        right_index = page_number * rows_per_page * cols_per_page - 1
        if number_of_records - 1 < right_index:
            right_index = number_of_records - 1
        self.numberOfPages = ceil(number_of_records / (rows_per_page * cols_per_page))

        for elem in self.table.winfo_children():
            if type(elem) == UserCardView:
                elem.destroy()

        cur_record_num = left_index
        cur_row_num = 1
        cur_col_num = 1

        while cur_record_num <= right_index and cur_record_num < number_of_records:
            if self.areaMode == FULL_MODE:
                cur_card = UserCardView(self.table, self.app, self.app.userCards.get(cur_record_num))
            elif self.areaMode == SIMPLE_MODE:
                cur_card = SimpleCardView(self.table, self.app.simpleCards[cur_record_num])
            else:
                cur_card = SimpleCardView(self.table, self.app.simpleCards[cur_record_num])

            cur_card.grid(row=cur_row_num, column=cur_col_num, padx=10, pady=10)

            cur_col_num += 1
            if cur_col_num > cols_per_page:
                cur_col_num = 1
                cur_row_num += 1
            cur_record_num += 1

        self.draw_status_elements()

    def draw_status_elements(self):
        if self.statusPanel.toLeftButton.winfo_ismapped() == 0:
            self.statusPanel.toLeftButton.pack(side=tk.LEFT)
        if self.statusPanel.currentPageLabel.winfo_ismapped() == 0:
            self.statusPanel.currentPageLabel.pack(side=tk.LEFT, fill=tk.X, expand=1)
        if self.statusPanel.toRightButton.winfo_ismapped() == 0:
            self.statusPanel.toRightButton.pack(side=tk.RIGHT)

        if self.currentPageNumber <= 1:
            self.statusPanel.toLeftButton['state'] = tk.DISABLED
        else:
            self.statusPanel.toLeftButton['state'] = tk.NORMAL

        if self.currentPageNumber >= self.numberOfPages:
            self.statusPanel.toRightButton['state'] = tk.DISABLED
        else:
            self.statusPanel.toRightButton['state'] = tk.NORMAL

        self.statusPanel.currentPageLabel['text'] = 'Page %d of %d' % (self.currentPageNumber, self.numberOfPages)

    def to_prev_page(self):
        if self.currentPageNumber > 1:
            self.currentPageNumber -= 1
            self.show_page(page_number=self.currentPageNumber)

    def to_next_page(self):
        if self.currentPageNumber < self.numberOfPages:
            self.currentPageNumber += 1
            self.show_page(page_number=self.currentPageNumber)
Example #9
0
def draw_frame_2(elapsed_time, root):
    sf = ScrolledFrame(root, bg=greenILike)
    sf.place(relwidth=1, relheight=1)

    sf.bind_arrow_keys(root)
    sf.bind_scroll_wheel(root)

    frame2 = sf.display_widget(Frame, bg=greenILike)

    l = tk.Label(frame2,
                 text="Sorted Results",
                 font=('Helvetica', 30, 'normal'),
                 bg=greenILike)
    st = "Time taken:  " + str(elapsed_time)
    l1 = tk.Label(frame2,
                  text=st,
                  font=('Helvetica', 15, "normal"),
                  bg=greenILike)
    l.grid(row=0, column=1, columnspan=4)
    l1.grid(row=1, column=1, columnspan=4)

    tk.Label(frame2,
             padx=20,
             text="Name",
             font=('Helvetica', 12, 'bold'),
             bg=greenILike).grid(row=2, column=0, pady=2, sticky='w')
    tk.Label(frame2,
             text="Time",
             font=('Helvetica', 12, 'bold'),
             bg=greenILike).grid(row=2, column=2, pady=2)
    tk.Label(frame2,
             padx=10,
             text="Calories",
             font=('Helvetica', 12, 'bold'),
             bg=greenILike).grid(row=2, column=3, pady=2)
    tk.Label(frame2,
             padx=10,
             text="Steps",
             font=('Helvetica', 12, 'bold'),
             bg=greenILike).grid(row=2, column=4, pady=2)
    tk.Label(frame2,
             padx=10,
             text="No Ingredients",
             font=('Helvetica', 12, 'bold'),
             bg=greenILike).grid(row=2, column=5, pady=2)
    tk.Label(frame2,
             padx=20,
             text="Ingredients",
             font=('Helvetica', 12, 'bold'),
             bg=greenILike).grid(row=2,
                                 column=6,
                                 columnspan=2,
                                 pady=2,
                                 sticky='w')
    for i in range(3, min(len(recipe_list.recipes) - 1, 300)):
        tk.Label(frame2,
                 padx=20,
                 text=recipe_list.recipes[i - 3].name,
                 bg=greenILike).grid(row=i,
                                     column=0,
                                     columnspan=2,
                                     pady=2,
                                     sticky='w')
        tk.Label(frame2,
                 text=str(recipe_list.recipes[i - 3].minutes),
                 bg=greenILike).grid(row=i, column=2, pady=2)
        tk.Label(frame2,
                 text=str(recipe_list.recipes[i - 3].calories),
                 bg=greenILike).grid(row=i, column=3, pady=2)
        tk.Label(frame2,
                 text=str(recipe_list.recipes[i - 3].n_s),
                 bg=greenILike).grid(row=i, column=4, pady=2)
        tk.Label(frame2,
                 text=str(recipe_list.recipes[i - 3].n_i),
                 bg=greenILike).grid(row=i, column=5, pady=2)
        tk.Label(frame2,
                 padx=20,
                 text=recipe_list.recipes[i - 3].ing_info(),
                 bg=greenILike).grid(row=i,
                                     column=6,
                                     columnspan=2,
                                     pady=2,
                                     sticky='w')

    button3 = tk.Button(frame2,
                        text="GO BACK",
                        bg='yellow',
                        command=lambda: goBack(root))
    button3.grid(row=0, column=5)
Example #10
0
def create_columns_skeleton(currentValue, hasSearch):

    show_scroll = tk.Label(canvas,
                           text="Choose word to replace",
                           bg='#6DD5ED',
                           bd=10)
    show_scroll.place(relx=0.5,
                      rely=0.4,
                      relwidth=0.8,
                      relheight=0.05,
                      anchor='n')
    sf = ScrolledFrame(canvas)
    sf.place(relx=0.5, rely=0.45, relwidth=0.8, relheight=0.35, anchor='n')

    # Bind the arrow keys and scroll wheel
    sf.bind_arrow_keys(canvas)
    sf.bind_scroll_wheel(canvas)

    # Create a frame within the ScrolledFrame
    inner_frame = sf.display_widget(tk.Frame)

    general_checkbuttons = {}
    col = 3
    counterX = 0
    counterY = 0
    arrayAns = []
    global general_var
    # print(currentValue)
    # currentValue=["A","B","C","D","A","B","C","D","A","B","C","D","A","B","C","D"]
    root.grid_columnconfigure(4, minsize=50)

    for i in range(len(currentValue)):
        textVal = str(currentValue[i]
                      ) if currentValue[i] == currentValue[i] else "<Blank>"
        if hasSearch:
            var = general_var[textVal]
        else:
            var = tk.IntVar()
        for y in range(col):
            if counterX % col != 0 or i == 0:

                cal = i % col
                cb = tk.Checkbutton(inner_frame,
                                    font=(None, 12),
                                    variable=var,
                                    text=textVal,
                                    wraplength=250)
                cb.grid(row=counterY, column=cal, sticky="w", pady=1, padx=1)
                general_checkbuttons[i] = cb
                general_var[textVal] = var
                break
            elif counterX % col == 0:
                cal = i % col

                counterY += 1
                cb = tk.Checkbutton(inner_frame,
                                    font=(None, 12),
                                    variable=var,
                                    text=textVal,
                                    wraplength=250)

                cb.grid(row=counterY, column=cal, sticky="w", pady=1, padx=1)
                general_checkbuttons[i] = cb
                general_var[textVal] = var
                break

        counterX += 1
    if not hasSearch:
        return general_checkbuttons
    def __init__(self, win):

        sf = ScrolledFrame(win, width=1510, height=620)
        sf.place(x=0, y=152)
        # sf.pack(side="top",expand=1,fill="both")

        sf.bind_arrow_keys(win)
        sf.bind_scroll_wheel(win)

        canvas = sf.display_widget(Canvas)
        canvas.config( width=1610, height=1200)

        mydb = mysql.connector.connect(host="localhost", user="******", passwd="Meezan#2018", database="ice_creame")
        list5 = []

        cursor = mydb.cursor()
        cursor.execute("select bill_id from bill_records")
        list6 = cursor.fetchall()

        cursor.execute("select bill_date from bill_records")
        list1 = cursor.fetchall()
        # print(tabulate(list))

        cursor.execute("select customer_name from bill_records")
        list2 = cursor.fetchall()

        cursor.execute("select pro_name from bill_records")
        list3 = cursor.fetchall()

        cursor.execute("select pro_quantity from bill_records")
        list4 = cursor.fetchall()

        cursor.execute("select sub_total from bill_records")
        list5 = cursor.fetchall()

        title1 = Label(canvas,  text="Bill ID", font=("calibri Bold", 15)).place(x=70, y=90)

        title2 = Label(canvas,  text="Date", font=("calibri Bold", 15)).place(x=190, y=90)

        title3 = Label(canvas,  text="Customer", font=("calibri Bold", 15)).place(x=280, y=90)

        title4 = Label(canvas,  text="Products", font=("calibri Bold", 15)).place(x=700, y=90)

        title5 = Label(canvas,  text="Quantity", font=("calibri Bold", 15)).place(x=1220, y=90)

        title6 = Label(canvas,  text="Sub Total", font=("calibri Bold", 15)).place(x=1350, y=90)

        ym1 = 90
        for m in range(0, list6.__len__()):
            label = Label(canvas,  text=list6[m], font=("calibri regular", 15))
            ym1 = ym1 + 40
            label.place(x=70, y=ym1)

        l1 = list(list1)
        ind = 0

        ym2 = 0
        y1 = 100
        y2 = 90
        for m in range(0, list1.__len__()):
            a = str(l1[ind])

            c = a.replace("('", "")
            d = c.replace("',)", "")

            label = Label(canvas,  text=d, font=("calibri regular", 15))
            y2 = y2 + 40
            ind = ind + 1
            label.place(x=140, y=y2)
            y1 = y2 + 35
            ym2 = y1
            canvas.create_line(40, y1, 1450, y1, fill='black')

        y2 = 90

        for i in range(0, list2.__len__()):
            label = Label(canvas,  text=list2[i], font=("calibri regular", 15))
            y2 = y2 + 40
            label.place(x=290, y=y2)

        canvas.create_line(40, 80, 1450, 80, fill='black')

        canvas.create_line(40, 120, 1450, 120, fill='black')

        canvas.create_line(40, 80, 40, ym2, fill='black')
        canvas.create_line(130, 80, 130, ym2, fill='black')
        canvas.create_line(250, 80, 250, ym2, fill='black')
        canvas.create_line(390, 80, 390, ym2, fill='black')
        canvas.create_line(1200, 80,1200, ym2, fill='black')
        canvas.create_line(1320, 80,1320, ym2, fill='black')
        canvas.create_line(1450, 80,1450, ym2, fill='black')

        '''l3 = list(list3)
        ind = 0
        print(l3)'''

        y2 = 90
        for i in range(0, list3.__len__()):
            '''a = str(l3[ind])

            c = a.replace("('", "")
            d = c.replace("',)", "")'''

            label = Label(canvas,  text=list3[i], font=("calibri regular", 15))
            y2 = y2 + 40
            label.place(x=430, y=y2)

        y2 = 90
        for i in range(0, list4.__len__()):
            label = Label(canvas,  text=list4[i], font=("calibri regular", 15))
            y2 = y2 + 40
            label.place(x=1240, y=y2)



        y2 = 90
        for i in range(0,list5.__len__()):


            label = Label(canvas,  text=list5[i], font=("calibri regular", 15))
            y2 = y2 + 40
            ind = ind + 1
            label.place(x=1370, y=y2)
Example #12
0
class LinksDialog(Toplevel):
    def __init__(self, parent, flow: CurrentFlowModel, callback: Callable):
        super().__init__(parent)
        self._flow = flow
        self._callback = callback
        # Do the dialog modal
        self.transient(parent)
        self.grab_set()
        # Define the dialog size
        self.title('Configure:')
        self.geometry("550x845+%d+%d" %
                      (parent.winfo_rootx() + 920, parent.winfo_rooty() + 30))
        self.resizable(height=FALSE, width=FALSE)

        self.grid()
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.rowconfigure(1, weight=20)
        self.rowconfigure(2, weight=1)

        self._info = LabelFrame(self)
        self._info.columnconfigure(0, weight=1)
        self._info.columnconfigure(1, weight=5)
        self._info_lbl = Label(self._info, text='flow info:')
        self._info_lbl.grid(row=0, column=0, sticky=W)
        self._info_name_var = StringVar()
        self._info_name_var.set(flow.flow.info)
        self._info_entry = Entry(self._info,
                                 width=50,
                                 textvariable=self._info_name_var)
        self._info_entry.grid(row=0,
                              column=1,
                              padx=PADX,
                              pady=PADY,
                              sticky=W + E + N + S)
        self._info.grid(row=0,
                        column=0,
                        columnspan=2,
                        padx=PADX,
                        pady=PADY,
                        sticky=W + E + N + S)

        # Content will be scrolable
        self.content = ScrolledFrame(self)
        # Bind the arrow keys and scroll wheel
        self.content.bind_arrow_keys(self)
        self.content.bind_scroll_wheel(self)
        # Create the ContentView frame within the ScrolledFrame
        self.content_view = self.content.display_widget(ContentView)
        self.content_view.init_content(flow)
        self.content.grid(row=1,
                          column=0,
                          padx=PADX,
                          pady=PADY,
                          sticky=W + E + N + S)

        self.actions_frame = LdActionsFrame(self)
        self.actions_frame.grid(row=2,
                                column=0,
                                padx=PADX,
                                pady=PADY,
                                sticky=W + E + N + S)

        return

    def apply(self) -> None:
        self.content_view.update_flow()
        self._flow.flow = copy.deepcopy(self.content_view.tmp_flow)
        self._flow.flow.info = self._info_name_var.get()
        self._callback()
        self.destroy()
        return

    def cancel(self) -> None:
        self.destroy()
        return
def print_news():
    news_data = []
    files = glob.glob("*.json")
    for data_file in files:
        f = open(data_file)
        try:
            data = json.load(f)
            news_data.append(data)
        except:
            print('Error')
    # GUI

    # canvas.pack(side='left', fill='y')

    # vsb = tk.Scrollbar(window, orient="vertical", command=canvas.yview)
    # vsb.pack(side='right', fill='y')

    # canvas.configure(yscrollcommand=vsb.set)
    # canvas.bind('<Configure>', on_configure)

    # data_frame = tk.Frame(window, bg='#d7d5f7', height='800', width='1200', bd=0)
    # canvas.create_window((0, 0), window=data_frame, anchor='nw')

    data_frame = tk.Frame(window)
    data_frame.pack(side="left", expand=0, fill="y")

    sf = ScrolledFrame(data_frame, width=1150, height=250, bg='#ffffff')
    sf.pack(side="left", expand=1, fill="y")

    # Bind the arrow keys and scroll wheel
    sf.bind_arrow_keys(data_frame)
    sf.bind_scroll_wheel(data_frame)

    frame = sf.display_widget(tk.Frame)
    frame['bg'] = '#d7d5f7'
    frame['bd'] = 15
    frame['relief'] = 'sunken'

    for news_list in news_data:
        for news in news_list['articles']:
            print(news['description'])
            l = tk.Label(text=news['title'].title(),
                         fg='#3f0052',
                         bg='#d7d5f7',
                         wraplength=1120,
                         master=frame,
                         font="-size 18 -weight bold",
                         justify='left',
                         pady='10')

            l.pack()

            l = tk.Label(text=news['description'],
                         bg='#d7d5f7',
                         fg='#3f0052',
                         wraplength=1120,
                         master=frame,
                         font="-size 14",
                         justify='left',
                         padx='15')

            l.pack()

            l = tk.Label(
                text=
                '--------------------------------------------------------------------------------------------------',
                bg='#d7d5f7',
                fg='#3f0052',
                wraplength=1120,
                master=frame,
                font="-size 14",
                justify='left',
                pady='25')

            l.pack()

    window.mainloop()
Example #14
0
    bg='#0052cc',
    fg='#ffffff',
    activebackground='#0052cc',
    activeforeground='#aaffaa',
    command=doAnomalyDetection)
showAnomalyDetectionButton['font'] = myFont
showAnomalyDetectionButton.place(x=990, y=0)

downloadButton = Tkinter.Button(app,
                                text='Download CSV',
                                width=20,
                                height=3,
                                bg='#0052cc',
                                fg='#ffffff',
                                activebackground='#0052cc',
                                activeforeground='#aaffaa',
                                command=downloadCSV)
downloadButton['font'] = myFont
downloadButton.place(x=1480, y=0)

sf = ScrolledFrame(app, width=1780, height=660)
sf.place(x=5, y=120)

# Bind the arrow keys and scroll wheel
sf.bind_arrow_keys(app)
sf.bind_scroll_wheel(app)

inner_frame_csv = sf.display_widget(Tkinter.Frame)

app.mainloop()
Example #15
0
class CoronaDB:

    def __init__(self, master):
        self.master = master
        self.createWidgets()

    def createWidgets(self):

        style = ttk.Style()
        style.theme_use("clam")
        style.configure(
            "LightText.TFrame",
            background=COLOUR_SECONDARY,
            foreground=COLOUR_LIGHT_TEXT,
        )

        style.configure(
            "LightText.TLabel",
            background=COLOUR_PRIMARY,
            foreground=COLOUR_LIGHT_TEXT,
        )

        style.configure(
            "Button.TButton",
            background=COLOUR_SECONDARY,
            foreground=COLOUR_PRIMARY,
        )


        self.corona_label = ttk.Label(self.master, text='Corona Virus Data Calculator', style="LightText.TLabel", font=('helvetica', 20))
        self.corona_label.grid(row=0, sticky='N', padx=50, pady=25)

        self.button = ttk.Button(text='Show(Country)', command=self.getcorona, style="Button.TButton")
        self.button.grid(row=2, sticky='W', padx=50, pady=5)

        self.button1 = ttk.Button(text='Show(All)', command=self.allcompare, style="Button.TButton")
        self.button1.grid(row=2, sticky='E', padx=50, pady=5)

        # self.corona_frame = ttk.Frame(self.master, borderwidth = 5, width=500, height=250, relief='groove', style="LightText.TFrame")
        # self.corona_frame.grid_propagate(False)
        # self.corona_frame.grid(row=3, sticky='w', padx=50, pady=5)

        self.corona_frame = ScrolledFrame(self.master, borderwidth = 5, width=400, height=220, bg='black')
        self.corona_frame.grid(row=4, sticky='w', padx=50, pady=5)

        # Bind the arrow keys and scroll wheel
        self.corona_frame.bind_arrow_keys(self.master)
        self.corona_frame.bind_scroll_wheel(self.master)

        self.inner_frame = self.corona_frame.display_widget(Frame)

        options = [
            "World",
            "Czech Republic",
            "India",
            "United States of America",
            "Spain",
            "Italy",
            "France",
            "Germany",
            "China",
            "United Kingdom",
            "Turkey",
            "Belgium",
            "Switzerland",
            "Netherlands",
            "Canada",
            "Brazil",
            "Portugal",
            "Austria",
            "Pakistan",
        ]

        self.clicked = StringVar()
        self.clicked.set(options[0])
        self.drop = OptionMenu(self.master, self.clicked, *options)
        self.drop.config(bg = "#808080")
        self.drop["menu"].config(bg="white")
        self.drop.grid(row=1, sticky='W', padx=50, pady=5)

    def allcompare(self):
        if self.inner_frame.grid_slaves():
            self.clearContents()

        endpoint = "https://api.covid19api.com/summary"
        response = requests.get(endpoint)
        corona = response.json()
        dict = {}
        for data in corona['Countries']:
            new_dict = {**dict, **{data['Country']: data['TotalConfirmed']}}
            dict = new_dict

        sorted_data = sorted(dict.items(), key=operator.itemgetter(1),reverse=True)

        i = 1
        for item in sorted_data:
            text_val1 = item[0]
            text_val2 = item[1]
            ttk.Label(self.inner_frame,
                      borderwidth = 3,
                      width = 20,
                      text=text_val1,
                      font=('helvetica', 16),
                      style="Button.TButton",
                      wraplength=500).grid(row=i, column=2)

            ttk.Label(self.inner_frame,
                      borderwidth = 3,
                      width = 20,
                      text=text_val2,
                      font=('helvetica', 16),
                      style="Button.TButton",
                      wraplength=500).grid(row=i, column=4)
            i = i + 1


    def getcorona(self):
        if self.inner_frame.grid_slaves():
            self.clearContents()


        endpoint = "https://api.covid19api.com/summary"
        response = requests.get(endpoint)
        corona = response.json()  # corona data in json format
        dd_clicked = self.clicked.get()

        keys = {'NewConfirmed': 'New Confirmed', 'TotalConfirmed': 'Total Cases', 'NewDeaths': 'New Deaths', 'TotalDeaths': 'Total Deaths', 'NewRecovered': 'New Recovered', 'TotalRecovered': 'Total Recovered'}

        if dd_clicked != "World":
            for country_data in corona['Countries']:
                if country_data['Country'] == dd_clicked:
                    i = 1
                    for item in keys:
                        text_val1 = keys[item]
                        text_val2 = str(country_data[item])
                        ttk.Label(self.inner_frame,
                                  borderwidth = 3,
                                  width = 20,
                                  text=text_val1,
                                  font=('helvetica', 16),
                                  style="Button.TButton",
                                  wraplength=500).grid(row=i, column=2)

                        ttk.Label(self.inner_frame,
                                  borderwidth = 3,
                                  width = 20,
                                  text=text_val2,
                                  font=('helvetica', 16),
                                  style="Button.TButton",
                                  wraplength=500).grid(row=i, column=4)
                        i = i + 1
        else:
            i = 1
            for item in keys:
                text_val1 = keys[item]
                text_val2 = str(corona['Global'][item])
                ttk.Label(self.inner_frame,
                          borderwidth = 3,
                          width = 20,
                          text=text_val1,
                          font=('helvetica', 16),
                          style="Button.TButton",
                          wraplength=500).grid(row=i, column=2)

                ttk.Label(self.inner_frame,
                          borderwidth = 3,
                          width = 20,
                          text=text_val2,
                          font=('helvetica', 16),
                          style="Button.TButton",
                          wraplength=500).grid(row=i, column=4)
                i = i + 1

    def clearContents(self):
        for widget in self.inner_frame.grid_slaves():
            widget.destroy()
Example #16
0
#!/usr/bin/env python3

from tkinter import *
from tkscrolledframe import ScrolledFrame

# Create a root window
root = Tk()

# Create a ScrolledFrame widget
sf = ScrolledFrame(root, width=640, height=480)
sf.pack(side="top", expand=1, fill="both")

# Bind the arrow keys and scroll wheel
sf.bind_arrow_keys(root)
sf.bind_scroll_wheel(root)

# Create a frame within the ScrolledFrame
inner_frame = sf.display_widget(Frame)

# Add a bunch of widgets to fill some space
num_rows = 16
num_cols = 16
for row in range(num_rows):
    for column in range(num_cols):
        w = Label(inner_frame,
                  width=15,
                  height=5,
                  borderwidth=2,
                  relief="groove",
                  anchor="center",
                  justify="center",
class ImageViewer():

    def __init__(self, root_window, insta_id = None, insta_password = None):
        self.insta_bot_logged_in = False
        if insta_id is not None:
            self.insta_bot = Bot()

        self.camera_info = ''
        self.camera_hashtags = ''

        self.current_image_pil = None
        self.current_image_proxy_pil = None
        self.proxy_file_exists = None

        # Calling the Tk (The intial constructor of tkinter)
        self.root = root_window


        # The geometry of the box which will be displayed
        # on the screen
        self.root.geometry("1400x1000")

        #self.fr_buttons_scr = tk.Frame(self.root, relief=tk.RAISED, bd=2)
        #self.fr_buttons_scr.pack(side=tk.LEFT, fill=tk.Y)
        #self.fr_buttons = Scrollable(self.fr_buttons_scr)
        #self.fr_buttons_scr = ScrollableFrame(self.root, relief=tk.RAISED, bd=2)
        #self.fr_buttons_scr = ScrollableFrame(self.root, relief=tk.RAISED, bd=2)
        #self.fr_buttons_scr.pack(side=tk.LEFT, fill=tk.Y)
        #self.fr_buttons = self.fr_buttons_scr.scrollable_frame

        self.fr_buttons_scr = ScrolledFrame(self.root, width=600, relief=tk.RAISED, bd=2, scrollbars='vertical')
        self.fr_buttons_scr.pack(side=tk.LEFT, fill=tk.BOTH)
        self.fr_buttons_scr.bind_arrow_keys(root)
        self.fr_buttons_scr.bind_scroll_wheel(root)
        self.fr_buttons = self.fr_buttons_scr.display_widget(tk.Frame)

        #self.fr_buttons.grid(row=0, column=0, columnspan=1, sticky="ew", pady=5)

        self.sld_scale_val = tk.DoubleVar(value=1.0)
        self.sld_scale = tk.Scale(self.fr_buttons, from_ = 0.0, to = 4.0, resolution=0.1, orient=tk.HORIZONTAL, variable=self.sld_scale_val, command=self._scale_update)

        # range will be set at the end of the initialisation
        self.sld_imgidx_val = tk.IntVar(value=1)
        self.sld_imgidx = tk.Scale(self.fr_buttons, from_ = 1, to = 1, resolution=1, orient=tk.HORIZONTAL, variable=self.sld_imgidx_val, command=self._imgidx_update)

        self.chk_show_uploaded_val = tk.IntVar(value=1)
        self.chk_show_uploaded = tk.Checkbutton(self.fr_buttons, text='show uploaded', variable=self.chk_show_uploaded_val, command=self._on_show_tagged_untagged)
        self.chk_show_not_uploaded_val = tk.IntVar(value=1)
        self.chk_show_not_uploaded = tk.Checkbutton(self.fr_buttons, text='show not uploaded', variable=self.chk_show_not_uploaded_val, command=self._on_show_tagged_untagged)
        self.chk_show_untagged_val = tk.IntVar(value=1)
        self.chk_show_untagged = tk.Checkbutton(self.fr_buttons, text='show untagged', variable=self.chk_show_untagged_val, command=self._on_show_tagged_untagged)
        self.chk_use_proxy_val = tk.IntVar(value=1)
        self.chk_use_proxy = tk.Checkbutton(self.fr_buttons, text='Use proxy if available', variable=self.chk_use_proxy_val, command=self._on_use_proxy)
        self.chk_use_exif_val = tk.IntVar(value=0)
        self.chk_use_exif = tk.Checkbutton(self.fr_buttons, text='Use EXIF metadata if available (slow)', variable=self.chk_use_exif_val, command=self._on_use_exif)
        self.btn_last_edited = tk.Button(self.fr_buttons, text="Move to last edited", command=self._on_click_last_edited)

        self.btn_upload_insta = tk.Button(self.fr_buttons, text="Upload to Instagram", command=self._on_click_upload_insta)

        # root.quit for closing the app
        self.btn_exit = tk.Button(self.fr_buttons, text="Exit",
                             command=self.root.quit)
        # We will have three button back ,forward and exit
        self.btn_fast_back = tk.Button(self.fr_buttons, text="<< Fast Backward", command=self.fast_back, state=tk.DISABLED)
        self.btn_back = tk.Button(self.fr_buttons, text="< Back", command=self.back,
                             state=tk.DISABLED)
        self.txt_description = ScrolledText(self.fr_buttons, width=50, height=5, )


        self.config = json.load(open(os.path.join(SCRIPT_DIRPATH, 'config.json'), 'r', encoding='utf8'), object_pairs_hook=OrderedDict)
        self.hashtag_groups = self.config['hashtag_groups']
        self.hashtag_groups_indices = {k:i for i,k in enumerate(self.hashtag_groups.keys())}
        self.images_basedir = self.config['images_basedir']
        self.images_proxydir = self.config['images_proxydir']
        self.images_outputdir = self.config['images_outputdir']
        self.hashtag_group_chkbtns = []
        self.hashtag_group_chkbtn_vals = []

        for idx, (key, val) in enumerate(self.hashtag_groups.items()):
            self.hashtag_group_chkbtn_vals.append(tk.IntVar())
            # when using lambda, use default parameter idx=idx to avoid late-binding issue (otherwise `idx` is bound when the function is called)
            self.hashtag_group_chkbtns.append(tk.Checkbutton(self.fr_buttons, text=key, variable=self.hashtag_group_chkbtn_vals[idx], command=lambda idx=idx: self._hashtag_group_chkbtn_press(idx)))
            self.hashtag_group_chkbtns[idx].bind('<ButtonPress>', self._on_button_press)

        self.label_ratio = tk.Label(self.fr_buttons,text='crop ratio')
        self.radio_ratio_val = tk.IntVar()
        self.radio_ratio_none = tk.Radiobutton(self.fr_buttons, text="None", value=RATIO_NONE, variable=self.radio_ratio_val, command=self._on_ratio)
        self.radio_ratio_45 = tk.Radiobutton(self.fr_buttons, text="4:5", value=RATIO_45, variable=self.radio_ratio_val, command=self._on_ratio)
        self.radio_ratio_11 = tk.Radiobutton(self.fr_buttons, text="1:1", value=RATIO_11, variable=self.radio_ratio_val, command=self._on_ratio)
        self.radio_ratio_custom = tk.Radiobutton(self.fr_buttons, text="Custom", value=RATIO_CUSTOM, variable=self.radio_ratio_val, command=self._on_ratio)
        self.spin_ratio_x_val = tk.StringVar(value="3")
        self.spin_ratio_x = tk.Spinbox(self.fr_buttons,from_=1, to=30, textvariable=self.spin_ratio_x_val, justify=tk.CENTER)
        self.spin_ratio_y_val = tk.StringVar(value="2")
        self.spin_ratio_y = tk.Spinbox(self.fr_buttons,from_=1, to=30, textvariable=self.spin_ratio_y_val, justify=tk.CENTER)
        self.label_ratio_custom = tk.Label(self.fr_buttons,text=':')

        self.label_crop_x = tk.Label(self.fr_buttons,text='x')
        self.label_crop_y = tk.Label(self.fr_buttons,text='y')
        self.label_crop_size = tk.Label(self.fr_buttons,text='size')
        self.spin_crop_x_val = tk.StringVar(value='0.0')
        self.spin_crop_x = tk.Spinbox(self.fr_buttons,from_=-1.0, to=1.0, format='%.2f', increment=0.02, textvariable=self.spin_crop_x_val, justify=tk.CENTER)
        self.spin_crop_y_val = tk.StringVar(value='0.0')
        self.spin_crop_y = tk.Spinbox(self.fr_buttons,from_=-1.0, to=1.0, format='%.2f', increment=0.02, textvariable=self.spin_crop_y_val, justify=tk.CENTER)
        self.spin_crop_size_val = tk.StringVar(value='1.0')
        self.spin_crop_size = tk.Spinbox(self.fr_buttons,from_=0.0, to=2.0, format='%.2f', increment=0.02, textvariable=self.spin_crop_size_val, justify=tk.CENTER)

        # trace value changes
        self.spin_crop_x_val.trace_add('write', self._on_crop_xysize)
        self.spin_crop_y_val.trace_add('write', self._on_crop_xysize)
        self.spin_crop_size_val.trace_add('write', self._on_crop_xysize)

        self.chk_crop_preview_val = tk.IntVar()
        self.chk_crop_preview= tk.Checkbutton(self.fr_buttons, text='crop preview', variable=self.chk_crop_preview_val, command=self._on_click_crop_preview)

        self.btn_forward = tk.Button(self.fr_buttons, text="Forward >",
                                command=self.forward)
        self.btn_fast_forward = tk.Button(self.fr_buttons, text="Fast Forward >>",
                                command=self.fast_forward)
        self.txt_description_preview = ScrolledText(self.fr_buttons, width=50, height=20, state=tk.DISABLED)

        self.chk_is_proxy_val = tk.IntVar()
        self.chk_is_proxy = tk.Checkbutton(self.fr_buttons, text='proxy', variable=self.chk_is_proxy_val, state=tk.DISABLED, anchor=tk.W)
        self.chk_is_uploaded_val = tk.IntVar()
        self.chk_is_uploaded = tk.Checkbutton(self.fr_buttons, text='instagram uploaded', variable=self.chk_is_uploaded_val, state=tk.DISABLED, anchor=tk.W)

        self.fr_btn_widgets = []    # list of all the widgets in the left frame (in order), for grid (partially) and for binding click focus
        self.fr_btn_widgets.append(self.sld_scale)
        self.fr_btn_widgets.append(self.sld_imgidx)
        self.fr_btn_widgets.append(self.chk_show_uploaded)
        self.fr_btn_widgets.append(self.chk_show_not_uploaded)
        self.fr_btn_widgets.append(self.chk_show_untagged)
        self.fr_btn_widgets.append(self.chk_use_proxy)
        self.fr_btn_widgets.append(self.chk_use_exif)
        self.fr_btn_widgets.append(self.btn_last_edited)
        self.fr_btn_widgets.append(self.btn_upload_insta)
        self.fr_btn_widgets.append(self.btn_exit)
        self.fr_btn_widgets.append(self.btn_fast_back)
        self.fr_btn_widgets.append(self.btn_back)
        self.fr_btn_widgets.append(self.txt_description)
        self.fr_btn_widgets.extend(self.hashtag_group_chkbtns)
        #self.fr_btn_widgets.append(self.label_ratio)
        self.fr_btn_widgets.append(self.radio_ratio_none)
        self.fr_btn_widgets.append(self.radio_ratio_45)
        self.fr_btn_widgets.append(self.radio_ratio_11)
        self.fr_btn_widgets.append(self.radio_ratio_custom)
        self.fr_btn_widgets.append(self.spin_ratio_x)
        self.fr_btn_widgets.append(self.spin_ratio_y)
        self.fr_btn_widgets.append(self.spin_crop_size)
        self.fr_btn_widgets.append(self.spin_crop_x)
        self.fr_btn_widgets.append(self.spin_crop_y)
        self.fr_btn_widgets.append(self.chk_crop_preview)
        self.fr_btn_widgets.append(self.btn_forward)
        self.fr_btn_widgets.append(self.btn_fast_forward)
        self.fr_btn_widgets.append(self.txt_description_preview)


        # row_widget
        row_widget = 0

        for widget in self.fr_btn_widgets[:13]:
            # until txt_description
            widget.grid(row=row_widget, column=0, columnspan=3, sticky="ew")
            row_widget += 1
        for widget in self.hashtag_group_chkbtns:
            widget.grid(row=row_widget, column=0, columnspan=3, sticky="ew")
            row_widget += 1

        self.label_ratio.grid(row=row_widget, column=0, columnspan=3, sticky="ew", pady=5)
        row_widget += 1
        self.radio_ratio_none.grid(row=row_widget, column=0, sticky="ew")
        self.radio_ratio_45.grid(row=row_widget, column=1, sticky="ew")
        self.radio_ratio_11.grid(row=row_widget, column=2, sticky="ew")
        row_widget += 1
        self.radio_ratio_custom.grid(row=row_widget, column=0, sticky="ew")
        self.spin_ratio_x.grid(row=row_widget, column=1, sticky="ew", padx=40)
        self.label_ratio_custom.grid(row=row_widget, column=1, sticky="ee")
        self.spin_ratio_y.grid(row=row_widget, column=2, sticky="ew",padx=40)
        row_widget += 1
        self.label_crop_x.grid(row=row_widget, column=0, sticky="ew")
        self.label_crop_y.grid(row=row_widget, column=1, sticky="ew")
        self.label_crop_size.grid(row=row_widget, column=2, sticky="ew")
        row_widget += 1
        self.spin_crop_x.grid(row=row_widget, column=0, sticky="ew", padx=15)
        self.spin_crop_y.grid(row=row_widget, column=1, sticky="ew", padx=15)
        self.spin_crop_size.grid(row=row_widget, column=2, sticky="ew", padx=15)
        row_widget += 1
        self.chk_crop_preview.grid(row=row_widget, column=0, columnspan=3, sticky="ew")
        row_widget += 1
        self.btn_forward.grid(row=row_widget, column=0, columnspan=3, sticky="ew")
        row_widget += 1
        self.btn_fast_forward.grid(row=row_widget, column=0, columnspan=3, sticky="ew")
        row_widget += 1
        self.txt_description_preview.grid(row=row_widget, column=0, columnspan=3, sticky="ew")
        row_widget += 1
        self.chk_is_proxy.grid(row=row_widget, column=0, columnspan=3, sticky="ew")
        row_widget += 1
        self.chk_is_uploaded.grid(row=row_widget, column=0, columnspan=3, sticky="ew")

        self._sqlite_connect()
        self._sqlite_create_table()


        self._read_image_list(self.images_basedir)
        self.canvas = tk.Canvas(self.root, width=300, height=200)#, bg="white")
        self.canvas.pack(expand=tk.YES, fill=tk.BOTH)
        self.img_idx = 0
        self._change_image()


        # set self.sld_imgidx range
        self.sld_imgidx.configure(to=self.image_count())

        self._key_bind()



    def __del__(self):
        self._sqlite_close()
        self.insta_bot.logout()

    def _read_image_list(self, basedir: str):
        self.image_relpath_list = []
        for root, dirs, files in os.walk(basedir):
            reldir = root.replace(basedir, '')
            if reldir.startswith(os.sep):
                reldir = reldir[1:]
            self.image_relpath_list.extend(sorted([os.path.join(reldir,f).replace(os.sep, '/') for f in files if f.lower().endswith('jpg')]))

    def get_insta_description(self):
        text = self.txt_description.get('1.0', tk.END).strip()
        num_hashtags_desc = text.count('#')

        text += '\n\n' + self.camera_info + '\n\n'

        hashtags = ''
        for idx, (key, val) in enumerate(self.hashtag_groups.items()):
            if self.hashtag_group_chkbtn_vals[idx].get() == 1:
                hashtags += val
                hashtags += ' '

        hashtags += self.camera_hashtags
        num_hashtags = hashtags.count('#')

        if num_hashtags_desc + num_hashtags > 30:
            hashtags_list = hashtags.split(' ')
            random.shuffle(hashtags_list)
            hashtags_list = hashtags_list[:30-num_hashtags_desc]
            hashtags = ' '.join(hashtags_list)

        return text + hashtags

    def _update_description_preview(self):
        text = self.get_insta_description()
                
        self.txt_description_preview['state'] = tk.NORMAL
        self.txt_description_preview.delete(1.0,tk.END)
        self.txt_description_preview.insert(tk.END,text)
        self.txt_description_preview['state'] = tk.DISABLED


    def _save_txt_description(self):
        '''Save when modification is detected only
        '''
        #self._update_description_preview()
        text = self.txt_description.get('1.0', tk.END).strip()
        is_modified = self.txt_description.edit_modified()

        if is_modified:
            #self._sqlite_upsert_description(text)
            self._sqlite_upsert_one_field('description', text)

        # reset the flag
        self.txt_description.edit_modified(False)

    def _save_hashtag_groups(self):
        group_keys = []
        for idx, (key, val) in enumerate(self.hashtag_groups.items()):
            if self.hashtag_group_chkbtn_vals[idx].get() == 1:
                group_keys.append(key)
        
        self._sqlite_upsert_one_field('hashtag_groups', SQL_SEPARATOR.join(group_keys))
        
    def _save_crop_ratio(self):
        ratio_mode = self.radio_ratio_val.get()
        if ratio_mode == RATIO_NONE:
            text = 'none'
        elif ratio_mode == RATIO_45:
            text = '4:5'
        elif ratio_mode == RATIO_11:
            text = '1:1'
        else:
            text = self.spin_ratio_x_val.get() + ":" + self.spin_ratio_y_val.get()
        self._sqlite_upsert_one_field('crop_ratio', text)

    def _save_crop_x(self):
        x_offset = float(self.spin_crop_x_val.get())
        self._sqlite_upsert_one_field('crop_x_offset', x_offset)

    def _save_crop_y(self):
        y_offset = float(self.spin_crop_y_val.get())
        self._sqlite_upsert_one_field('crop_y_offset', y_offset)

    def _save_crop_size(self):
        crop_size = float(self.spin_crop_size_val.get())
        self._sqlite_upsert_one_field('crop_size', crop_size)

    def _sqlite_upsert_one_field(self, column, value):
        '''Updates the field with the current file path.
        Updates the last updated timestamp automatically.
        '''
        last_updated_ts = datetime.utcnow().timestamp()
        
        self.sqlite_cursor.execute(f'''INSERT INTO insta_tags(file_relpath, {column}, last_updated_utc)
        VALUES(?,?,?)
        ON CONFLICT(file_relpath) DO UPDATE SET
        {column}=excluded.{column},
        last_updated_utc=excluded.last_updated_utc;''', (self.image_relpath_list[self.img_idx], value, last_updated_ts))
        self.sqlite_conn.commit()

    def _sqlite_connect(self):
        self.sqlite_conn = sqlite3.connect(self.config['database_path'])
        self.sqlite_cursor = self.sqlite_conn.cursor()

    def _sqlite_create_table(self):
        self.sqlite_cursor.execute('''CREATE TABLE IF NOT EXISTS insta_tags (
        file_relpath TEXT PRIMARY KEY,
        description TEXT,
        hashtag_groups TEXT,
        crop_ratio TEXT DEFAULT none,
        crop_size REAL DEFAULT 1.0,
        crop_x_offset REAL DEFAULT 0.0,
        crop_y_offset REAL DEFAULT 0.0,
        is_insta_uploaded INTEGER DEFAULT 0,
        last_updated_utc REAL )''')

        self.sqlite_conn.commit()

    def _sqlite_close(self):
        self.sqlite_conn.close()

    def _key_bind(self):
        self.root.bind('<Left>', self._back_event)
        self.root.bind('<Right>', self._forward_event)
        self.root.protocol("WM_DELETE_WINDOW", self._on_close)
        self.root.bind('<Configure>', self._on_change_window_size)

        # unbind tab function for the text widget
        self.txt_description.bind('<Tab>', self._focus_next_widget)
        self.txt_description.bind('<FocusOut>', self._on_focus_out)
        self.txt_description.bind('<<TextModified>>', self._on_txt_modified)

        self.spin_crop_size.bind('<FocusOut>', self._on_focus_out)
        self.spin_crop_x.bind('<FocusOut>', self._on_focus_out)
        self.spin_crop_y.bind('<FocusOut>', self._on_focus_out)

        # move focus when pressing widgets
        self.root.bind('<ButtonPress>', self._on_button_press)

        for widget in self.fr_btn_widgets:
            widget.bind('<ButtonPress>', self._on_button_press)
#        self.chk_show_tagged.
#        self.chk_show_untagged.bind('<ButtonPress>', self._on_button_press)
#        self.btn_last_edited.bind('<ButtonPress>', self._on_button_press)
#        self.btn_upload_insta.bind('<ButtonPress>', self._on_button_press)
#        self.btn_exit.bind('<ButtonPress>', self._on_button_press)
#        self.btn_back.bind('<ButtonPress>', self._on_button_press)
#        self.btn_forward.bind('<ButtonPress>', self._on_button_press)

    def _forward_event(self, event):
        self.forward()
    def _back_event(self, event):
        self.back()

    def _hashtag_group_chkbtn_press(self, idx):
        self._update_description_preview()
        self._save_hashtag_groups()

    def _focus_next_widget(self, event):
        '''To unbind tab key on the text widget
        '''
        event.widget.tk_focusNext().focus()
        return("break")

    def _on_show_tagged_untagged(self):
        if self.chk_show_uploaded_val.get() == 0 and self.chk_show_not_uploaded_val.get() == 0:
            self.btn_last_edited['state'] = tk.DISABLED
        else:
            self.btn_last_edited['state'] = tk.NORMAL

    def _on_use_proxy(self):
        if self.chk_use_proxy_val.get() == 0:
            self.chk_is_proxy_val.set(0)
        else:
            _, is_proxy = self.get_image()
            self.chk_is_proxy_val.set(is_proxy)
        self._scale_update()

    def _on_use_exif(self):
        if self.chk_use_exif_val.get() == 0:
            self.camera_info = ''
            self.camera_hashtags = ''
        else:
            self._read_camera_exif()

        self._update_description_preview()


    def _on_click_last_edited(self):
        pass

    def _on_click_upload_insta(self):
        # process image
        # 
        image = self.get_original_image()
        crop_xywh = self.get_crop_xywh(image)
        img = self.get_scaled_cropped_image(image, 1.0, crop_xywh, resample=Image.LANCZOS)
        img = watermark_signature(img).convert('RGB')

        output_filepath = os.path.join(self.images_outputdir, self.image_relpath_list[self.img_idx])
        output_dirpath = os.path.dirname(output_filepath)
        os.makedirs(output_dirpath, exist_ok=True)

        img.save(output_filepath, quality=95)
        logger.info('Image saved to %s', output_filepath)

        #caption = self.get_insta_description()
        caption = self.txt_description_preview.get('1.0', tk.END).strip()
        logger.info('Instagram caption: %s', caption)

        
        if not self.insta_bot_logged_in:
            # True / False
            self.insta_bot_logged_in = self.insta_bot.login(username=insta_id, password=insta_password)
        if not self.insta_bot_logged_in:
            logger.error('Failed to log in to Instagram')
            return

        #self.insta_bot.upload_photo(output_filepath, caption)
        self.insta_bot.upload_photo(output_filepath, caption)
        os.rename(output_filepath + '.REMOVE_ME', output_filepath)

        self._sqlite_upsert_one_field('is_insta_uploaded', 1)
        self.chk_is_uploaded_val.set(1)

    def _on_close(self):
        self._save_txt_description()
        self._save_crop_size()
        self._save_crop_x()
        self._save_crop_y()
        self.root.destroy()

    def _on_focus_out(self, event):
        '''Save the description when the text box is out of focus
        '''
        if event.widget == self.txt_description:
            logger.info('Description text focus out: Saving..')
            self._save_txt_description()

        elif event.widget == self.spin_crop_size:
            logger.info('Crop size focus out: Saving..')
            self._save_crop_size()

        elif event.widget == self.spin_crop_x:
            logger.info('Crop x focus out: Saving..')
            self._save_crop_x()

        elif event.widget == self.spin_crop_y:
            logger.info('Crop y focus out: Saving..')
            self._save_crop_y()

    def _on_txt_modified(self, event):
        '''Update preview as soon as description is modified
        '''
        if event.widget == self.txt_description:
            self._update_description_preview()

    def _on_button_press(self, event):
        '''Move focus
        '''
        event.widget.focus()

    def _on_crop_xysize(self, var, indx, mode):
        if self.chk_crop_preview_val.get() == 1:
            self._scale_update()
        else:
            self._refresh_canvas()

    def _ratio_disability_update(self):
        ratio_mode = self.radio_ratio_val.get()
        if ratio_mode == RATIO_NONE:
            self.spin_crop_x['state'] = tk.DISABLED
            self.spin_crop_y['state'] = tk.DISABLED
            self.spin_crop_size['state'] = tk.DISABLED
            self.chk_crop_preview['state'] = tk.DISABLED
        else:
            self.spin_crop_x['state'] = tk.NORMAL
            self.spin_crop_y['state'] = tk.NORMAL
            self.spin_crop_size['state'] = tk.NORMAL
            self.chk_crop_preview['state'] = tk.NORMAL


        if ratio_mode == RATIO_CUSTOM:
            self.spin_ratio_x['state'] = tk.NORMAL
            self.spin_ratio_y['state'] = tk.NORMAL
        else:
            self.spin_ratio_x['state'] = tk.DISABLED
            self.spin_ratio_y['state'] = tk.DISABLED


    def _on_ratio(self):
        self._ratio_disability_update()

        if self.chk_crop_preview_val.get() == 1:
            self._scale_update()
        else:
            self._refresh_canvas()

        logger.info('Ratio changed: Saving..')
        self._save_crop_ratio()

    def point_to_canvas(self, image: Image.Image, x, y):
        '''Convert image point coordinate to canvas coordinate
        Considers scaling and canvas offset (image is centre aligned)
        '''
        canvas_width = self.canvas.winfo_width()
        canvas_height = self.canvas.winfo_height()
        image_width, image_height = image.size
        scale = self.sld_scale_val.get()
        # adding canvas offset
        canvas_x = x * scale + (canvas_width - image_width * scale)/2
        canvas_y = y * scale + (canvas_height - image_height * scale)/2

        if self.chk_crop_preview_val.get() == 1:
            # image centre - crop centre is the another offset
            crop_xywh = self.get_crop_xywh(image)
            crop_centre_x = crop_xywh[0] + crop_xywh[2]/2
            crop_centre_y = crop_xywh[1] + crop_xywh[3]/2
            canvas_x += (image_width/2 - crop_centre_x)*scale
            canvas_y += (image_height/2 - crop_centre_y)*scale

        return round(canvas_x), round(canvas_y)

    def rectangle_to_canvas(self, image: Image.Image, x, y, w, h):
        x1, y1, x2, y2 = self.xywh_to_xyxy(x, y, w, h)
        canvas_x1, canvas_y1 = self.point_to_canvas(image, x1,y1)
        canvas_x2, canvas_y2 = self.point_to_canvas(image, x2,y2)
        return canvas_x1, canvas_y1, canvas_x2, canvas_y2

    def get_crop_xywh(self, image: Image.Image):
        ratio_mode = self.radio_ratio_val.get()

        if ratio_mode == RATIO_NONE:
            return None
        else:
            if ratio_mode == RATIO_45:
                ratio_x = 4
                ratio_y = 5
            elif ratio_mode == RATIO_11:
                ratio_x = 1
                ratio_y = 1
            else:
                # RATIO_CUSTOM
                ratio_x = int(self.spin_ratio_x_val.get())
                ratio_y = int(self.spin_ratio_y_val.get())

            crop_x_offset = float(self.spin_crop_x_val.get())
            crop_y_offset = float(self.spin_crop_y_val.get())
            crop_size = float(self.spin_crop_size_val.get())

            crop_ratio = ratio_x / ratio_y
            image_width, image_height = image.size
            image_ratio = image_width / image_height

            if image_ratio > crop_ratio:
                # image is wider. crop_size==1 should be matching image's height.
                # base width and height when crop_size==1
                crop_base_height = image_height
                crop_base_width = crop_base_height / ratio_y * ratio_x
            else:
                # image is narrower. crop_size==1 should be matching image's width.
                # base width and height when crop_size==1
                crop_base_width = image_width
                crop_base_height = crop_base_width / ratio_x * ratio_y

            crop_centre_x = image_width / 2 + (crop_x_offset * image_width / 2)
            crop_centre_y = image_height / 2 + (crop_y_offset * image_height / 2)
            crop_width = crop_base_width * crop_size
            crop_height = crop_base_height * crop_size
            crop_x1 = crop_centre_x - (crop_width / 2)
            crop_y1 = crop_centre_y - (crop_height / 2)
            return crop_x1, crop_y1, crop_width, crop_height

    def xywh_to_xyxy(self, x, y, w, h):
        return x, y, x+w, y+h

    def get_scaled_cropped_image(self, image: Image.Image, scale, crop_xywh, resample=Image.BICUBIC):
        if crop_xywh is not None:
            new_image_size = tuple(map(lambda x: round(x*scale), crop_xywh[2:]))
            crop_xyxy = tuple(map(round, self.xywh_to_xyxy(*crop_xywh)))

            # perform padding when crop is out of border
            image_width, image_height = image.size
            padding = None
            if crop_xyxy[0] < 0:
                if padding is None:
                    padding = [0,0,0,0]
                padding[0] = -crop_xyxy[0]
            if crop_xyxy[1] < 0:
                if padding is None:
                    padding = [0,0,0,0]
                padding[1] = -crop_xyxy[1]
            if crop_xyxy[2] > image_width:
                if padding is None:
                    padding = [0,0,0,0]
                padding[2] = crop_xyxy[2] - image_width
            if crop_xyxy[3] > image_height:
                if padding is None:
                    padding = [0,0,0,0]
                padding[3] = crop_xyxy[3] - image_height

            if padding is None:
                current_image_pil_scaled = image.resize(new_image_size, box=crop_xyxy, resample=resample)
            else:
                logger.warning('white padding applied to the image borders')
                padding = tuple(padding)
                crop_xyxy_padded = (crop_xyxy[0] + padding[0], crop_xyxy[1] + padding[1],
                        crop_xyxy[2] + padding[0], crop_xyxy[3] + padding[1])   # padding on the left and top sides makes the box shift, but not the right and bottom sides.
                current_image_pil_scaled = ImageOps.expand(image, border=padding, fill=(255,255,255)).resize(new_image_size, box=crop_xyxy_padded, resample=resample)
        else:
            if scale == 1.0:
                # use the original and do not make a copy
                current_image_pil_scaled = image
            else:
                new_image_size = tuple(map(lambda x: round(x*scale), image.size))
                current_image_pil_scaled = image.resize(new_image_size, resample=resample)

        return current_image_pil_scaled


    def _imgidx_update(self, event=None):
        index = self.sld_imgidx_val.get() - 1
        self.jump(index)

    def _scale_update(self, event=None):
        '''Manipulate original image
        1. Apply scaling
        2. Apply crop preview
        3. Apply proxy
        '''
        scale = self.sld_scale_val.get()

        image, use_proxy = self.get_image()
        crop_xywh = self.get_crop_xywh(image)
        
        if self.chk_crop_preview_val.get() == 1 and crop_xywh is not None:
            self.current_image_pil_scaled = self.get_scaled_cropped_image(image, scale, crop_xywh, resample=Image.BILINEAR)
        else:
            if scale == 1.0:
                # use the original and do not make a copy
                self.current_image_pil_scaled = image
            else:
                new_image_size = tuple(map(lambda x: round(x*scale), image.size))
                self.current_image_pil_scaled = image.resize(new_image_size, resample=Image.BILINEAR)

        self.current_image = ImageTk.PhotoImage(self.current_image_pil_scaled)
        self._refresh_canvas()

    def _refresh_canvas(self):
        '''DO NOT change the image itself but change the positioning
        '''
        #self.canvas.create_image(0,0,image=self.current_image, anchor=tk.NW)
        
        self.canvas.delete(tk.ALL)
        #self.canvas.create_image(0,0,image=self.current_image, anchor=tk.CENTER)
        canvas_width = self.canvas.winfo_width()
        canvas_height = self.canvas.winfo_height()
        self.canvas.create_image(canvas_width/2,canvas_height/2,image=self.current_image, anchor=tk.CENTER)
        #self.label.configure(image=self.label.image)

        # crop
        image, use_proxy = self.get_image()
        crop_xywh = self.get_crop_xywh(image)
        if crop_xywh is not None:
            canvas_crop_xyxy = self.rectangle_to_canvas(image, *crop_xywh)

            is_crop_preview = self.chk_crop_preview_val.get()
            if is_crop_preview == 0:
                # draw rectangle
                self.canvas.create_rectangle(*canvas_crop_xyxy, dash=(3,3), outline="blue", width=2)

    def _on_change_window_size(self, event):
        # refresh 
        self._refresh_canvas()

    def _on_click_crop_preview(self):
        # refresh 
        self._scale_update()

    def get_original_image(self):
        if self.current_image_pil is None:
            self.current_image_pil, _, _ = exif_transpose_delete_exif(Image.open(self.current_image_path))
        return self.current_image_pil


    def get_image(self):
        '''
        Gets image (get proxy if user sets it and file available)
        Returns:
            image (PIL)
            is_proxy (bool)
        '''
        use_proxy = bool(self.chk_use_proxy_val.get())
        if use_proxy:
            if self.current_image_proxy_pil is None:
                if self.proxy_file_exists is None:
                    proxy_path = os.path.join(self.images_proxydir, self.image_relpath)

                    if os.path.isfile(proxy_path):
                        self.proxy_file_exists = True
                        self.current_image_proxy_pil, _, _ = exif_transpose_delete_exif(Image.open(proxy_path))
                        return self.current_image_proxy_pil, True
                    else:
                        self.proxy_file_exists = False
                        return self.get_original_image(), False
                elif not self.proxy_file_exists:
                    return self.get_original_image(), False
                else:
                    raise NotImplementedError()
            else:
                return self.current_image_proxy_pil, True

        else:
            return self.get_original_image(), False

        
    def _read_camera_exif(self):
        self.camera_info = ''
        self.camera_hashtags = ''
        try:
            with exiftool.ExifTool() as et:
                metadata = et.get_metadata(self.current_image_path)
        except json.decoder.JSONDecodeError:
            return

        for key, val in self.config['exif'].items():
            if 'exif_field' in val.keys():
                if val['exif_field'] in metadata.keys():
                    metavalue = str(metadata[val['exif_field']])

                    if 'format' in val.keys():
                        self.camera_info += val['format'].replace("%s", metavalue) + '\n'
                    if 'hashtag' in val.keys():
                        self.camera_hashtags += val['hashtag'].replace("%s", metavalue) + ' '
                    if 'hashtags' in val.keys():
                        if metavalue in val['hashtags'].keys():
                            self.camera_hashtags += val['hashtags'][metavalue] + ' '
                    if 'conditional_hashtags' in val.keys():
                        for condition in val['conditional_hashtags'].keys():
                            if eval(metavalue + condition):
                                self.camera_hashtags += val['conditional_hashtags'][condition] + ' '



            elif 'exif_fields' in val.keys():
                metavalues = []
                bypass_format = False
                for key2 in val['exif_fields']:
                    if key2 in metadata.keys():
                        metavalues.append(metadata[key2])
                    else:
                        logger.warning('%s not found in EXIF of file %s', key2, self.image_relpath)
                        bypass_format = True

                if not bypass_format and 'format' in val.keys():
                    formatted_str = val['format']
                    for i, metaval in enumerate(metavalues):
                        formatted_str = formatted_str.replace("%{:d}".format(i+1), str(metaval))
                    self.camera_info += formatted_str + '\n'
            else:
                raise ValueError()

    #@profile
    def _change_image(self):
        # This is a Linux path with / no matter what OS you use.
        self.image_relpath = self.image_relpath_list[self.img_idx]
        # This is an OS dependent path with / or \.
        self.current_image_path = os.path.join(self.images_basedir, self.image_relpath.replace('/', os.sep))
        self.current_image_pil = None
        self.current_image_proxy_pil = None
        self.proxy_file_exists = None

        use_proxy = bool(self.chk_use_proxy_val.get())
        pil, is_proxy = self.get_image()
        self.chk_is_proxy_val.set(int(is_proxy))
        self.current_image = ImageTk.PhotoImage(pil)    # this is replaced by scaled image

        self._scale_update()

        self.root.title("({:d}/{:d}) {:s}".format(self.img_idx+1, self.image_count(), self.image_relpath))

        # read exif
        if self.chk_use_exif_val.get() == 1:
            self._read_camera_exif()

        # check db
        self.sqlite_cursor.execute('SELECT * FROM insta_tags WHERE file_relpath=?', (self.image_relpath,))
        db_imageinfo = self.sqlite_cursor.fetchone()

        logger.info("Loaded info from DB: %s", str(db_imageinfo))
        self.initialise_widgets()
        if db_imageinfo is not None:
            if db_imageinfo[SQL_DESCRIPTION] is not None:
                self.txt_description.insert(tk.END,db_imageinfo[SQL_DESCRIPTION])


            if db_imageinfo[SQL_HASHTAG_GROUPS] is not None:
                for hashtag_group in db_imageinfo[SQL_HASHTAG_GROUPS].split(SQL_SEPARATOR):
                    idx = self.hashtag_groups_indices[hashtag_group]
                    self.hashtag_group_chkbtn_vals[idx].set(1)

            if db_imageinfo[SQL_CROP_RATIO] == 'none':
                self.radio_ratio_val.set(RATIO_NONE)
            elif db_imageinfo[SQL_CROP_RATIO] == '4:5':
                self.radio_ratio_val.set(RATIO_45)
            elif db_imageinfo[SQL_CROP_RATIO] == '1:1':
                self.radio_ratio_val.set(RATIO_11)
            else:
                ratio_xy = db_imageinfo[SQL_CROP_RATIO].split(':')
                if len(ratio_xy) != 2:
                    raise ValueError(f'Unknown ratio {db_imageinfo[SQL_CROP_RATIO]}')
                self.radio_ratio_val.set(RATIO_CUSTOM)
                self.spin_ratio_x_val.set(ratio_xy[0])
                self.spin_ratio_y_val.set(ratio_xy[1])

            self.spin_crop_size_val.set(db_imageinfo[SQL_CROP_SIZE])
            self.spin_crop_x_val.set(db_imageinfo[SQL_CROP_X_OFFSET])
            self.spin_crop_y_val.set(db_imageinfo[SQL_CROP_Y_OFFSET])
            self._ratio_disability_update()

            if db_imageinfo[SQL_IS_INSTA_UPLOADED] is not None:
                self.chk_is_uploaded_val.set(db_imageinfo[SQL_IS_INSTA_UPLOADED])
            else:
                self.chk_is_uploaded_val.set(0)

        self._update_description_preview()

        # reset the modified flag
        self.txt_description.edit_modified(False)

    def initialise_widgets(self):
        self.txt_description.delete(1.0,tk.END)
        # initialise hashtag groups (set to False)
        for hashtag_group_val in self.hashtag_group_chkbtn_vals:
            hashtag_group_val.set(0)
        self.radio_ratio_val.set(RATIO_NONE)
        self.spin_crop_size_val.set(1.0)
        self.spin_crop_x_val.set(0.0)
        self.spin_crop_y_val.set(0.0)
        self._ratio_disability_update()

    def image_count(self):
        return len(self.image_relpath_list)

    def _forward_back_disability_update(self, fast_count=20):
        if self.img_idx >= self.image_count() - 1:
            self.btn_forward['state'] = tk.DISABLED
        else:
            self.btn_forward['state'] = tk.NORMAL

        if self.img_idx >= self.image_count() - fast_count:
            self.btn_fast_forward['state'] = tk.DISABLED
        else:
            self.btn_fast_forward['state'] = tk.NORMAL

        if self.img_idx > 0:
            self.btn_back['state'] = tk.NORMAL
        else:
            self.btn_back['state'] = tk.DISABLED

        if self.img_idx > fast_count:
            self.btn_fast_back['state'] = tk.NORMAL
        else:
            self.btn_fast_back['state'] = tk.DISABLED

    def jump(self, imgidx):
        '''
        Jump to the img index
        '''
        if self.img_idx == imgidx:
            return
        if imgidx < 0:
            return
        if imgidx >= self.image_count():
            return

        self._save_txt_description()
        self._save_crop_size()
        self._save_crop_x()
        self._save_crop_y()

        self.img_idx = imgidx

        self._change_image()

        self._forward_back_disability_update()

        self.txt_description.focus()
        self.sld_imgidx_val.set(imgidx+1)

    def forward(self, count = 1):
        '''
        if self.img_idx >= self.image_count() - count:
            return

        self._save_txt_description()
        self._save_crop_size()
        self._save_crop_x()
        self._save_crop_y()

        self.img_idx += count

        self._change_image()

        self._forward_back_disability_update()

        self.txt_description.focus()
        '''
        self.jump(self.img_idx + count)


    def back(self, count = 1):
        '''
        if self.img_idx < count:
            return

        self._save_txt_description()
        self._save_crop_size()
        self._save_crop_x()
        self._save_crop_y()

        self.img_idx -= count

        self._change_image()

        self._forward_back_disability_update()

        self.txt_description.focus()
        '''
        self.jump(self.img_idx - count)

    def fast_forward(self):
        self.forward(20)

    def fast_back(self):
        self.back(20)
Example #18
0
    def __init__(self, win):

        sf = ScrolledFrame(win, width=1210, height=620)
        sf.place(x=300, y=152)
        #sf.pack(side="top",expand=1,fill="both")

        sf.bind_arrow_keys(win)
        sf.bind_scroll_wheel(win)

        canvas = sf.display_widget(Canvas)
        canvas.config(bg="bisque2", width=1210, height=1000)

        mydb = mysql.connector.connect(host="localhost",
                                       user="******",
                                       passwd="Meezan#2018",
                                       database="ice_creame")
        list5 = []
        cursor = mydb.cursor()
        cursor.execute("select pro_id from products")
        list6 = cursor.fetchall()

        cursor.execute("select pro_name from products")
        list1 = cursor.fetchall()
        # print(tabulate(list))

        cursor.execute("select pro_cat from products")
        list2 = cursor.fetchall()

        cursor.execute("select pro_quant from products")
        list3 = cursor.fetchall()

        cursor.execute("select pro_price from products")
        list4 = cursor.fetchall()

        cursor.execute("select decp from products")
        list5 = cursor.fetchall()

        title1 = Label(canvas,
                       bg="bisque2",
                       text="ID",
                       font=("calibri Bold", 15)).place(x=70, y=90)

        title2 = Label(canvas,
                       bg="bisque2",
                       text="Product Name",
                       font=("calibri Bold", 15)).place(x=190, y=90)

        title3 = Label(canvas,
                       bg="bisque2",
                       text="Category",
                       font=("calibri Bold", 15)).place(x=450, y=90)

        title4 = Label(canvas,
                       bg="bisque2",
                       text="Quantity",
                       font=("calibri Bold", 15)).place(x=600, y=90)

        title5 = Label(canvas,
                       bg="bisque2",
                       text="Price",
                       font=("calibri Bold", 15)).place(x=720, y=90)

        title6 = Label(canvas,
                       bg="bisque2",
                       text="Description",
                       font=("calibri Bold", 15)).place(x=900, y=90)

        ym1 = 90
        for m in range(0, list6.__len__()):
            label = Label(canvas,
                          bg="bisque2",
                          text=list6[m],
                          font=("calibri regular", 15))
            ym1 = ym1 + 40
            label.place(x=70, y=ym1)

        l1 = list(list1)
        ind = 0

        ym2 = 0
        y1 = 100
        y2 = 90
        for m in range(0, list1.__len__()):

            a = str(l1[ind])

            c = a.replace("('", "")
            d = c.replace("',)", "")

            label = Label(canvas,
                          bg="bisque2",
                          text=d,
                          font=("calibri regular", 15))
            y2 = y2 + 40
            ind = ind + 1
            label.place(x=140, y=y2)
            y1 = y2 + 35
            ym2 = y1
            canvas.create_line(40, y1, 1200, y1, fill='black')

        y2 = 90

        for i in range(0, list2.__len__()):
            label = Label(canvas,
                          bg="bisque2",
                          text=list2[i],
                          font=("calibri regular", 13))
            y2 = y2 + 40
            label.place(x=410, y=y2)

        canvas.create_line(40, 80, 1200, 80, fill='black')

        canvas.create_line(40, 120, 1200, 120, fill='black')

        canvas.create_line(40, 80, 40, ym2, fill='black')
        canvas.create_line(130, 80, 130, ym2, fill='black')
        canvas.create_line(390, 80, 390, ym2, fill='black')
        canvas.create_line(590, 80, 590, ym2, fill='black')
        canvas.create_line(700, 80, 700, ym2, fill='black')
        canvas.create_line(800, 80, 800, ym2, fill='black')
        canvas.create_line(1200, 80, 1200, ym2, fill='black')

        a = ""
        temp1 = 0
        temp2 = 0
        for i in range(0, list2.__len__()):
            a = list1[i]

            n = a.__len__()
            temp1 = n
            if (temp1 > temp2):
                print(list1[i])
            temp2 = temp1

        y2 = 90
        for i in range(0, list3.__len__()):
            label = Label(canvas,
                          bg="bisque2",
                          text=list3[i],
                          font=("calibri regular", 15))
            y2 = y2 + 40
            label.place(x=620, y=y2)

        y2 = 90
        for i in range(0, list4.__len__()):
            label = Label(canvas,
                          bg="bisque2",
                          text=list4[i],
                          font=("calibri regular", 15))
            y2 = y2 + 40
            label.place(x=730, y=y2)

        l5 = list(list5)
        ind = 0

        y2 = 90
        for i in range(0, l5.__len__()):
            a = str(l5[ind])

            c = a.replace("('", "")
            d = c.replace("',)", "")

            label = Label(canvas,
                          bg="bisque2",
                          text=d,
                          font=("calibri regular", 15))
            y2 = y2 + 40
            ind = ind + 1
            label.place(x=810, y=y2)