Example #1
1
def Mk_Book_display(book, name):
    w = book.page(name)
    disp = Frame(w)

    tree_columns = ('book_no', 'book_name', 'book_author', 'book_publisher', 'in_out_status')
    Entries=Treeview(   disp,
                        columns=tree_columns,
                        show="headings"
                    )


    global_bucket['book_shelf'] = Entries

    vsb = Scrollbar (   disp,
                        orient="vertical",
                        command=Entries.yview)
    Entries.configure(yscrollcommand=vsb.set)
    for col,width in zip(tree_columns,(4,20,10,5,6)):
        Entries.heading(col, text=col.title(), anchor='w')
        Entries.column(col, width=1)

    vsb.pack(side=RIGHT,fill=Y)
    Entries.pack(fill=BOTH, expand=1)
    disp.pack(fill=BOTH, expand=1)

    update()
Example #2
0
class DeviceToFrame(CopilotInnerFrame):
    def __init__(self, master, config, state):
        super(DeviceToFrame, self).__init__(master, config)

        self._state = state

        if self._state.action == 'copy':
            self._frame_lbl['text'] = 'Copy To Directory'
        elif self._state.action == 'delete':
            self._frame_lbl['text'] = 'Delete From Directory'

        self._next_btn['command'] = self._next_cmd

        self._tree = Treeview(self._master, columns=('size'))
        self._tree.heading('size', text='Size')
        self._tree.grid(row=1, column=0, columnspan=3, sticky='nsew')
        self._tree.configure(yscrollcommand=self._sb.set)
        self._sb['command'] = self._tree.yview

        self._item_paths = {}
        self._populate_tree(self._state.to_device.part().mount())

    def _next_cmd(self):
        cur_item = self._tree.focus()
        cur_path = self._item_paths.get(cur_item, '')
        if cur_path != '':
            self._state.device_to_path = cur_path
            self._new_state_window(CopyFileFrame, self._state)

    def _populate_tree(self, tree_root):
        self._item_paths = {}
        def insert_path(tree, path, parent_id):
            dirs = [e for e in scandir(path) if e.is_dir()]
            dirs.sort(key=lambda e: e.name)

            for d in dirs:
                dir_name = d.name
                dir_id = '{}-{}'.format(parent_id, dir_name)
                dir_path = os.path.join(path, dir_name)
                tree.insert(parent_id, 'end', dir_id, text=dir_name, tags=('dir'))
                self._item_paths[dir_id] = dir_path
                try:
                    insert_path(tree, dir_path, dir_id)
                except:
                    pass

        insert_path(self._tree, tree_root, '')

        tree = self._tree
        tree.tag_configure('dir', font=self._config.item_font)
        tree.tag_configure('file', font=self._config.item_font)
        tree.tag_configure('file_odd', background='light grey')
Example #3
0
def Mk_Status_display(book, name):
    w = book.page(name)
    disp = Frame(w)

    tree_columns = ('book_no', 'book_name', 'date', 'staff_id', 'staff_name', 'note')
    Entries=Treeview(   disp,
                        columns=tree_columns,
                        show="headings",
                    )

    global_bucket['status_register'] = Entries

    vsb = Scrollbar (   disp,
                        orient="vertical",
                        command=Entries.yview)
    Entries.configure(yscrollcommand=vsb.set)
    for col in tree_columns:
        Entries.heading(col, text=col.title(), anchor='w')
        Entries.column(col, width=0)
    vsb.pack(side=RIGHT,fill=Y)
    Entries.pack(fill=BOTH, expand=1)
    disp.pack(fill=BOTH, expand=1)

    update()
Example #4
0
class FormChildReport:
    def __init__(self, frm_parent, connection):
        self.connection = connection
        self.id_selected = 0
        self.frm_child_report = LabelFrame(frm_parent)
        self.tlevel_comp_detail = Toplevel(frm_parent)
        self.tlevel_comp_detail.protocol("WM_DELETE_WINDOW", self.click_exit_component_det)
        self.tlevel_comp_detail.withdraw()
        self.tlevel_sol_detail = Toplevel(frm_parent)
        self.tlevel_sol_detail.protocol("WM_DELETE_WINDOW", self.click_exit_solution_det)
        self.tlevel_sol_detail.withdraw()
        self.tlevel_diagram = Toplevel(self.tlevel_sol_detail)
        self.tlevel_diagram.protocol("WM_DELETE_WINDOW", self.click_exit_diagram)
        self.tlevel_diagram.withdraw()
        self.initialize_components()

    def initialize_components(self):
        """
        Method that initialize the visual components for each form associated with the configuration of experiments
        """
        # Button icons used in the forms
        self.csv_icon = PhotoImage(file=r"./Resources/csv.png")
        self.info_icon = PhotoImage(file=r"./Resources/info.png")

        # Components for Report form (list of experiments)
        # General selection section
        lbl_sep1 = Label(self.frm_child_report)
        lbl_sep1.grid(row=0, column=0, padx=10, pady=10, rowspan=7)
        lbl_available_exp = Label(self.frm_child_report, text='Select an experiment', anchor=W)
        lbl_available_exp.config(fg=TEXT_COLOR, font=SUBTITLE2_FONT)
        lbl_available_exp.grid(row=0, column=1, pady=10, sticky=W)
        self.trv_available_exp = Treeview(self.frm_child_report, height=5, columns=('N', 'Experiment'))
        self.trv_available_exp.heading('#0', text='ID', anchor=CENTER)
        self.trv_available_exp.heading('#1', text='N', anchor=CENTER)
        self.trv_available_exp.heading('#2', text='Experiment', anchor=CENTER)
        self.trv_available_exp.column('#0', width=0, minwidth=50, stretch=NO)
        self.trv_available_exp.column('#1', width=20, minwidth=20, stretch=NO)
        self.trv_available_exp.column('#2', width=250, minwidth=250, stretch=NO)
        self.trv_available_exp.bind("<ButtonRelease-1>", self.select_experiment_general)
        self.trv_available_exp.grid(row=1, column=1, columnspan=3, sticky=W, pady=10)
        vsb_trv_avex = Scrollbar(self.frm_child_report, orient="vertical", command=self.trv_available_exp.yview)
        vsb_trv_avex.grid(row=1, column=4, pady=10, sticky=NS)
        self.trv_available_exp.configure(yscrollcommand=vsb_trv_avex.set)
        btn_detail_exp = Button(self.frm_child_report, image=self.info_icon, command=self.click_view_experiment)
        btn_detail_exp.grid(row=0, column=3, pady=10, padx=5, sticky=E)
        btn_detail_exp_ttp = CreateToolTip(btn_detail_exp, 'View experiment information')
        btn_csv = Button(self.frm_child_report, image=self.csv_icon, command=self.click_csv)
        btn_csv.grid(row=0, column=2, pady=10, sticky=E)
        btn_csv_ttp = CreateToolTip(btn_csv, 'Generate .csv file')
        lbl_available_sc = Label(self.frm_child_report, text='Select a scenario', anchor=W)
        lbl_available_sc.config(font=SUBTITLE2_FONT, fg=TEXT_COLOR)
        lbl_available_sc.grid(row=2, column=1, pady=10, columnspan=2, sticky=W)
        self.trv_available_sc = Treeview(self.frm_child_report, height=5, columns=('N', 'Experimental scenario'))
        self.trv_available_sc.heading('#0', text='ID', anchor=CENTER)
        self.trv_available_sc.heading('#1', text='N', anchor=CENTER)
        self.trv_available_sc.heading('#2', text='Experimental scenario', anchor=CENTER)
        self.trv_available_sc.column('#0', width=0, minwidth=50, stretch=NO)
        self.trv_available_sc.column('#1', width=20, minwidth=20, stretch=NO)
        self.trv_available_sc.column('#2', width=250, minwidth=250, stretch=NO)
        self.trv_available_sc.bind("<ButtonRelease-1>", self.select_scenario_general)
        self.trv_available_sc.grid(row=3, column=1, columnspan=3, sticky=W, pady=10)
        vsb_trv_avsc = Scrollbar(self.frm_child_report, orient="vertical", command=self.trv_available_sc.yview)
        vsb_trv_avsc.grid(row=3, column=4, pady=10, sticky=NS)
        self.trv_available_sc.configure(yscrollcommand=vsb_trv_avsc.set)
        btn_detail_sc = Button(self.frm_child_report, image=self.info_icon, command=self.click_view_scenario)
        btn_detail_sc.grid(row=2, column=3, pady=10, sticky=E)
        btn_detail_sc_ttp = CreateToolTip(btn_detail_sc, 'View scenario information')
        lbl_available_prob = Label(self.frm_child_report, text='Select a problem', anchor=W)
        lbl_available_prob.config(font=SUBTITLE2_FONT, fg=TEXT_COLOR)
        lbl_available_prob.grid(row=4, column=1, pady=10, columnspan=2, sticky=W)
        self.trv_available_prob = Treeview(self.frm_child_report, height=5, columns=('N', 'Design problem'))
        self.trv_available_prob.heading('#0', text='ID', anchor=CENTER)
        self.trv_available_prob.heading('#1', text='N', anchor=CENTER)
        self.trv_available_prob.heading('#2', text='Design problem', anchor=CENTER)
        self.trv_available_prob.column('#0', width=0, minwidth=50, stretch=NO)
        self.trv_available_prob.column('#1', width=20, minwidth=20, stretch=NO)
        self.trv_available_prob.column('#2', width=250, minwidth=250, stretch=NO)
        self.trv_available_prob.bind("<ButtonRelease-1>", self.select_problem_general)
        self.trv_available_prob.grid(row=5, column=1, columnspan=3, sticky=W, pady=10)
        vsb_trv_avprob = Scrollbar(self.frm_child_report, orient="vertical", command=self.trv_available_prob.yview)
        vsb_trv_avprob.grid(row=5, column=4, pady=10, sticky=NS)
        self.trv_available_prob.configure(yscrollcommand=vsb_trv_avprob.set)
        btn_detail_prob = Button(self.frm_child_report, image=self.info_icon, command=self.click_view_problem)
        btn_detail_prob.grid(row=4, column=3, pady=10, sticky=E)
        btn_detail_prob_ttp = CreateToolTip(btn_detail_prob, 'View problem report')
        sep_aux1 = Separator(self.frm_child_report, orient=VERTICAL)
        sep_aux1.grid(row=0, column=5, sticky=NS, rowspan=7, padx=30)
        # Detailed selection section
        self.trv_detail_sc = Treeview(self.frm_child_report, height=8,
                                      columns=('N', 'Scenario', 'M1', 'M2', 'M3', 'M4'))
        self.trv_detail_sc.heading('#0', text='ID', anchor=CENTER)
        self.trv_detail_sc.heading('#1', text='N', anchor=CENTER)
        self.trv_detail_sc.heading('#2', text='Scenario', anchor=CENTER)
        self.trv_detail_sc.heading('#3', text='M1', anchor=CENTER)
        self.trv_detail_sc.heading('#4', text='M2', anchor=CENTER)
        self.trv_detail_sc.heading('#5', text='M3', anchor=CENTER)
        self.trv_detail_sc.heading('#6', text='M4', anchor=CENTER)
        self.trv_detail_sc.column('#0', width=0, minwidth=50, stretch=NO)
        self.trv_detail_sc.column('#1', width=20, minwidth=20, stretch=NO)
        self.trv_detail_sc.column('#2', width=250, minwidth=250, stretch=NO)
        self.trv_detail_sc.column('#3', width=55, minwidth=55, stretch=NO)
        self.trv_detail_sc.column('#4', width=55, minwidth=55, stretch=NO)
        self.trv_detail_sc.column('#5', width=55, minwidth=55, stretch=NO)
        self.trv_detail_sc.column('#6', width=55, minwidth=55, stretch=NO)
        self.trv_detail_sc.grid(row=0, column=6, rowspan=2, sticky=W, pady=10)
        vsb_trv_detsc = Scrollbar(self.frm_child_report, orient="vertical", command=self.trv_detail_sc.yview)
        vsb_trv_detsc.grid(row=0, column=7, rowspan=2, pady=10, sticky=NS)
        self.trv_detail_sc.configure(yscrollcommand=vsb_trv_detsc.set)
        self.trv_detail_prob = Treeview(self.frm_child_report, height=8,
                                        columns=('N', 'Problem', 'M1', 'M2', 'M3', 'M4'))
        self.trv_detail_prob.heading('#0', text='ID', anchor=CENTER)
        self.trv_detail_prob.heading('#1', text='N', anchor=CENTER)
        self.trv_detail_prob.heading('#2', text='Problem', anchor=CENTER)
        self.trv_detail_prob.heading('#3', text='M1', anchor=CENTER)
        self.trv_detail_prob.heading('#4', text='M2', anchor=CENTER)
        self.trv_detail_prob.heading('#5', text='M3', anchor=CENTER)
        self.trv_detail_prob.heading('#6', text='M4', anchor=CENTER)
        self.trv_detail_prob.column('#0', width=0, minwidth=50, stretch=NO)
        self.trv_detail_prob.column('#1', width=20, minwidth=20, stretch=NO)
        self.trv_detail_prob.column('#2', width=250, minwidth=250, stretch=NO)
        self.trv_detail_prob.column('#3', width=55, minwidth=55, stretch=NO)
        self.trv_detail_prob.column('#4', width=55, minwidth=55, stretch=NO)
        self.trv_detail_prob.column('#5', width=55, minwidth=55, stretch=NO)
        self.trv_detail_prob.column('#6', width=55, minwidth=55, stretch=NO)
        self.trv_detail_prob.grid(row=2, column=6, rowspan=2, sticky=W, pady=10)
        vsb_trv_detprob = Scrollbar(self.frm_child_report, orient="vertical", command=self.trv_detail_prob.yview)
        vsb_trv_detprob.grid(row=2, column=7, rowspan=2, pady=10, sticky=NS)
        self.trv_detail_prob.configure(yscrollcommand=vsb_trv_detprob.set)
        self.trv_detail_designer = Treeview(self.frm_child_report, height=8, columns=('N', 'Designer', 'M1', 'M2',
                                                                                      'M3', 'M4'))
        self.trv_detail_designer.heading('#0', text='ID', anchor=CENTER)
        self.trv_detail_designer.heading('#1', text='N', anchor=CENTER)
        self.trv_detail_designer.heading('#2', text='Designer', anchor=CENTER)
        self.trv_detail_designer.heading('#3', text='M1', anchor=CENTER)
        self.trv_detail_designer.heading('#4', text='M2', anchor=CENTER)
        self.trv_detail_designer.heading('#5', text='M3', anchor=CENTER)
        self.trv_detail_designer.heading('#6', text='M4', anchor=CENTER)
        self.trv_detail_designer.column('#0', width=0, minwidth=50, stretch=NO)
        self.trv_detail_designer.column('#1', width=20, minwidth=20, stretch=NO)
        self.trv_detail_designer.column('#2', width=250, minwidth=250, stretch=NO)
        self.trv_detail_designer.column('#3', width=55, minwidth=55, stretch=NO)
        self.trv_detail_designer.column('#4', width=55, minwidth=55, stretch=NO)
        self.trv_detail_designer.column('#5', width=55, minwidth=55, stretch=NO)
        self.trv_detail_designer.column('#6', width=55, minwidth=55, stretch=NO)
        self.trv_detail_designer.bind("<Double-1>", self.view_detailed_solution)
        self.trv_detail_designer.grid(row=4, column=6, rowspan=2, sticky=W, pady=10)
        vsb_trv_detdesig = Scrollbar(self.frm_child_report, orient="vertical", command=self.trv_detail_designer.yview)
        vsb_trv_detdesig.grid(row=4, column=7, rowspan=2, pady=10, sticky=NS)
        self.trv_detail_designer.configure(yscrollcommand=vsb_trv_detdesig.set)
        lbl_notes = Label(self.frm_child_report, text='NOTE:\tDouble click on a designer to see\tLEGEND:\tM1=Solution '
                                                      'time | M3=Viewed patterns\n\this solution for a problem ^.\t\t\t'
                                                      'M2=Selection time | M4=Selection efficiency\n')
        lbl_notes.config(fg=TEXT_COLOR, font=NOTE_FONT, justify=LEFT)
        lbl_notes.grid(row=6, column=6, pady=10, sticky=W)
        lbl_sep2 = Label(self.frm_child_report)
        lbl_sep2.grid(row=0, column=8, padx=10, pady=10, rowspan=7)

        # Components for component (experiment, scenario or problem) details
        lbl_sep3 = Label(self.tlevel_comp_detail)
        lbl_sep3.grid(row=0, column=0, padx=10, pady=20)
        self.txt_detail_component = Text(self.tlevel_comp_detail, height=25, width=60)
        self.txt_detail_component.config(font=TEXT_FONT, bg=DISABLED_COLOR)
        self.txt_detail_component.grid(row=0, column=1, pady=20, sticky=W)
        vsb_txt_detcomp = Scrollbar(self.tlevel_comp_detail, orient="vertical", command=self.txt_detail_component.yview)
        vsb_txt_detcomp.grid(row=0, column=2, pady=20, sticky=NS)
        self.txt_detail_component.configure(yscrollcommand=vsb_txt_detcomp.set)
        lbl_sep4 = Label(self.tlevel_comp_detail)
        lbl_sep4.grid(row=0, column=3, padx=10, pady=20)

        # Components of expanded detailed sent solution
        lbl_sep5 = Label(self.tlevel_sol_detail)
        lbl_sep5.grid(row=0, column=0, padx=10, pady=20, rowspan=3)
        lbl_sep6 = Label(self.tlevel_sol_detail)
        lbl_sep6.grid(row=0, column=1, pady=10)
        self.btn_detail_sol = Button(self.tlevel_sol_detail, text='View diagram >>',
                                     command=self.click_view_diagram_sol)
        self.txt_detail_solution = Text(self.tlevel_sol_detail, height=25, width=60)
        self.txt_detail_solution.config(font=TEXT_FONT, bg=DISABLED_COLOR)
        self.txt_detail_solution.grid(row=1, column=1, sticky=W, columnspan=2)
        vsb_txt_detsol = Scrollbar(self.tlevel_sol_detail, orient="vertical", command=self.txt_detail_solution.yview)
        vsb_txt_detsol.grid(row=1, column=3, sticky=NS)
        self.txt_detail_solution.configure(yscrollcommand=vsb_txt_detsol.set)
        lbl_sep7 = Label(self.tlevel_sol_detail)
        lbl_sep7.grid(row=0, column=4, padx=10, pady=20, rowspan=3)
        lbl_sep8 = Label(self.tlevel_sol_detail)
        lbl_sep8.grid(row=2, column=1, pady=10, columnspan=2)

        # Components of expanded sent solution diagram
        self.canvas_expanded = Canvas(self.tlevel_diagram, width=500, height=500)
        self.canvas_expanded.config(background='white', borderwidth=1)
        self.canvas_expanded.grid()

    def show_frm(self):
        """
        Displays the home list of the 'Experiments' form
        """
        self.frm_child_report.grid(row=1, column=0, columnspan=9, rowspan=8, pady=10, padx=10)
        self.retrieve_experiments()

    def hide_frm(self):
        """
        Hides all forms that are currently active
        """
        self.clear_components()
        self.frm_child_report.grid_forget()

    def retrieve_experiments(self):
        """
        This function shows the existing 'Experiments' in the home TreeView
        """
        # Remove existing elements in the list
        for item in self.trv_available_exp.get_children():
            self.trv_available_exp.delete(item)
        self.directive = Message(action=92, information=['finished'])
        self.connection = self.directive.send_directive(self.connection)
        if len(self.connection.message.information) != 0:
            for index, item in enumerate(self.connection.message.information):
                elements = item.split('¥')
                self.trv_available_exp.insert('', 'end', text=elements[0], values=(index + 1,
                                                                                   summarize_text(elements[1], 250)))
            self.available_patterns = Pattern.get_available_patterns(self.connection)
            '''if len(self.trv_available_exp.get_children()) != 0:
                self.trv_available_exp.selection_set(self.trv_available_exp.get_children()[0])
                self.select_experiment_general()'''
        else:
            messagebox.showwarning(parent=self.frm_child_report, title='No experiments',
                                   message='No experiments in finished state')

    def retrieve_scenarios(self, scenarios=None):
        """
        This function shows the existing Experimental scenarios in an 'Experiment'
        """
        # Remove existing elements in the list
        for item in self.trv_available_sc.get_children():
            self.trv_available_sc.delete(item)
        for index, item in enumerate(scenarios):
            elements = item.split('¥')
            self.trv_available_sc.insert('', 'end', text=elements[0], values=(index + 1,
                                                                              summarize_text(elements[1], 250)))
        '''if len(self.trv_available_sc.get_children()) != 0:
            self.trv_available_sc.selection_set(self.trv_available_sc.get_children()[0])
            self.select_scenario()'''

    def retrieve_problems(self, problems=None):
        """
        This function shows the existing Problems in an 'Experimental scenario'
        """
        # Remove existing elements in the list
        for item in self.trv_available_prob.get_children():
            self.trv_available_prob.delete(item)
        for index, item in enumerate(problems):
            elements = item.split('¥')
            self.trv_available_prob.insert('', 'end', text=elements[0], values=(index + 1,
                                                                                summarize_text(elements[1], 250)))
        '''if len(self.trv_available_prob.get_children()) != 0:
            self.trv_available_prob.selection_set(self.trv_available_prob.get_children()[0])
            self.select_problem()'''

    def select_experiment_general(self, event=None):
        """
        This function is activated when the 'Click Experiments TreeView' event ocurrs, it indicates than an experiments
        has been selected
        """
        if len(self.trv_available_exp.selection()) == 1:
            self.clear_components(3)
            id_selected_exp = int(self.trv_available_exp.item(self.trv_available_exp.selection())[
                                      'text'])  # Retrieve id of selected item from TreeView
            self.directive = Message(action=95, information=[id_selected_exp])
            self.connection = self.directive.send_directive(self.connection)
            self.experiment = Experiment(id=id_selected_exp, name=self.connection.message.information[0],
                                         description=self.connection.message.information[1],
                                         design_type=self.connection.message.information[2],
                                         state=self.connection.message.information[3],
                                         creation_date=self.connection.message.information[5],
                                         execution_date=self.connection.message.information[6],
                                         finished_date=self.connection.message.information[7])
            self.retrieve_scenarios(self.connection.message.information[4])
            # Ask to server for dataframe of the measurements for the scenarios of selected experiment
            self.directive = Message(action=107, information=[id_selected_exp, 'experiment'])
            self.connection = self.directive.send_directive(self.connection)
            final_df = get_mean_value(self.connection.message.information[0])
            for index, row in final_df.iterrows():
                self.trv_detail_sc.insert('', 'end', text=row.id, values=(index + 1, summarize_text(row.variable, 250),
                                                                          row.m1, row.m2, row.m3, row.m4))

    def select_scenario_general(self, event=None):
        """
        Function activated when a scenario is selecteded
        """
        if len(self.trv_available_sc.selection()) == 1:
            self.clear_components(2)
            id_selected_sc = int(self.trv_available_sc.item(self.trv_available_sc.selection())[
                                     'text'])  # Retrieve id of selected item from TreeView
            self.directive = Message(action=85, information=[id_selected_sc, 'report', 1])
            self.connection = self.directive.send_directive(self.connection)
            self.scenario = ExperimentalSC(id=id_selected_sc, title=self.connection.message.information[0],
                                           description=self.connection.message.information[1],
                                           id_description_diagram=self.connection.message.information[2],
                                           info_designers=self.connection.message.information[4])
            self.retrieve_problems(self.connection.message.information[3])
            # Ask to server for dataframe of the measurements for the problems of selected scenario
            self.directive = Message(action=107, information=[id_selected_sc, 'scenario'])
            self.connection = self.directive.send_directive(self.connection)
            final_df = get_mean_value(self.connection.message.information[0])
            for index, row in final_df.iterrows():
                self.trv_detail_prob.insert('', 'end', text=row.id, values=(index + 1,
                                                                            summarize_text(row.variable, 250), row.m1,
                                                                            row.m2, row.m3, row.m4))

    def select_problem_general(self, event=None):
        """
        Function activated when a scenario is selected
        """
        if len(self.trv_available_prob.selection()) == 1:
            self.clear_components(1)
            id_selected_prob = int(self.trv_available_prob.item(self.trv_available_prob.selection())[
                                       'text'])  # Retrieve id of selected item from TreeView
            self.directive = Message(action=55, information=[id_selected_prob])
            self.connection = self.directive.send_directive(self.connection)
            self.problem = Problem(id=id_selected_prob, brief_description=self.connection.message.information[0],
                                   description=self.connection.message.information[1],
                                   id_solution=self.connection.message.information[2],
                                   av_patterns=self.available_patterns, connection=self.connection)
            # Ask to server for dataframe of the measurements for the designers of selected problem
            self.directive = Message(action=107, information=[id_selected_prob, 'problem'])
            self.connection = self.directive.send_directive(self.connection)
            final_df = get_mean_value(self.connection.message.information[0])
            for index, row in final_df.iterrows():
                self.trv_detail_designer.insert('', 'end', text=row.id, values=(index + 1,
                                                                                summarize_text(row.variable, 250),
                                                                                row.m1, row.m2, row.m3, row.m4))

    def click_view_experiment(self):
        """
        Function activated when 'Experiment detail' button is pressed, it shows the tlevel_detail window showing
        main information of the selected experimentin trv_available_sc
        """
        if len(self.trv_available_exp.selection()) == 1:
            self.txt_detail_component['state'] = NORMAL
            self.txt_detail_component.delete('1.0', 'end-1c')
            self.txt_detail_component.insert('1.0', 'EXPERIMENT NAME\n{}\n\n'
                                                    'DESCRIPTION\n{}\n\n'
                                                    'DESIGN TYPE\n{}\n\n'
                                                    'CREATION DATETIME\n{}\n\n'
                                                    'EXECUTION DATETIME\n{}\n\n'
                                                    'FINISHED DATETIME\n{}'.
                                             format(self.experiment.name,
                                                    self.experiment.description,
                                                    'One group' if self.experiment.design_type == 1 else 'Two groups',
                                                    self.experiment.creation_date.strftime('%c'),
                                                    self.experiment.execution_date.strftime('%c'),
                                                    self.experiment.finished_date.strftime('%c')))
            self.txt_detail_component['state'] = DISABLED
            self.tlevel_comp_detail.deiconify()
            self.tlevel_comp_detail.grab_set()
        else:
            messagebox.showwarning(parent=self.frm_child_report, title='No selection',
                                   message='You must select one item')

    def click_view_scenario(self):
        """
        Function activated when 'Scenario detail' button is pressed, it shows the tlevel_detail window showing
        main information of the selected experimental scenario in trv_available_sc
        """
        if len(self.trv_available_sc.selection()) == 1:
            self.txt_detail_component['state'] = NORMAL
            self.txt_detail_component.delete('1.0', 'end-1c')
            self.txt_detail_component.insert('1.0', 'EXPERIMENTAL SCENARIO TITLE\n{}\n\n'
                                                    'DESCRIPTION\n{}\n\n'
                                                    'DESIGNERS SCENARIO ASSIGNED: {}\n\n'
                                                    'DESIGNERS COMPLETED SCENARIO: {}\n\n'
                                                    'DESIGNERS DID NOT COMPLETE SCENARIO: {}\n\n'
                                                    'DESIGNERS DID NOT RUN SCENARIO: {}'.
                                             format(self.scenario.title,
                                                    self.scenario.description,
                                                    self.scenario.info_designers[0],
                                                    self.scenario.info_designers[1],
                                                    self.scenario.info_designers[2],
                                                    self.scenario.info_designers[3]))
            self.txt_detail_component['state'] = DISABLED
            self.tlevel_comp_detail.deiconify()
            self.tlevel_comp_detail.grab_set()
        else:
            messagebox.showwarning(parent=self.frm_child_report, title='No selection',
                                   message='You must select one item')

    def click_view_problem(self):
        """
        Function activated when 'Problem detail' button is pressed, it shows the tlevel_detail window showing
        main information of the selected problem in trv_available_prob
        """
        if len(self.trv_available_prob.selection()) == 1:
            aux_patterns = ''
            for item in self.problem.solution.patterns:
                aux_patterns += '- {}\n'.format(item.get_joined_main_s())
            self.txt_detail_component['state'] = NORMAL
            self.txt_detail_component.delete('1.0', 'end-1c')
            self.txt_detail_component.insert('1.0', 'PROBLEM BRIEF DESCRIPTION\n{}\n\n'
                                                    'DESCRIPTION\n{}\n\n'
                                                    'EXPECTED SOLUTION NOTES\n{}\n\n'
                                                    'EXPECTED SOLUTION PATTERNS\n{}'.
                                             format(self.problem.brief_description,
                                                    self.problem.description,
                                                    self.problem.solution.annotations,
                                                    'No patterns configured' if aux_patterns == '' else aux_patterns))
            self.txt_detail_component['state'] = DISABLED
            self.tlevel_comp_detail.deiconify()
            self.tlevel_comp_detail.grab_set()
        else:
            messagebox.showwarning(parent=self.frm_child_report, title='No selection',
                                   message='You must select one item')

    def click_view_diagram_sol(self):
        # Fill summary problem canvas with retrieved image
        load = Image.open(self.solution.diagram.filename)
        load = load.resize((500, 500), Image.ANTIALIAS)
        self.render = ImageTk.PhotoImage(load)
        self.canvas_expanded.delete()
        self.solution.diagram.image = self.canvas_expanded.create_image(0, 0, anchor='nw',
                                                                        image=self.render)  # and display new image
        self.tlevel_diagram.deiconify()
        self.tlevel_diagram.grab_set()

    def click_csv(self):
        if len(self.trv_available_exp.selection()) == 1:
            # Get report in .zip (temporarly)
            path = askdirectory(title='Select destination folder')  # shows dialog box and return the path
            if path:
                # Retrieve zip file and create into the selected folder
                self.directive = Message(action=106, information=[self.experiment.id])
                self.connection = self.directive.send_directive(self.connection)
                report_file = File()
                report_file.write_permanent_file(self.connection.message.information[0],
                                                 self.connection.message.information[1], path)
                messagebox.showinfo(parent=self.frm_child_report, title='Report created',
                                    message='Zipped report created: "{}"'.format(report_file.filename))
        else:
            messagebox.showwarning(parent=self.frm_child_report, title='No selection',
                                   message='You must select one item')

    def view_detailed_solution(self, event=None):
        if len(self.trv_detail_designer.selection()) == 1:
            id_selected_desig = self.trv_detail_designer.item(self.trv_detail_designer.selection())[
                'text']  # Retrieve id of selected item from TreeView
            if id_selected_desig != 'X':
                if self.trv_detail_designer.item(self.trv_detail_designer.selection())['values'][2] != 'X':
                    # Here asks for the sent solution of specific designer
                    self.directive = Message(action=105, information=[int(id_selected_desig), self.problem.id])
                    self.connection = self.directive.send_directive(self.connection)
                    # Getting assigned patterns in current experimental scenario
                    assigned_patterns = []
                    for item in self.connection.message.information[4]:
                        for pattern in self.available_patterns:
                            if item == pattern.id:
                                assigned_patterns.append(pattern)
                    chosen_patterns = []
                    # Getting patterns of sent solution
                    for item in self.connection.message.information[2]:
                        id_pattern = int(item.split('¥')[0])
                        for pattern in self.available_patterns:
                            if id_pattern == pattern.id:
                                chosen_patterns.append(pattern)
                    # Getting current group for the designer
                    current_group = self.connection.message.information[3]
                    # Creating the auxiliar solution
                    self.solution = Solution(annotations=self.connection.message.information[0],
                                             patterns=chosen_patterns,
                                             diagram_id=self.connection.message.information[1],
                                             connection=self.connection)
                    # Adjust visual components depending on the sent solution
                    self.btn_detail_sol.grid_forget()
                    if self.solution.diagram_id is not None:
                        self.btn_detail_sol.grid(row=0, column=2, pady=10, sticky=E)
                    aux_patterns_assign = ''
                    for item in assigned_patterns:
                        aux_patterns_assign += '- {}\n'.format(item.get_joined_main_s())
                    aux_patterns_sent_sol = ''
                    for item in self.solution.patterns:
                        aux_patterns_sent_sol += '- {}\n'.format(item.get_joined_main_s())
                    self.txt_detail_solution['state'] = NORMAL
                    self.txt_detail_solution.delete('1.0', 'end-1c')
                    self.txt_detail_solution.insert('1.0', 'CURRENT PROBLEM\n{}\n\n'
                                                           'CURRENT DESIGNER\n{}\n\n'
                                                           'ASSIGNED GROUP\n{}\n\n'
                                                           'SENT SOLUTION NOTES\n{}\n\n'
                                                           'SENT SOLUTION DIAGRAM\n{}\n\n'
                                                           'ASSIGNED PATTERNS\n{}\n\n'
                                                           'CHOSEN PATTERNS\n{}'.
                                                    format(self.problem.brief_description,
                                                           self.trv_detail_designer.item(
                                                               self.trv_detail_designer.selection())['values'][1],
                                                           'Control group' if current_group == 1 else 'Experimental group',
                                                           self.solution.annotations,
                                                           'No diagram in solution' if self.solution.diagram_id is None else 'Click up button to see diagram ^',
                                                           'No patterns configured' if aux_patterns_assign == '' else aux_patterns_assign,
                                                           'No patterns chosen' if aux_patterns_sent_sol == '' else aux_patterns_sent_sol))
                    self.txt_detail_solution['state'] = DISABLED
                    self.tlevel_sol_detail.deiconify()
                    self.tlevel_sol_detail.grab_set()
                else:
                    messagebox.showwarning(parent=self.frm_child_report, title='Wrong selection',
                                           message='The selected designer does not have a solution for the current '
                                                   'problem')

    def clear_components(self, decision=4):
        if decision > 0:  # When selecting an problem form general list
            for item in self.trv_detail_designer.get_children():
                self.trv_detail_designer.delete(item)
            if decision > 1:  # When selecting a scenario form general list
                for item in self.trv_available_prob.get_children():
                    self.trv_available_prob.delete(item)
                for item in self.trv_detail_prob.get_children():
                    self.trv_detail_prob.delete(item)
                if decision > 2:  # When selecting an experiment form general list
                    for item in self.trv_available_sc.get_children():
                        self.trv_available_sc.delete(item)
                    for item in self.trv_detail_sc.get_children():
                        self.trv_detail_sc.delete(item)
                    if decision > 3:  # Clearing information from all the treeviews
                        for item in self.trv_available_exp.get_children():
                            self.trv_available_exp.delete(item)

    def click_exit_component_det(self):
        self.tlevel_comp_detail.grab_release()
        self.tlevel_comp_detail.withdraw()

    def click_exit_diagram(self):
        self.tlevel_diagram.grab_release()
        self.tlevel_diagram.withdraw()

    def click_exit_solution_det(self):
        self.tlevel_sol_detail.grab_release()
        self.tlevel_sol_detail.withdraw()
Example #5
0
def on_double_click(event):
    def student_update():
        StudentUpdate(name_top.get(), family_top.get(), id_top.get(),
                      birth_top.get(), addr_top.get(), item['text'])
        top.destroy()
        tree_update()

    item_id = event.widget.focus()
    item = event.widget.item(item_id)
    person = StudentGet(item['text']).get()[0]
    top = Toplevel()
    Label(top, text="Name").grid(row=0, column=0)
    name_top = StringVar()
    name_top.set(person[1])
    Entry(top, textvariable=name_top).grid(row=0, column=1)

    Label(top, text="Family").grid(row=1, column=0)
    family_top = StringVar()
    family_top.set(person[2])
    Entry(top, textvariable=family_top).grid(row=1, column=1)

    Label(top, text="B.Date").grid(row=2, column=0)
    birth_top = StringVar()
    birth_top.set(person[3])
    Entry(top, textvariable=birth_top).grid(row=2, column=1)

    Label(top, text="ID").grid(row=3, column=0)
    id_top = StringVar()
    id_top.set(person[4])
    Entry(top, textvariable=id_top).grid(row=3, column=1)

    Label(top, text="Address").grid(row=4, column=0)
    addr_top = StringVar()
    addr_top.set(person[5])
    Entry(top, textvariable=addr_top).grid(row=4, column=1)

    Button(top, text="Edit", command=student_update).grid(row=5,
                                                          column=0,
                                                          columnspan=2)
    grades = Toplevel()
    grd = GradeSearch(item['text']).get()
    tree = Treeview(grades)
    vsb = Scrollbar(grades, orient="vertical", command=tree.yview)
    vsb.grid(row=0, column=1)
    tree.configure(yscrollcommand=vsb.set)
    tree["columns"] = ("m", "p", "c", "h", "pr")
    tree.column("#0", width=30)

    tree.column("m", width=80)
    tree.column("p", width=100)
    tree.column("c", width=90)
    tree.column("h", width=90)
    tree.column("pr", width=90)
    tree.heading("#0", text="ID", anchor=W)

    tree.heading("m", text="Math")
    tree.heading("p", text="Physics")
    tree.heading("c", text="Chemistry")
    tree.heading("h", text="History")
    tree.heading("pr", text="Programming")
    for g in grd:
        tree.insert("", 1, text=g[0], values=(g[2], g[3], g[4], g[5], g[6]))
    tree.grid(row=0, column=0)
Example #6
0
                                                           sticky=W + E)
# #################################################################### #
Label(s_search, text="Name").grid(row=0, column=0)
search_name = StringVar()
Entry(s_search, textvariable=search_name).grid(row=0, column=1)
Button(s_search, text='Search', command=student_search).grid(row=0,
                                                             column=2,
                                                             rowspan=2)

Label(s_search, text="Family").grid(row=1, column=0)
search_family = StringVar()
Entry(s_search, textvariable=search_family).grid(row=1, column=1)
tree = Treeview(s_search, selectmode='browse')
vsb = Scrollbar(s_search, orient="vertical", command=tree.yview)
vsb.grid(row=2, column=3)
tree.configure(yscrollcommand=vsb.set)
tree["columns"] = ("one", "two", "three")
tree.column("#0", width=30)
tree.column("one", width=120)
tree.column("two", width=120)
tree.column("three", width=90)

tree.heading("#0", text="ID", anchor=W)
tree.heading("one", text="Name")
tree.heading("two", text="Family")
tree.heading("three", text="Code", anchor=W)
persons = StudentSelect().get()
for person in persons:
    tree.insert("",
                person[0],
                text=person[0],
Example #7
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        for count in range(0, 10):
            Grid.rowconfigure(self, count, weight=1)
            Grid.columnconfigure(self, count, weight=1)
        # load size from settings and set min max size for window
        controller.maxsize(height=1400, width=1800)
        controller.minsize(height=400, width=600)
        controller.geometry("%dx%d" %
                            (my_lib.settings.dict_by_name('Video')['Width'],
                             my_lib.settings.dict_by_name('Video')['Height']))
        controller.title("Game Library %f" % global_version)
        # Treeview for library

        tv = Treeview(self)
        self.library_treeview = tv
        tv.grid(row=0,
                column=0,
                rowspan=10,
                columnspan=10,
                sticky=(N, E, W, S))
        tv['columns'] = ('Version', 'Source')
        tv.heading('#0', text="Name")
        tv.heading('Version', text="Version")
        tv.heading('Source', text="Source")

        tv.column("#0", anchor='w', minwidth=200)
        tv.column('Version', width=150, minwidth=100, anchor='center')
        tv.column('Source', width=150, minwidth=100, anchor='center')

        # adding scrollbar

        ysb = Scrollbar(self, orient='vertical', command=tv.yview)
        tv.configure(yscroll=ysb.set)
        ysb.grid(row=0, column=9, rowspan=10, sticky='nse')

        # Buttons for the rest

        settings_button = Button(
            self,
            text="Settings",
            command=lambda: controller.show_frame(SettingsPage))
        settings_button.grid(row=10, column=0, sticky=N + S + E + W)

        populate_button = Button(
            self,
            text="Load library",
            command=lambda: fill_tv_from_list(tv, my_lib.as_list(), 3))
        populate_button.grid(row=10, column=1, sticky=N + S + E + W)

        install_button = Button(
            self,
            text="Install game",
            command=lambda: self.installer_page_button(
                my_lib.install_game(tv.item(tv.focus())['text'])))
        install_button.grid(row=10, column=2, sticky=N + S + E + W)

        duplicates_button = Button(self,
                                   text="Find duplicates",
                                   command=my_lib.find_duplicates)
        duplicates_button.grid(row=10, column=3, sticky=N + S + E + W)

        search_entry = Entry(self, text="")
        search_entry.grid(row=10, column=4, columnspan=3, sticky=N + S + E + W)
        self.torrent_search_entry = search_entry

        search_button = Button(
            self,
            text="Find in library",
            command=lambda: fill_tv_from_list(
                tv,
                my_lib.find_games_by_name(search_entry.get()).as_list(), 3))
        search_button.grid(row=10, column=7, sticky=N + S + E + W)

        torrent_button = Button(self,
                                text="Find on torrents",
                                command=self.torrent_button_on_click)
        torrent_button.grid(row=10, column=8, sticky=N + S + E + W)

        quit_button = Button(self, text="Quit", command=controller.destroy)
        quit_button.grid(row=10, column=9, sticky=N + S + E + W)
Example #8
0
class Gr():
    def __init__(self,root,data,SCRY=None):
        self.data=data
        self.columns=[x for x in range(1,8)]+['day']
        root.rowconfigure(1,weight=1)
        root.columnconfigure(0,weight=1)
        root.columnconfigure(1,weight=1)
        root.columnconfigure(2,weight=1)
        f=Frame(root)
        f.columnconfigure(0,weight=1)
        f.rowconfigure(1,weight=1)
        self.v=Combobox(root)
        self.v.grid(row=0,column=0)
        self.v.bind('<<ComboboxSelected>>',self.select_ver)
        f.grid(row=1,column=0,columnspan=3,sticky=N+S)
        self.tree=Treeview(f,
                columns=self.columns,
                displaycolumns=['day']+self.columns[:-1],
                show='headings')
        #self.tree.tag_configure('odd',background='white')
        #self.tree.tag_configure('even',background='gray')
        self.tree.tag_configure('dif',foreground='brown')
        self.tree.tag_configure('work',background='white')
        self.tree.tag_configure('short',background='#F5EFE0')
        self.tree.tag_configure('rest',background='#E0B0B0')
        self.tree.tag_configure('holyday',background='#E7B7A4')
        for c in self.columns:
            self.tree.heading(c,text=c)
            self.tree.column(c,width=65,anchor='center')
        self.tree.column('day',width=30)
        scrX=Scrollbar(f,orient='horizontal',command=self.tree.xview)
        self.tree['xscrollcommand']=scrX.set
        if not SCRY:
            self.scrY=Scrollbar(f,orient='vertical',command=self.yview)
            self.tree['yscrollcommand']=self.scrY.set
        else:
            self.tree['yscrollcommand']=SCRY.set
        self.tree.grid(row=1,column=0,sticky=N+S)
        if not SCRY:
            self.scrY.grid(row=1,column=1,sticky=N+S)
        scrX.grid(row=2,column=0,sticky=E+W)
    def set(self,y,m):
        self.y=y
        self.m=m
        self.show()
    def yview(self,*args):
        self.tree.yview(*args)
        self.yview2(*args)
    def yview2(self,*args):
        pass
    def show(self):
        d=self.data[self.y][self.m]
        V=list(d['degur'].keys())
        self.v['values']=V
        self.v.set(V[0])
        self.select_ver()
    def select_ver(self,*e):
        self.tree.delete(*self.tree.get_children())
        d=self.data[self.y][self.m]
        offset=d['offset']
        v=self.v.get()
        col=[]
        for i,deg in enumerate(d['degurs']):
            self.tree.heading(i+1,text=deg)
            col.append(i+1)
        self.tree.configure(displaycolumns=['day']+col)
        items=dict()

        if 'табель' in d['degur']:
            a=[''.join(x) for x in zip(*[[x for x in d['degur']['план'][j]] \
                    for j in d['degurs']])]
            b=[''.join(x) for x in zip(*[[x for x in d['degur']['табель'][j]] \
                    for j in d['degurs']])]
            c=[x!=y for x,y  in zip(a,b)]
        else:
            c=[False]*32

        for i in range(1,d['days']+1):
            tag = (i+offset) % 7 in [0,6] and 'rest' or 'work'
            if i in d['holydays'] : tag='holyday'
            elif i in d['restdays'] : tag='rest'
            elif i in d['shortdays'] : tag='short'
            elif i in d['workdays'] : tag='work'
            if c[i]: tag=[tag,'dif']
            ii=self.tree.insert('','end',values=['-','-','-','-','-'],tag=tag)
            self.tree.set(ii,column='day',value=i)
            items[i]=ii

        
        for j,s in d['degur'][v].items(): # j-degur
            if not s: continue
            for i,val in enumerate(s[1:-1]):
                if val=='J':
                    val='до'
                elif val=='j':
                    val='од'
                elif val=='a':
                    val='10'
                self.tree.set(items[i+1],column=d['degurs'].index(j)+1,value=val)
            if s[0]=='Н':
                if s[1]=='-':
                    self.tree.set(items[1],column=d['degurs'].index(j)+1,value='Н(8)')
                else:
                    self.tree.set(items[1],column=d['degurs'].index(j)+1,value='!')
            if s[-2]=='Н':
                if s[-1]=='-':
                    self.tree.set(items[len(s)-2],column=d['degurs'].index(j)+1,value='Н(4)')
                else:
                    self.tree.set(items[len(s)-2],column=d['degurs'].index(j)+1,value='!')
        self.calc(self.y,self.m)
    def calc(self,y,m):
        d=self.data[y][m]
        offset=d['offset']
        WH=0
        for i in range(1,d['days']+1):
            if i in d['holydays']: wh=0
            elif i in d['restdays'] : wh=0
            elif i in d['shortdays'] : wh=7
            elif i in d['workdays'] : wh=8
            elif (i+offset) % 7 in [0,6]: wh=0
            else: wh=8
            WH+=wh
Example #9
0
class SearchFrame(Frame):
    content = None
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.analysisthread = None
        self.controller = controller  # set the controller
        self.title = "Article Search"  # title of the window

        #title
        path = os.getcwd() + '\\resources\cyspider.jpg'
        self.img = ImageTk.PhotoImage(Image.open(path))
        self.panel = Label(self, image=self.img)
        self.panel.pack()

        # widgets for results page
        # frame for individual analysis
        self.sf = LabelFrame(self, width=550, height=150, background='#383838', bd=6)

        # frame for results analysis
        self.sf2 = LabelFrame(self, width=550, height=150, background='#383838', bd=6)

        # labels for article topics
        self.topicsHead = Label(self, text='Key Article Subjects', font="times 16 underline", background='#282828',
                                foreground='#5DE0DC')
        self.topics = Label(self, text='Click on an article to see more info', wraplength=500, font='times 16',
                            background='#383838', foreground='#5DE0DC', anchor=W, justify=LEFT)
        calltipwindow.createToolTip(self.topicsHead, "These are a few subjects that were mentioned in the article")

        # labels for results analysis
        self.resultTopicHead = Label(self, text='Most Mentioned Phrases in Results', font="times 16 underline",
                                     background='#282828', foreground='#5DE0DC')
        self.resultTopics = Label(self, text='Processing Data (0%)', wraplength=500, font='times 16',
                                  background='#383838', foreground='#5DE0DC', anchor=W, justify=LEFT)
        calltipwindow.createToolTip(self.resultTopicHead,
                                    "These are the most mentioned phrases in the resulting articles.")

        # helper class to improve code readability
        self.helper = cyhelper.SearchHelper(self)

        self.helper.showsearch()

    def search(self, url):
        # queue to share between gui and threads
        q = queue.Queue()
        self.helper.hidefilters()

        if SearchFrame.content is None:
            searchprogress = Progressbar(self, orient="horizontal", style='mongo.Horizontal.TProgressbar', length=700, mode="indeterminate")
            searchprogress.place(relx=.5, rely=.8, anchor=CENTER)
            searchprogress.start()

            proglabel = Label(self, text="Fetching Results...", font="Times 14", bg="#282828", fg="#FFFFFF")
            proglabel.place(relx=.5, rely=.765, anchor=CENTER)

            # get additional info from filters if they exist
            url = self.helper.addurlfilters(url)

            # start thread to get data from url
            thread = GetDataThread(url, q)
            thread.start()

            # wait until thread is done, then get data from queue
            self.updateuntildata(q, searchprogress)
            self.data = q.get(0)

            # get rid of progress bar
            searchprogress.destroy()
            proglabel.destroy()

        else:
            self.data = SearchFrame.content

        # make sure search didn't time out
        if self.data != "ReadTimeout":
            self.master.master.updateque.queue.clear()

            # start thread to analyze data and repeat process
            self.analysisthread = ResultsAnalysisThread(self.data, self.master.master.analyzer, q, self.resultTopics)
            self.analysisthread.start()

            self.resultTopics.config(text="Processing Data...(0%)")
            self.processingloop('percent')
            self.processingloop('dots')

            self.helper.hidesearch()

            style = Style(self)
            style.configure("Treeview", rowheight=30, fieldbackground='#bdbdbd')
            style.configure("Treeview.Heading", background="#707070", rowheight=60, font="Ariel 14 bold")
            self.tree = Treeview(self, columns=('date','title'), selectmode='browse')
            self.tree['show'] = 'headings'

            self.tree.column('date', width=100, anchor=CENTER)
            self.tree.heading('date', text="Date", command = lambda: self.treeview_sort_column(self.tree,'date',False))
            self.tree.column('title', width=900)
            self.tree.heading('title', text="Article Title", anchor=W,
                              command = lambda: self.treeview_sort_column(self.tree,'title',False))

            #self.tree.place(relx=.3, relheight=1, width=1200)
            self.tree.place(x=330, relheight=1, width=760)

            self.treeyscb = Scrollbar(self, orient="vertical", command=self.tree.yview)
            self.treeyscb.place(relx=1, rely=.5, relheight=1, anchor=E)

            self.tree.configure(yscrollcommand=self.treeyscb.set)

            self.treexscb = Scrollbar(self, orient="horizontal", command=self.tree.xview)
            self.treexscb.place(relx=.3, rely=.999, width=755, anchor=SW)


            self.tree.configure(xscrollcommand=self.treexscb.set)
            self.sf.place(relx=0, rely=.055, relwidth=.30, relheight=.4)

            self.topicsHead.place(relx=.01, rely=.024, relwidth=.28, relheight=.03)
            self.topics.place(relx=.01, rely=.065, relwidth=.28)


            # frame for results analysis
            self.sf2.place(relx=0, rely=.51, relwidth=.30, relheight=.4)


            self.resultTopicHead.place(relx=.01, rely=.475, relwidth=.28, relheight=.03)
            self.resultTopics.place(relx=.01, rely=.52, relwidth=.28)


            # New Search Edit Search Save Search
            self.new_search = Button(self, text='New Search', background='#383838', foreground='#5DE0DC',
                                     font="Veranda 14", command=self.NewSearch)
            self.edit_search = Button(self, text='Edit Search', background='#383838', foreground='#5DE0DC',
                                      font="Veranda 14", command=self.EditSearch)
            self.save_search = Button(self, text='Save Search', background='#383838', foreground='#5DE0DC',
                                      font="Veranda 14", command=self.saveMenu)

            if self.data:
                for count,item in enumerate(self.data):
                    # remove BOM images first from body >uffff
                    item['body'] = ''.join(c for c in unicodedata.normalize('NFC', item['body']) if c <= '\uFFFF')
                    tagname = 'even' if count % 2 == 0 else 'odd'
                    self.tree.insert('', 'end',
                                     values=(parser.parse(item['date']).strftime('%m/%d/%y'), item['title'], item['uri'], item['author'], item['body']),
                                     tag=tagname)

                self.tree.tag_configure('even', font='Verdana 14', background="#9fedea")
                self.tree.tag_configure('odd', font='Verdana 14', background="#dedede")
                self.tree.bind('<Double-1>', self.on_click)
                self.tree.bind('<<TreeviewSelect>>', self.on_single_click)

                self.treeview_sort_column(self.tree,'date',True)


            else:
                self.topics.config(text='No Articles Matching Search')
                self.resultTopics.config(text='')

            self.new_search.place(relx=0, rely=.95, relwidth=.1, relheight=.05, anchor=NW)
            if SearchFrame.content is None:
                self.edit_search.place(relx=.1, rely=.95, relwidth=.1, relheight=.05, anchor=NW)
                if len(self.data) > 0:
                    self.save_search.place(relx=.2, rely=.95, relwidth=.1, relheight=.05, anchor=NW)

        else:
            messagebox.showerror("Too Broad", "Search is too broad. Try refining with filters.")
            self.helper.ent_keyword.focus_set()

        SearchFrame.content = None
        pass

    def NewSearch(self):
        self.analysisthread.stopthread()
        self.deletesearch()
        self.helper.resetsearch()
        self.helper.showsearch()


    def EditSearch(self):
        self.analysisthread.stopthread()
        self.deletesearch()
        self.helper.showsearch()

    def saveMenu(self):
        # create main directory and subdir(current date) if not made already
        path = os.getcwd() + "/Sessions/" + str(datetime.date.today())
        if not os.path.exists(path):
            os.makedirs(path)
        # get a filename from the user or default to current time
        currentTime = datetime.datetime.now().strftime("%H_%M_%S")

        filename = filedialog.asksaveasfilename(defaultextension="txt", initialdir=path, initialfile=currentTime)
        if filename:
            self.saveFilename = filename
            with open(filename, 'w') as outfile:
                json.dump(self.data, outfile)
            # with open(filename, 'w') as f:
            #     f.write("Testing Save As/No Current Save")


    #defind clear search
    def deletesearch(self):
        self.tree.destroy()
        self.sf.place_forget()
        self.topicsHead.place_forget()
        self.topics.place_forget()
        self.sf2.place_forget()
        self.resultTopicHead.place_forget()
        self.resultTopics.place_forget()
        self.new_search.destroy()
        self.treexscb.destroy()
        self.treeyscb.destroy()
        try:
            self.edit_search.destroy()
            self.save_search.destroy()
        except AttributeError:
            pass

    #on click gets the articles information and displays it in the Key Article Subjects window
    def on_single_click(self, event):
        self.topicsHead.config(text="Key Article Subjects")
        item = self.tree.item(self.tree.selection()[0], 'values')
        topicStr = '\n\n'.join(['\n    '.join(textwrap.wrap('\u27a2' + phrase[0], width=33)) for phrase in
                                self.master.master.analyzer.getMostCommonNounPhrases(5, [item[4]],
                                                                                     threading.Event(), 'one')])
        self.topics.config(text=topicStr)

    #on d click will open the article for display
    def on_click(self, event):
        try:
            item = self.tree.selection()[0]
        except IndexError:
            return

        self.n = self.tree.item(item, 'values')
        tw = Toplevel(self)
        xoffset = int(self.winfo_screenwidth() / 2 - 1280 / 2)
        yoffset = int(self.winfo_screenheight() / 2 - 800 / 2)
        tw.geometry("%dx%d+%d+%d" % (800, 600, xoffset, yoffset))  # set geometry of window
        tw.title(self.n[1])
        tb = Text(tw, width=90, height=40, font="Times 14", wrap=WORD)

        makemenu.ArticleMenu(tw, tb, self.n)

        tb.insert('end', self.n[4])
        tb.config(state=DISABLED)
        link = Label(tw, text=self.n[2])
        link.configure(foreground='blue', cursor='hand2')
        link.bind('<1>', self.op_link)
        auth = Label(tw, text='Author: ' + self.n[3])
        articledate = Label(tw, text='Date Published: ' + self.n[0])

        # window formatting for tw
        link.place(x=0, y=0, relwidth=1)
        tb.place(y=20, relwidth=1, relheight=1)
        auth.pack(side=LEFT, anchor='sw')
        articledate.pack(side=RIGHT, anchor='se')
    # op_link "double click on the link at the top of the page opens up the url link
    def op_link(self, event):
        webbrowser.open_new(self.n[2])

    def callEnable(self, event, searchtype):
        self.helper.callenable(event, searchtype)

    def updateuntildata(self, q, progress):
        while q.empty():
            time.sleep(.01)
            progress.step(1)
            progress.master.update()

    def processingloop(self, updatetype):
        string = self.resultTopics.cget('text')
        if len(string) and string[0] == 'P':
            if updatetype == 'percent':
                if not self.master.master.updateque.empty():
                    string = "{}({}%)".format(re.search('Processing Data(\.|\s)*', string).group(0), str(self.master.master.updateque.get(0)))
                    self.after(300, lambda: self.processingloop('percent'))
                else:
                    self.after(100, lambda: self.processingloop('percent'))
            elif updatetype == 'dots':
                numdots = len(string.split('.')) % 4
                string = "Processing Data" + numdots * '.' + (3 - numdots) * ' ' + re.search('\(.+\)', string).group(0)
                self.after(300, lambda: self.processingloop('dots'))

        self.resultTopics.config(text=string)

    def treeview_sort_column(self, tv, col, reverse=False):
        l = [(tv.set(k, col), k) for k in tv.get_children('')]
        if col == 'date':
            l.sort(key=lambda t: "{}/{}/{}".format(t[0].split('/')[2],t[0].split('/')[0],t[0].split('/')[1]), reverse=reverse)
        else:
            l.sort(key=lambda t: t[0], reverse=reverse)

        for index, (val, k) in enumerate(l):
            tv.move(k, '', index)

        for count, child in enumerate(tv.get_children()):
            tagn = 'even' if count % 2 == 0 else 'odd'
            tv.item(child, tag=tagn)

        tv.heading(col,
                   command=lambda: self.treeview_sort_column(tv, col, not reverse))
class TkinterApp(object):
    def __init__(self, q, q2):
        self.txt_mostrar = ('Coches aparcados',
                            'Coches en camino a aparcamiento',
                            'Coches en tránsito',
                            'Coches buscando aparcamiento', 'Plazas Libres')
        self.lista_labels_actualizar = list()
        self.window = Tk()
        self.window.resizable(False, False)
        self.window.title("Park results")
        #generamos la carpeta para guardar los datos
        self.ruta_carpeta = os.getcwd() + "\\Datos_{}".format(
            datetime.now().strftime("%Y-%m-%d %H-%M-%S"))
        if not os.path.exists(self.ruta_carpeta):
            os.makedirs(self.ruta_carpeta)
        for texto, contador in zip(self.txt_mostrar, count(0)):
            self.txt_numero = StringVar()
            self.txt_numero.set(0)
            self.lista_labels_actualizar.append(self.txt_numero)
            Label(self.window, text=texto).grid(column=0,
                                                row=contador,
                                                padx=10,
                                                pady=10)
            Label(self.window,
                  textvariable=self.txt_numero,
                  borderwidth=2,
                  relief="solid",
                  width=5).grid(column=1, row=contador, padx=10)
        Button(self.window,
               text="Ver coches aparcados",
               command=lambda: self.callback()).grid(row=5,
                                                     columnspan=2,
                                                     pady=20)
        self.window.after(1, self.comprobar_cola, q)
        self.window.after(1, self.lanzar_ventana_tabla_aparcados, q2)

    def comprobar_cola(self, c_queue):
        try:
            datos_cola = c_queue.get(0)
            self.lista_labels_actualizar[datos_cola[0]].set(str(datos_cola[1]))
        except Exception as e:
            pass
        finally:
            self.window.after(1, self.comprobar_cola, c_queue)

    def callback(self):
        t2 = multiprocessing.Process(target=envia_peticion, args=(q2, ))
        t2.start()
        # creamos una conexion inversa con el otro hilo
    def abrir_ventana_mapas(self, dataframe):
        test_mapas.lanza_mapa(self, dataframe, self.ruta_carpeta)

    def OnDoubleClick(self, event):
        global df_mostrar
        try:
            df_interno = df_mostrar.round(2)
            item = self.tabla.identify('item', event.x, event.y)
            valor = int(self.tabla.item(item, "text"))
            fila = df_interno.loc[valor, :]
            # una vez clickado se abre una ventana con todos los datos de ese
            # vehiculo
            ventana_detalle = Toplevel()
            ventana_detalle.resizable(False, False)
            ventana_detalle.title("Detalle vehiculo " + str(valor))
            mostrar = ("Hora Entrada", "T busqueda real", "Nodo destino",
                       "Nodo aparcamiento", "Distancia entre nodos",
                       "Intentos aparcamiento", "Tarifa", "Hora aparcamiento",
                       "Duracion aparcamiento", "Parking",
                       "Secciones intento aparcamiento", "Seccion de paso")
            for texto, contador in zip(mostrar, count(0)):
                Label(ventana_detalle, text=texto).grid(column=0,
                                                        row=contador,
                                                        padx=10,
                                                        pady=10)
                Label(ventana_detalle,
                      text=fila[texto],
                      borderwidth=2,
                      relief="solid",
                      width=70).grid(column=1, row=contador, padx=10)
            Button(ventana_detalle,
                   text="Ver mapas",
                   command=lambda: self.abrir_ventana_mapas(fila)).grid(
                       row=12, columnspan=2, pady=20)
        except BaseException:
            print(traceback.print_exc())

    def lanzar_ventana_tabla_aparcados(self, cola2):
        global df_mostrar
        try:
            diccionario = cola2.get(0)
            diccionario = pd.read_excel(
                r"C:\Users\Andrés\Desktop\informes\2019-05-24__08_27_06_informe.xlsx"
            )
            df_mostrar = copy.deepcopy(diccionario)
            print(df_mostrar.head())
            df_mostrar.set_index('ID', inplace=True)
            self.ventana = Toplevel()
            self.ventana.title('Coches aparcados')
            self.ventana.resizable(False, False)
            self.tabla = Treeview(self.ventana,
                                  columns=("coche", "destino", "park",
                                           "intentos"))
            self.tabla['show'] = 'headings'
            for columna in ("coche", "destino", "park", "intentos"):
                self.tabla.column(columna, width=100, anchor='c')
            self.vsb = Scrollbar(self.ventana,
                                 orient="vertical",
                                 command=self.tabla.yview)
            self.vsb.pack(side='right', fill='y')
            self.tabla.bind('<Double-1>', self.OnDoubleClick)
            self.tabla.configure(yscrollcommand=self.vsb.set)
            self.tabla.heading("coche", text="Coche")
            self.tabla.heading("destino", text="Nodo destino")
            self.tabla.heading("park", text="Nodo aparcamiento")
            self.tabla.heading("intentos", text="Intentos")
            for index, coche in diccionario.iterrows():
                self.tabla.insert("",
                                  END,
                                  text=str(index),
                                  values=(str(index), coche["Nodo destino"],
                                          coche["Nodo aparcamiento"],
                                          coche["Intentos aparcamiento"]))
            self.tabla.pack()

        except Empty:
            pass
        except Exception as e:
            print(traceback.print_exc())
        finally:
            self.window.after(1, self.lanzar_ventana_tabla_aparcados, cola2)
Example #11
0
class SearchApplication(GenericFrame):
    FAVICON = "../assets/favicon.ico"

    def __init__(self, parent=None, app_window=None):
        self.lastValue = None
        self.category_option = StringVar("")
        self.column_id = ['ProductDescription', 'ManufacturerName',
                          'ManufacturerPartNumber', 'DigiKeyPartNumber', 'Category']
        Frame.__init__(self, parent)
        self.pack()
        self.parent = parent
        self.app_window = app_window
        self.selectedField = None

        self.parent.title("Partlocater - Advanced Database Search")
        self.parent.iconbitmap(self.FAVICON)
        self.menubar = Frame(self, background='white')
        
        self.menubar.pack(side=TOP, fill=X, expand=YES);
        self.win_frame = Frame(self)
        self.win_frame.pack(side=TOP, fill=BOTH, expand=YES)
        self.editbutton = Menubutton(self.menubar, text='Edit', background='grey98')
        self.editbutton.pack(side=LEFT, fill=X)
        self.editmenu = Menu(self.editbutton, tearoff=0)
        self.editbutton.config(menu=self.editmenu)
        self.copySourcesMenu = Menu(self.editbutton, tearoff=0)
        self.editmenu.add_cascade(label='Copy', menu=self.copySourcesMenu)
        self.copySourcesMenu.add_command(label='Part Number', state=DISABLED, command=self.on_copy_partnumber)
        self.partnumber_index = 0
        self.copySourcesMenu.add_command(label='Selected Parameter', state=DISABLED, command=self.on_copy_parameters)
        self.selectedParameter_index = 1
        self.copySourcesMenu.add_command(label='Selected Part All Parameters', state=DISABLED, command=self.on_copy_all_parameters)
        self.allParameters_index = 2
        self.editmenu.add_command(label='Delete Part', state=DISABLED, command=self.on_delete)
        self.delete_part_index = 1
        
        self.searchLF = LabelFrame(self.win_frame, text="Search")
        self.searchLF.pack(side=LEFT, fill=X, expand=YES, pady=4, padx=6)
        self.searchLeftF = Frame(self.searchLF)
        self.searchLeftF.pack(side=LEFT, anchor=W)
        self.searchRightF = Frame(self.searchLF)
        self.searchRightF.pack(side=LEFT, anchor=N)
        self.searchLabelWidth = 20
        self.catF = Frame(self.searchLeftF)
        self.catF.pack(side=TOP, anchor=W)
        self.catL = Label(self.catF, text='Category', width=self.searchLabelWidth, anchor=W, justify=LEFT)
        self.catL.pack(side=LEFT, fill=X, expand=YES)
        self.cat = StringVar()
        self.catE = Entry(self.catF, textvariable=self.cat, width=50, state=DISABLED)
        self.catE.config(disabledbackground=self.catE.cget("bg"))
        self.catE.config(disabledforeground=self.catE.cget("fg"))
        self.catE.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.category_option = StringVar()
        self.cat.set("All")
        option_list = ['All', 'All'] + Config().tables
        self.catM = OptionMenu(self.searchRightF, self.category_option, *option_list, command=self.on_category)
        self.catM.pack(side=TOP, anchor=N, fill=X, expand=YES)

        self.manF = Frame(self.searchLeftF)
        self.manF.pack(side=TOP, anchor=W)
        self.manL = Label(self.manF, text='ManufacturerName', width=self.searchLabelWidth, anchor=W, justify=LEFT)
        self.manL.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.man = StringVar()
        self.manE = Entry(self.manF, width=50, textvariable=self.man)
        self.manE.pack(side=LEFT, fill=X, expand=YES, pady=4)

        self.mpnF = Frame(self.searchLeftF)
        self.mpnF.pack(side=TOP, anchor=W)
        self.mpnL = Label(self.mpnF, text='ManufacturerPartNumber', width=self.searchLabelWidth, anchor=W, justify=LEFT)
        self.mpnL.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.mpn = StringVar()
        self.mpnE = Entry(self.mpnF, width=50, textvariable=self.mpn)
        self.mpnE.pack(side=LEFT, fill=X, expand=YES, pady=4)

        self.spnF = Frame(self.searchLeftF)
        self.spnF.pack(side=TOP, anchor=W)
        self.spnL = Label(self.spnF, text='DigiKeyPartNumber', width=self.searchLabelWidth, anchor=W, justify=LEFT)
        self.spnL.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.spn = StringVar()
        self.spnE = Entry(self.spnF, width=50, textvariable=self.spn)
        self.spnE.pack(side=LEFT, fill=X, expand=YES, pady=4)

        self.descF = Frame(self.searchLeftF)
        self.descF.pack(side=TOP, anchor=W)
        self.descL = Label(self.descF, text='ProductDescription', width=self.searchLabelWidth, anchor=W, justify=LEFT)
        self.descL.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.desc = StringVar()
        self.descE = Entry(self.descF, width=50, textvariable=self.desc)
        self.descE.pack(side=LEFT, fill=X, expand=YES, pady=4)
        self.descE.focus_force()

        self.findF = Frame(self.searchLeftF)
        self.findF.pack(side=TOP, anchor=E)
        self.findB = ttk.Button(self.findF, text="Find", width=12, command=lambda event=None: self.do_find(event))
        self.findB.pack(side=LEFT, pady=4)
        self.clearB = ttk.Button(self.findF, text="Clear", width=6, command=self.on_clear_search)
        self.clearB.pack(side=LEFT, pady=4)

        self.partsLF = LabelFrame(self, text="Found Components")
        self.partsLF.pack(side=TOP, fill=X, expand=YES, pady=4, padx=4)
        self.partsF = Frame(self.partsLF)
        self.partsF.pack(side=TOP, pady=4, padx=4)
        # change treeview for search here
        self.partsTV = Treeview(self.partsF, selectmode=BROWSE, show='tree headings', columns=self.column_id)

        self.partsTV.bind('<Double-Button-1>', self.on_edit_item)
        self.partsTV.bind('<<TreeviewSelect>>', self.fieldChanged)
        self.partsTV.bind('<Escape>', self.clearSelection)
        self.partsTV.bind('<MouseWheel>', self.mousewheel)
        self.partsTV.bind('<Button-4>', self.mousewheel)
        self.partsTV.bind('<Button-5>', self.mousewheel)
        vcmd = (self.register(self.validateEntry), '%P')
        self.editfield = ttk.Entry(self.partsTV, validate='key', validatecommand=vcmd)
        self.editfield.bind('<Return>', self.updateField)
        self.editfield.bind('<Escape>', self.clearSelection)

        
        self.partsTV.bind('<Control-c>', self.on_copy_element)
        self.partsTV.column("#0", minwidth=0, width=18, stretch=NO)
        for t in self.column_id:
            self.partsTV.heading(t, text=Config().parameter[t])
        self.partsTV.column('Category', width=60)
        self.scrollbar = Scrollbar(self.partsF, orient='vertical', command=self.partsTV.yview)
        self.scrollbar.pack(side=RIGHT, fill=Y, expand=YES, anchor=E)
        self.partsTV.configure(yscroll=self.scrollbar.set)
        self.scrollbar.config(command=self.yview)
        
        self.partsTV.pack(side=TOP, anchor=W, fill=X, expand=YES)
        self.partsTV.delete(*self.partsTV.get_children())
    
        self.statusLF = LabelFrame(self, text="Status")
        self.statusLF.pack(side=BOTTOM, fill=X, expand=YES, pady=4, padx=6)
        self.statusF = Frame(self.statusLF)
        self.statusF.pack(side=TOP, fill=X, expand=YES, padx=6)
        self.status = self.StatusBar(self.statusF, self)

    def validateEntry(self, P):
        if (len(P) <= 120):
            return True
        else:
            self.bell()
            return False
    # scroll bar event
    def yview(self,*args):
        if self.selectedField is not None:
            self.editfield.place_forget()
            self.selectedField = None
        self.partsTV.yview(*args)

    # mousewheel and button4/5 event
    def mousewheel(self, event):
        if self.selectedField is not None:
            self.editfield.place_forget()
            self.selectedField = None
            
    # escape event in treeview or editfield
    def clearSelection(self, event):
        self.editfield.place_forget()
        self.selectedField = None
        self.partsTV.selection_remove(self.partsTV.selection())
        self.status.set("")
              
    # double button event
    def on_edit_item(self, event):
        if self.partsTV.parent(self.partsTV.selection()) == '': # testing should not edit a parent
            self.selectedField = None
            return
        if(self.partsTV.identify_region(event.x, event.y) == 'cell'):
            self.selectedField = self.partsTV.identify_row(event.y)
            x,y,width,height = self.partsTV.bbox(self.selectedField, '#2')
            v = self.partsTV.set(self.selectedField, 1)
            self.editfield.pack()
            self.editfield.delete(0, len(self.editfield.get()))
            self.editfield.insert(0,v)
            self.editfield.selection_range(0, 'end')
            self.editfield.focus_force()
            self.editfield.place(x=x, y=y, width=width, height=height)    

    # find button event
    def on_find(self):
        category = self.cat.get()
        search_list = []
        col_list = []
        search_str = self.man.get()
        if not (validate(search_str)):
            raise Exception("Invalid Manufacture Name")
        search_list.append(search_str)
        col_list.append(Config().parameter['ManufacturerName'])
        search_str = self.mpn.get()
        if not (validate(search_str)):
            raise Exception("Invalid Manufacture Part Number")
        search_list.append(search_str)
        col_list.append(Config().parameter['ManufacturerPartNumber'])
        search_str = self.spn.get()
        if not (validate(search_str)):
            raise Exception("Invalid Supplier Part Number")
        search_list.append(search_str)
        col_list.append(Config().parameter['DigiKeyPartNumber'])
        search_str = self.desc.get().split()
        if not (validate(search_str)):
            raise Exception("Invalid Description")
        search_list += search_str
        col_list.append(Config().parameter['ProductDescription'])
        select = "SELECT * FROM `" + Config().loaded_db.name + "`."
        where = "WHERE"
        like = ""
        i = 0
        for item in search_list:
            if len(item) > 0:
                item = item.replace('%', '\\%')
                item = item.replace('"', '')
                item = item.replace("'", "")
                if i < 3:
                    like += where + " `" + col_list[i] + "` LIKE '" + item + "%'"
                else:
                    like += where + " (`" + col_list[i] + "` LIKE '" + item + "%' OR `" + \
                            col_list[i] + "` LIKE '% " + item + "%')"
                where = " AND"
            i = i + 1 if (i < 3) else i
        self.partsTV.delete(*self.partsTV.get_children())
        count = 0
        if category == "All":
            for table in Config().tables:
                qry = select + "`" + table + "` " + like
                result = Config().loaded_db.query(qry)
                for record in result:
                    v = []
                    spn = record[Config().parameter['DigiKeyPartNumber']]
                    count += 1
                    for id in self.column_id:
                        if id == 'Category':
                            v.append(table)
                        else:
                            v.append(record[Config().parameter[id]])
                    id = self.partsTV.insert('', 'end', iid=spn, text=spn, values=v)
                    for params in record:
                        if record[params] is not None:
                            self.partsTV.insert(id, 'end', text=spn, values=(params, record[params]))
        else:
            qry = select + "`" + category + "` " + like
            result = Config().loaded_db.query(qry)
            for record in result:
                v = []
                count += 1
                spn = record[Config().parameter['DigiKeyPartNumber']]
                for id in self.column_id:
                    if id == 'Category':
                        v.append(category)
                    else:
                        v.append(record[Config().parameter[id]])
                id = self.partsTV.insert('', 'end', iid=spn, text=spn, values=v)
                for params in record:
                    if record[params] is not None:
                        self.partsTV.insert(id, 'end', text=spn, values=(params, record[params]))
        self.status.set(("No" if count == 0 else str(count)) + " items found")

    # return event
    def updateField(self, event):
        value=self.editfield.get()
        self.editfield.place_forget()
        name = self.partsTV.item(self.selectedField, "text")
        if not validate(value):
            self.status.seterror("Invalid value, must not have quotes")
            return
        self.partsTV.set(self.selectedField, "#2", value)
        key = self.partsTV.set(self.selectedField, "#1")
        self.editfield.place_forget()
        element_parent = self.partsTV.parent(self.selectedField)
        table_name = self.partsTV.item(element_parent, "values")[self.column_id.index('Category')]
        part_number = self.partsTV.item(element_parent, "values")[self.column_id.index('DigiKeyPartNumber')]
        set_param = "SET `" + key + "` = '" + value + "' "
        where = "WHERE `" + Config().parameter['DigiKeyPartNumber'] + "` = '" + part_number + "'"
        qry = "UPDATE `" + Config().loaded_db.name + "`.`" + table_name + "` " + set_param + where
        print(qry)
        try:
            Config().loaded_db.query(qry)
        except Exception as e:
            self.status.seterror("Database query failed: %s", e)
            return
        self.status.set("Changed " + key + " to " + value + " for part " + part_number + ".")
        self.partsTV.see(self.selectedField)

    # clear button in search frame   
    def on_clear_search(self):
        self.man.set("")
        self.mpn.set("")
        self.spn.set("")
        self.desc.set("")
        self.cat.set("All")
        self.category_option.set("All")
        self.partsTV.delete(*self.partsTV.get_children())
    
    def do_flash(self):
        current_color = self.element_entry.cget("background")
        if current_color == self.default_color:
            self.element_entry.config(background="red")
        else:
            self.element_entry.config(background=self.default_color)
            return
        self.after(250, self.do_flash)
    # category option menu
    def on_category(self, value):
        self.catE.config(state=NORMAL)
        self.cat.set(value)
        self.catE.config(state=DISABLED)

    #def on_copy(self):
        #selected = self.partsTV.selection()[0]
        #key = self.partsTV.item(selected, "values")[self.column_id.index('DigiKeyPartNumber')]
        #self.app_window.part_num_string.set(key)
        #self.status.set("Part Number '" + key + "' copied to Part Find")
    # Edit -> Delete menu
    def on_delete(self):
        selected = self.partsTV.selection()[0]
        key = self.partsTV.item(selected, "values")[self.column_id.index('DigiKeyPartNumber')]
        table = self.partsTV.item(selected, "values")[self.column_id.index('Category')]
        if messagebox.askokcancel("Delete", "Click OK if you really want to delete '" + key + "' from database?"):
            Config().loaded_db.query("DELETE FROM `" + table + "` WHERE `" + Config().parameter['DigiKeyPartNumber'] +
                                     "` = '" + key + "'")
            self.status.set("Part Number '" + key + "' deleted from database")
            try:
                self.on_find()
            except Exception as e:
                self.status.seterror(e)

    # treeview select event
    def fieldChanged(self, event):
        selected = self.partsTV.selection()
        if len(selected) > 0:
            self.copySourcesMenu.entryconfig(self.partnumber_index, state=NORMAL)
            self.copySourcesMenu.entryconfig(self.allParameters_index, state=NORMAL)
        else:
            self.copySourcesMenu.entryconfig(self.partnumber_index, state=DISABLED)
            self.copySourcesMenu.entryconfig(self.allParameters_index, state=DISABLED)
            self.copySourcesMenu.entryconfig(self.selectedParameter_index, state=DISABLED)
            self.editmenu.entryconfig(self.delete_part_index, state=DISABLED)
            return
        if self.partsTV.parent(selected) == '':
            self.copySourcesMenu.entryconfig(self.selectedParameter_index, state=DISABLED)
            self.editmenu.entryconfig(self.delete_part_index, state=NORMAL)
        else:
            self.copySourcesMenu.entryconfig(self.selectedParameter_index, state=NORMAL)
            self.editmenu.entryconfig(self.delete_part_index, state=DISABLED)
        if selected != self.selectedField:
            self.editfield.place_forget()
            self.selectedField = None


    def on_copy_parameters(self):
        selected = self.partsTV.selection()
        if len(selected) == 0 or self.partsTV.parent(selected) == '':
            return
        try:
            property = self.partsTV.item(selected, "values")
            self.parent.clipboard_clear()
            self.parent.clipboard_append(property[0] + '\t' + property[1])
            self.parent.update()
            self.status.set(property[0] + ' ' + property[1] + " copied to clipboard")
        except Exception as e:
            pass
    
    def on_copy_partnumber(self):
        selected = self.partsTV.selection()
        if len(selected) == 0 or self.partsTV.parent(selected) == '':
            return
        try:
            if self.partsTV.parent(selected) != '':
                selected = self.partsTV.parent(selected)
            partnumber = self.partsTV.item(selected, "values")[self.column_id.index('DigiKeyPartNumber')]
            self.parent.clipboard_clear()
            self.parent.clipboard_append(partnumber)
            self.parent.update()
            self.status.set(" '" + partnumber + "' copied to clipboard")
        except Exception as e:
            pass
    
    def on_copy_all_parameters(self):
        selected = self.partsTV.selection()
        if len(selected) == 0:
            return
        try:
            if self.partsTV.parent(selected) != '':
                selected = self.partsTV.parent(selected)
            partnumber = self.partsTV.item(selected, "values")[self.column_id.index('DigiKeyPartNumber')]            
            elements = self.partsTV.get_children(selected)
            self.parent.clipboard_clear()
            self.parent.clipboard_clear()
            for i in elements:
                element = self.partsTV.item(i, "values")
                self.parent.clipboard_append(element[0] + "\t" + element[1] + "\n")
            self.parent.update()
            self.status.set("All properties of " + partnumber +  " copied to clipboard")
        except Exception as e:
            pass

          # deprecate   
    def on_copy_element(self, event):
        try:
            selected = self.partsTV.selection()[0]
            if self.partsTV.parent(selected) == '':
                partnumber = self.partsTV.item
                elements = self.partsTV.get_children(selected)
                self.parent.clipboard_clear()
                for i in elements:
                    element = self.partsTV.item(i, "values")
                    self.parent.clipboard_append(element[0] + "\t" + element[1] + "\n")
                self.parent.update()
                self.status.set("All properties of " + self.partsTV.item(selected,"values")[3] +  " copied to clipboard")
            else:
                key = self.partsTV.item(selected, "values")[0]
                val = self.partsTV.item(selected, "values")[1]
                self.parent.clipboard_clear()
                self.parent.clipboard_append(val)
                self.parent.update()
                self.status.set(key + " '" + val + "' copied to clipboard")
        except Exception as e:
            pass

    def do_find(self, event):
        try:
            self.on_find()
        except Exception as e:
            self.status.seterror(e)
class NotebookDemo:
    def __init__(self, fr):

        self.fr = fr
        self.st0 = Style()
        self.style = ts.ThemedStyle()  # Style()
        self._create_demo_panel()  # run this before allBtns
        self.allBtns = self.ttkbut + self.cbs[1:] + self.rb

    def _create_demo_panel(self):
        demoPanel = Frame(self.fr, name="demo")
        demoPanel.pack(side='top', fill='both', expand='y')

        # create the notebook
        self.nb = nb = Notebook(demoPanel, name="nb")

        # extend bindings to top level window allowing
        #   CTRL+TAB - cycles thru tabs
        #   SHIFT+CTRL+TAB - previous tab
        #   ALT+K - select tab using mnemonic (K = underlined letter)
        nb.enable_traversal()
        nb.bind("<<NotebookTabChanged>>", self._on_tab_changed)
        nb.pack(fill='both', expand='y', padx=2, pady=3)
        self._create_descrip_tab(nb)
        self._create_treeview_tab(nb)
        self._create_text_tab(nb)

    def _create_descrip_tab(self, nb):
        # frame to hold contents
        frame = Frame(nb, name='descrip')

        # widgets to be displayed on 'Description' tab
        # position and set resize behaviour

        frame.rowconfigure(1, weight=1)
        frame.columnconfigure((0, 1), weight=1, uniform=1)
        lf = LabelFrame(frame, text='Animals')
        lf.pack(pady=2, side='left', fill='y')
        themes = [
            'cat', 'dog', 'horse', 'elephant', 'crocodile', 'bat',
            'grouse\nextra line made longer'
        ]
        self.ttkbut = []
        for t in themes:
            b = Button(lf, text=t)
            b.pack(pady=2)
            self.ttkbut.append(b)

        lF2 = LabelFrame(frame, text="Theme Combobox")
        lF2.pack(anchor='nw')
        themes = list(sorted(self.style.get_themes()))
        themes.insert(0, "Pick a theme")
        self.cb = cb = Combobox(lF2,
                                values=themes,
                                state="readonly",
                                height=10)
        cb.set(themes[0])
        cb.bind('<<ComboboxSelected>>', self.change_style)
        cb.grid(row=0, column=0, sticky='nw', pady=5)

        lF3 = LabelFrame(frame, text="Entry")
        lF3.pack(anchor='ne')
        self.en = Entry(lF3)
        self.en.grid(row=0, column=0, sticky='ew', pady=5, padx=5)

        lf1 = LabelFrame(frame, text='Checkbuttons')
        lf1.pack(pady=2, side='left', fill='y')

        # control variables
        self.enabled = IntVar()
        self.cheese = IntVar()
        self.tomato = IntVar()
        self.basil = IntVar()
        self.oregano = IntVar()
        # checkbuttons
        self.cbOpt = Checkbutton(lf1,
                                 text='Enabled',
                                 variable=self.enabled,
                                 command=self._toggle_opt)
        cbCheese = Checkbutton(text='Cheese',
                               variable=self.cheese,
                               command=self._show_vars)
        cbTomato = Checkbutton(text='Tomato',
                               variable=self.tomato,
                               command=self._show_vars)
        sep1 = Separator(orient='h')
        cbBasil = Checkbutton(text='Basil',
                              variable=self.basil,
                              command=self._show_vars)
        cbOregano = Checkbutton(text='Oregano',
                                variable=self.oregano,
                                command=self._show_vars)
        sep2 = Separator(orient='h')

        self.cbs = [
            self.cbOpt, sep1, cbCheese, cbTomato, sep2, cbBasil, cbOregano
        ]
        for opt in self.cbs:
            if opt.winfo_class() == 'TCheckbutton':
                opt.configure(onvalue=1, offvalue=0)
                opt.setvar(opt.cget('variable'), 0)

            opt.pack(in_=lf1,
                     side='top',
                     fill='x',
                     pady=2,
                     padx=5,
                     anchor='nw')

        lf2 = LabelFrame(frame, text='Radiobuttons', labelanchor='n')
        lf2.pack(pady=2, side='left', fill='y')

        self.rb = []
        self.happiness = StringVar()
        for s in ['Great', 'Good', 'OK', 'Poor', 'Awful']:
            b = Radiobutton(lf2,
                            text=s,
                            value=s,
                            variable=self.happiness,
                            command=lambda s=s: self._show_vars())
            b.pack(anchor='nw', side='top', fill='x', pady=2)
            self.rb.append(b)

        right = LabelFrame(frame, text='Control Variables')
        right.pack(pady=2, side='left', fill='y')

        self.vb0 = Label(right, font=('Courier', 10))
        self.vb1 = Label(right, font=('Courier', 10))
        self.vb2 = Label(right, font=('Courier', 10))
        self.vb3 = Label(right, font=('Courier', 10))
        self.vb4 = Label(right, font=('Courier', 10))
        self.vb5 = Label(right, font=('Courier', 10))

        self.vb0.pack(anchor='nw', pady=3)
        self.vb1.pack(anchor='nw', pady=3)
        self.vb2.pack(anchor='nw', pady=3)
        self.vb3.pack(anchor='nw', pady=3)
        self.vb4.pack(anchor='nw', pady=3)
        self.vb5.pack(anchor='nw', pady=3)

        self._show_vars()
        # add to notebook (underline = index for short-cut character)
        nb.add(frame, text='Description', underline=0, padding=2)

    # =========================================================================
    def _create_treeview_tab(self, nb):
        # Populate the second pane. Note that the content doesn't really matter
        # tree = None
        self.backg = ["white", '#f0f0ff']
        tree_columns = ("country", "capital", "currency")
        tree_data = [("Argentina", "Buenos Aires", "ARS"),
                     ("Australia", "Canberra", "AUD"),
                     ("Brazil", "Brazilia", "BRL"),
                     ("Canada", "Ottawa", "CAD"), ("China", "Beijing", "CNY"),
                     ("France", "Paris", "EUR"), ("Germany", "Berlin", "EUR"),
                     ("India", "New Delhi", "INR"), ("Italy", "Rome", "EUR"),
                     ("Japan", "Tokyo", "JPY"),
                     ("Mexico", "Mexico City", "MXN"),
                     ("Russia", "Moscow", "RUB"),
                     ("South Africa", "Pretoria", "ZAR"),
                     ("United Kingdom", "London", "GBP"),
                     ("United States", "Washington, D.C.", "USD")]

        #test_length = font.Font(family="Times", size=12, weight="bold").measure('Test')
        #fact = int(test_length / 30 * 20.45) # 30 is the length of Test in Idle
        fact = font.Font(font="TkDefaultFont").metrics('linespace')

        self.st0.configure('fact.Treeview',
                           rowheight=fact,
                           font=font.nametofont("TkDefaultFont"))

        container = Frame(nb)
        container.grid(sticky='nsew')  #(fill='both', expand=True)
        self.tree = Treeview(container,
                             columns=tree_columns,
                             show="headings",
                             style='fact.Treeview')
        vsb = Scrollbar(container, orient="vertical", command=self.tree.yview)
        hsb = Scrollbar(container,
                        orient="horizontal",
                        command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
        vsb.grid(column=1, row=0, sticky='ns', in_=container)
        hsb.grid(column=0, row=1, sticky='ew', in_=container)

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

        for col in tree_columns:
            self.tree.heading(
                col,
                text=col.title(),
                command=lambda c=col: self.sortby(self.tree, c, 0))
            # XXX tkFont.Font().measure expected args are incorrect according
            #     to the Tk docs
            self.tree.column(col,
                             width=Font().measure(col.title()),
                             stretch=False)

        for ix, item in enumerate(tree_data):
            itemID = self.tree.insert('', 'end', values=item)
            self.tree.item(itemID, tags=itemID)
            self.tree.tag_configure(itemID, background=self.backg[ix % 2])

            # adjust columns lengths if necessary
            for indx, val in enumerate(item):
                ilen = Font().measure(val)
                if self.tree.column(tree_columns[indx], width=None) < ilen:
                    self.tree.column(tree_columns[indx], width=ilen)

        sg = Sizegrip(container)
        sg.grid(sticky='e')

        nb.add(container, text='Treeview', underline=0, padding=2)

    # =========================================================================
    def _create_text_tab(self, nb):
        # populate the third frame with other widgets
        self.pw = PanedWindow(nb, name='pw')
        self.pw.pack(fill='both', expand=True)

        lF = LabelFrame(self.pw, text="Slider")
        fr1 = Frame(lF)
        fr1.grid(row=0, column=0)
        from_ = -5
        to = 105
        value = 19
        step = 11
        fontSize = 9
        scvar = IntVar()
        #scRange=self.any_number_range(from_,to,step)
        #scLen = len(scRange[1]) * (fontSize + 10)

        self.sc = TtkScale(fr1,
                           from_=from_,
                           to=to,
                           variable=scvar,
                           orient='vertical',
                           length=200,
                           showvalue=True,
                           command=lambda s: scvar.set('%d' % float(s)),
                           tickinterval=5,
                           resolution=5)
        #self.sc = Scale(fr1, from_=from_, to=to, variable=scvar,
        #orient='vertical',length=scLen,
        #command=lambda s: scvar.set('%d' % float(s) ))
        self.sc.set(value)
        #l1 = Label(fr1,textvariable=scvar,width=5)
        l1 = Spinbox(fr1, from_=from_, to=to, textvariable=scvar, width=4)
        l1.grid(row=0, column=0, pady=2)
        self.sc.grid(row=0, column=1, pady=5, padx=40)
        fr = Frame(fr1)
        fr.grid(row=0, column=2)
        #for ix,sR in enumerate(scRange[1]):
        #lb = Label(fr, text=sR, font=('Courier New', str(fontSize)))
        #lb.grid(row=ix, column=1)

        schvar = IntVar()
        a = -5
        b = 105
        #schRange = self.any_number_range(a,b,s=11)
        #schLen = Font().measure(schRange[0])
        self.sch = TtkScale(lF,
                            from_=a,
                            to=b,
                            length=200,
                            variable=schvar,
                            orient='horizontal',
                            showvalue=True,
                            command=lambda s: schvar.set('%d' % float(s)),
                            tickinterval=5,
                            resolution=5)
        #self.sch = Scale(lF, from_=a, to=b, length=schLen, variable=schvar,
        #orient='horizontal',
        #command=lambda s: schvar.set('%d' % float(s) ))
        self.sch.set(23)
        #l2 = Label(lF,textvariable=schvar)
        l2 = Spinbox(lF, from_=a, to=b, textvariable=schvar, width=4)
        l2.grid(row=1, column=1, pady=2)
        self.sch.grid(row=2, column=1, pady=40, padx=5, sticky='nw')
        #l3 = Label(lF,text=schRange[0], font=('Courier New', str(fontSize)))
        #l3.grid(row=3,column=1,pady=2)
        self.sch.bind("<ButtonRelease-1>", self.show_x)
        self.pw.add(lF)

        lF1 = LabelFrame(self.pw, text="Progress", name='lf')
        pb1var = IntVar()
        pb2var = IntVar()
        self.pbar = Progressbar(lF1,
                                variable=pb1var,
                                length=150,
                                mode="indeterminate",
                                name='pb1',
                                orient='horizontal')
        self.pb2 = Progressbar(lF1,
                               variable=pb2var,
                               mode='indeterminate',
                               name='pb2',
                               orient='vertical')
        self.pbar["value"] = 25
        self.pbar.grid(row=1, column=0, padx=5, pady=5, sticky='nw')
        self.pb2.grid(row=1, column=1, padx=5, pady=5, sticky='nw')
        l3 = Label(lF1, textvariable=pb1var)
        l3.grid(row=0, column=0, pady=2, sticky='nw')
        l4 = Label(lF1, textvariable=pb2var)
        l4.grid(row=0, column=1, pady=2, sticky='nw')
        start = Button(lF1,
                       text='Start Progress',
                       command=lambda: self._do_bars('start'))
        stop = Button(lF1,
                      text='Stop Progress',
                      command=lambda: self._do_bars('stop'))
        start.grid(row=2, column=0, padx=5, pady=5, sticky='nw')
        stop.grid(row=3, column=0, padx=5, pady=5, sticky='nw')
        self.pw.add(lF1)

        # add to notebook (underline = index for short-cut character)
        nb.add(self.pw, text='Sliders & Others', underline=0)

    #=========================================================================
    def _toggle_opt(self):
        # state of the option buttons controlled
        # by the state of the Option frame label widget
        if self.enabled.get() == 1:
            self.sc.state(['!disabled'])
            self.sch.state(['!disabled'])
            self.cb.state(['!disabled'])
            self.en.state(['!disabled'])
            self.pbar.state(['!disabled'])
            self.pb2.state(['!disabled'])
        else:
            self.sc.state(['disabled'])
            self.sch.state(['disabled'])
            self.cb.state(['disabled'])
            self.en.state(['disabled'])
            self.pbar.state(['disabled'])
            self.pb2.state(['disabled'])

        for opt in self.allBtns:
            if opt.winfo_class() != 'TSeparator':
                if self.cbOpt.instate(('selected', )):
                    opt['state'] = '!disabled'  # enable option
                    self.nb.tab(1, state='normal')
                else:
                    opt['state'] = 'disabled'
                    self.nb.tab(1, state='disabled')
        self._show_vars()

    def _show_vars(self):
        # set text for labels in var_panel to include the control
        # variable name and current variable value
        self.vb0['text'] = '{:<11} {:<8}'.format('enabled:',
                                                 self.enabled.get())
        self.vb1['text'] = '{:<11} {:<8}'.format('cheese:', self.cheese.get())
        self.vb2['text'] = '{:<11} {:<8}'.format('tomato:', self.tomato.get())
        self.vb3['text'] = '{:<11} {:<8}'.format('basil:', self.basil.get())
        self.vb4['text'] = '{:<11} {:<8}'.format('oregano:',
                                                 self.oregano.get())
        self.vb5['text'] = '{:<11} {:<8}'.format('happiness:',
                                                 self.happiness.get())

    def sortby(self, tree, col, descending):
        """Sort tree contents when a column is clicked on."""
        # grab values to sort
        data = [(tree.set(child, col), child)
                for child in tree.get_children('')]

        # reorder data
        data.sort(reverse=descending)
        for indx, item in enumerate(data):
            tree.move(item[1], '', indx)

        # switch the heading so that it will sort in the opposite direction
        tree.heading(col,
                     command=lambda col=col: self.sortby(
                         tree, col, int(not descending)))
        # reconfigure tags after ordering
        list_of_items = tree.get_children('')
        for i in range(len(list_of_items)):
            tree.tag_configure(list_of_items[i], background=self.backg[i % 2])

    def any_number_range(self, a, b, s=1):
        """ Generate consecutive values list between two numbers with optional
        step (default=1)."""
        if (a == b):
            return a
        else:
            mx = max(a, b)
            mn = min(a, b)
            result = []
            output = ''
            # inclusive upper limit. If not needed, delete '+1' in the line
            #below
            while (mn < mx + 1):
                # if step is positive we go from min to max
                if s > 0:
                    result.append(mn)
                    mn += s
                # if step is negative we go from max to min
                if s < 0:
                    result.append(mx)
                    mx += s
                # val
            maxLen = 0
            output = ""
            for ix, res in enumerate(result[:-1]):  # last value ignored
                if len(str(res)) > maxLen:
                    maxLen = len(str(res))
            if maxLen == 1:
                # converts list to string
                output = ' '.join(str(i) for i in result)
            else:
                for ix, res in enumerate(result):
                    if maxLen == 2:
                        if len(str(res)) == 1:
                            output = output + str(res) + " " * maxLen
                        elif len(str(res)) == 2:
                            output = output + str(res) + " "
                        else:
                            output = output + str(res)

            return output, result

    def _do_bars(self, op):
        pbar = self.pbar.nametowidget('.fr.demo.nb.pw.lf.pb1')
        pb2 = self.pb2.nametowidget('.fr.demo.nb.pw.lf.pb2')

        if op == 'start':
            pbar.start()
            pb2.start()
        else:
            pbar.stop()
            pb2.stop()

    def change_style(self, event=None):
        """set the Style to the content of the Combobox"""
        content = self.cb.get()
        try:
            self.style.theme_use(content)
            fact = font.Font(font="TkDefaultFont").metrics('linespace')
            self.st0.configure('font.Treeview',
                               rowheight=fact,
                               font=font.nametofont("TkDefaultFont"))
        except TclError as err:
            messagebox.showerror('Error', err)
        else:
            root.title(content)

    def change_theme(self, theme):
        window = ttktheme.ThemedTk()
        window.set_theme(theme)
        root.title(theme)

    def _on_tab_changed(self, event):
        event.widget.update_idletasks()

        tab = event.widget.nametowidget(event.widget.select())
        event.widget.configure(height=tab.winfo_reqheight(),
                               width=tab.winfo_reqwidth())
Example #13
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.amLabel = Label(self, text='am')
        self.amLabel.grid(row= 0 , column= 0, sticky= EW)
        #天 下拉菜单
        tageVariable = StringVar()
        tageVariable.set('Tag auswählen')
        self.tageOptionsMenu = OptionMenu(self, tageVariable, *tageOptions)
        self.tageOptionsMenu.grid(row= 0 , column= 1, sticky= EW)
        self.tageOptionsMenu.configure(width=20)

        self.vonLabel = Label(self, text='von')
        self.vonLabel.grid(row= 1 , column= 0, sticky= EW)
        #小时 下拉菜单
        anfangsStundeVariable = StringVar()
        anfangsStundeVariable.set('Stunde auswählen')
        self.anfangsStundenOptionsMenu = OptionMenu(self, anfangsStundeVariable, *stundenOptions)
        self.anfangsStundenOptionsMenu.grid(row= 1 , column= 1, sticky= EW)
        self.anfangsStundenOptionsMenu.configure(width=20)

        #分钟 下拉菜单
        anfangsMinutenVariable = StringVar()
        anfangsMinutenVariable.set('minute auswählen')
        self.anfangsMinutenOptionsMenu = OptionMenu(self, anfangsMinutenVariable, *minutenOptions)
        self.anfangsMinutenOptionsMenu.grid(row= 1 , column= 2, sticky= EW)
        self.anfangsMinutenOptionsMenu.configure(width=20)
        
        self.bisLabel = Label(self, text='bis')
        self.bisLabel.grid(row= 2 , column= 0, sticky= EW)
        #小时 下拉菜单
        endeStundeVariable = StringVar()
        endeStundeVariable.set('Stunde auswählen')
        self.endeStundenOptionsMenu = OptionMenu(self, endeStundeVariable, *stundenOptions)
        self.endeStundenOptionsMenu.grid(row= 2 , column= 1, sticky= EW)
        self.endeStundenOptionsMenu.configure(width=20)

        #分钟 下拉菜单
        endeMinutenVariable = StringVar()
        endeMinutenVariable.set('minute auswählen')
        self.endeMinutenOptionsMenu = OptionMenu(self, endeMinutenVariable, *minutenOptions)
        self.endeMinutenOptionsMenu.grid(row= 2, column= 2, sticky= EW)
        self.endeMinutenOptionsMenu.configure(width=20)

        #课程展示组件
        self.vsBar = Scrollbar(self.master)
        self.vsBar.grid(row=0,column =4, sticky= NS) 
        self.tree = Treeview(self.master, columns=('c1', 'c2', 'c3'), show="headings")
        self.vsBar.configure(command=self.tree.yview)
        self.tree.configure(yscrollcommand=self.vsBar.set)

        self.tree.grid(row= 0, column= 3, sticky= NSEW)
        self.tree.column('c1', width=400, anchor='center')
        self.tree.column('c2', width=100, anchor='center')
        self.tree.column('c3', width=250, anchor='center')
        self.tree.heading('c1', text='Kurs')
        self.tree.heading('c2', text='Lehrer')
        self.tree.heading('c3', text='Zeitraum')

        #确认按键
        self.doneButton = Button(self, text = 'done', command=lambda: self.checkTheList(self.tree, tageVariable.get(), anfangsStundeVariable.get(), anfangsMinutenVariable.get(), endeStundeVariable.get(), endeMinutenVariable.get()))  
        self.doneButton.grid(row= 4 , column= 1, sticky= EW)
        #退出按键
        self.quitButton = Button(self, text='Quit', command=self.quit)
        self.quitButton.grid(row= 4 , column= 2, sticky= EW)
    
    def checkTheList(self, treeBox, tag, aStunde, aMinute, eStunde, eMinute):
        try:
            if treeBox.get_children() is not None:
                treeBox.delete(*treeBox.get_children())
            if tag and aStunde and aMinute and eStunde and eMinute:
                f = open("TU_Spider/fachbereich_list.json", 'r', encoding='GBK')
                pattern = re.compile(r'.*}')
                for line in f.readlines():
                    #print(pattern.search(line).group(0))
                    dic = json.loads(pattern.search(line).group(0))
                    if tag[0:2] in dic['zeitraum']: 
                        zeit = re.findall(r'\[[0-9]{2}:[0-9]{2}\]', dic['zeitraum']) #z.B. zeit = ['[09:50]', '[16:05]']
                        if int(zeit[0][1:3]) > int(aStunde) or ( int(zeit[0][4:6]) >= int(aMinute) and int(zeit[0][1:3]) == int(aStunde) ):
                            if int(zeit[1][1:3]) < int(eStunde) or ( int(zeit[1][4:6]) <= int(eMinute) and  int(zeit[1][1:3]) == int(eStunde)):
                                treeBox.insert("", 1, text="" ,values=(dic['name'], dic['lehrer'], dic['zeitraum']))
        finally:
            f.close()
Example #14
0
class EventScheduler(Tk):
    def __init__(self):
        Tk.__init__(self, className='Scheduler')
        logging.info('Start')
        self.protocol("WM_DELETE_WINDOW", self.hide)
        self._visible = BooleanVar(self, False)
        self.withdraw()

        self.icon_img = PhotoImage(master=self, file=ICON48)
        self.iconphoto(True, self.icon_img)

        # --- systray icon
        self.icon = TrayIcon(ICON, fallback_icon_path=ICON_FALLBACK)

        # --- menu
        self.menu_widgets = SubMenu(parent=self.icon.menu)
        self.menu_eyes = Eyes(self.icon.menu, self)
        self.icon.menu.add_checkbutton(label=_('Manager'),
                                       command=self.display_hide)
        self.icon.menu.add_cascade(label=_('Widgets'), menu=self.menu_widgets)
        self.icon.menu.add_cascade(label=_("Eyes' rest"), menu=self.menu_eyes)
        self.icon.menu.add_command(label=_('Settings'), command=self.settings)
        self.icon.menu.add_separator()
        self.icon.menu.add_command(label=_('About'),
                                   command=lambda: About(self))
        self.icon.menu.add_command(label=_('Quit'), command=self.exit)
        self.icon.bind_left_click(lambda: self.display_hide(toggle=True))

        add_trace(self._visible, 'write', self._visibility_trace)

        self.menu = Menu(self, tearoff=False)
        self.menu.add_command(label=_('Edit'), command=self._edit_menu)
        self.menu.add_command(label=_('Delete'), command=self._delete_menu)
        self.right_click_iid = None

        self.menu_task = Menu(self.menu, tearoff=False)
        self._task_var = StringVar(self)
        menu_in_progress = Menu(self.menu_task, tearoff=False)
        for i in range(0, 110, 10):
            prog = '{}%'.format(i)
            menu_in_progress.add_radiobutton(label=prog,
                                             value=prog,
                                             variable=self._task_var,
                                             command=self._set_progress)
        for state in ['Pending', 'Completed', 'Cancelled']:
            self.menu_task.add_radiobutton(label=_(state),
                                           value=state,
                                           variable=self._task_var,
                                           command=self._set_progress)
        self._img_dot = tkPhotoImage(master=self)
        self.menu_task.insert_cascade(1,
                                      menu=menu_in_progress,
                                      compound='left',
                                      label=_('In Progress'),
                                      image=self._img_dot)
        self.title('Scheduler')
        self.rowconfigure(1, weight=1)
        self.columnconfigure(0, weight=1)

        self.scheduler = BackgroundScheduler(coalesce=False,
                                             misfire_grace_time=86400)
        self.scheduler.add_jobstore('sqlalchemy',
                                    url='sqlite:///%s' % JOBSTORE)
        self.scheduler.add_jobstore('memory', alias='memo')
        # --- style
        self.style = Style(self)
        self.style.theme_use("clam")
        self.style.configure('title.TLabel', font='TkdefaultFont 10 bold')
        self.style.configure('title.TCheckbutton',
                             font='TkdefaultFont 10 bold')
        self.style.configure('subtitle.TLabel', font='TkdefaultFont 9 bold')
        self.style.configure('white.TLabel', background='white')
        self.style.configure('border.TFrame',
                             background='white',
                             border=1,
                             relief='sunken')
        self.style.configure("Treeview.Heading", font="TkDefaultFont")
        bgc = self.style.lookup("TButton", "background")
        fgc = self.style.lookup("TButton", "foreground")
        bga = self.style.lookup("TButton", "background", ("active", ))
        self.style.map('TCombobox',
                       fieldbackground=[('readonly', 'white'),
                                        ('readonly', 'focus', 'white')],
                       background=[("disabled", "active", "readonly", bgc),
                                   ("!disabled", "active", "readonly", bga)],
                       foreground=[('readonly', '!disabled', fgc),
                                   ('readonly', '!disabled', 'focus', fgc),
                                   ('readonly', 'disabled', 'gray40'),
                                   ('readonly', 'disabled', 'focus', 'gray40')
                                   ],
                       arrowcolor=[("disabled", "gray40")])
        self.style.configure('menu.TCombobox',
                             foreground=fgc,
                             background=bgc,
                             fieldbackground=bgc)
        self.style.map('menu.TCombobox',
                       fieldbackground=[('readonly', bgc),
                                        ('readonly', 'focus', bgc)],
                       background=[("disabled", "active", "readonly", bgc),
                                   ("!disabled", "active", "readonly", bga)],
                       foreground=[('readonly', '!disabled', fgc),
                                   ('readonly', '!disabled', 'focus', fgc),
                                   ('readonly', 'disabled', 'gray40'),
                                   ('readonly', 'disabled', 'focus', 'gray40')
                                   ],
                       arrowcolor=[("disabled", "gray40")])
        self.style.map('DateEntry', arrowcolor=[("disabled", "gray40")])
        self.style.configure('cal.TFrame', background='#424242')
        self.style.configure('month.TLabel',
                             background='#424242',
                             foreground='white')
        self.style.configure('R.TButton',
                             background='#424242',
                             arrowcolor='white',
                             bordercolor='#424242',
                             lightcolor='#424242',
                             darkcolor='#424242')
        self.style.configure('L.TButton',
                             background='#424242',
                             arrowcolor='white',
                             bordercolor='#424242',
                             lightcolor='#424242',
                             darkcolor='#424242')
        active_bg = self.style.lookup('TEntry', 'selectbackground',
                                      ('focus', ))
        self.style.map('R.TButton',
                       background=[('active', active_bg)],
                       bordercolor=[('active', active_bg)],
                       darkcolor=[('active', active_bg)],
                       lightcolor=[('active', active_bg)])
        self.style.map('L.TButton',
                       background=[('active', active_bg)],
                       bordercolor=[('active', active_bg)],
                       darkcolor=[('active', active_bg)],
                       lightcolor=[('active', active_bg)])
        self.style.configure('txt.TFrame', background='white')
        self.style.layout('down.TButton', [('down.TButton.downarrow', {
            'side': 'right',
            'sticky': 'ns'
        })])
        self.style.map('TRadiobutton',
                       indicatorforeground=[('disabled', 'gray40')])
        self.style.map('TCheckbutton',
                       indicatorforeground=[('disabled', 'gray40')],
                       indicatorbackground=[
                           ('pressed', '#dcdad5'),
                           ('!disabled', 'alternate', 'white'),
                           ('disabled', 'alternate', '#a0a0a0'),
                           ('disabled', '#dcdad5')
                       ])
        self.style.map('down.TButton', arrowcolor=[("disabled", "gray40")])

        self.style.map('TMenubutton',
                       arrowcolor=[('disabled',
                                    self.style.lookup('TMenubutton',
                                                      'foreground',
                                                      ['disabled']))])
        bg = self.style.lookup('TFrame', 'background', default='#ececec')
        self.configure(bg=bg)
        self.option_add('*Toplevel.background', bg)
        self.option_add('*Menu.background', bg)
        self.option_add('*Menu.tearOff', False)
        # toggle text
        self._open_image = PhotoImage(name='img_opened',
                                      file=IM_OPENED,
                                      master=self)
        self._closed_image = PhotoImage(name='img_closed',
                                        file=IM_CLOSED,
                                        master=self)
        self._open_image_sel = PhotoImage(name='img_opened_sel',
                                          file=IM_OPENED_SEL,
                                          master=self)
        self._closed_image_sel = PhotoImage(name='img_closed_sel',
                                            file=IM_CLOSED_SEL,
                                            master=self)
        self.style.element_create(
            "toggle",
            "image",
            "img_closed", ("selected", "!disabled", "img_opened"),
            ("active", "!selected", "!disabled", "img_closed_sel"),
            ("active", "selected", "!disabled", "img_opened_sel"),
            border=2,
            sticky='')
        self.style.map('Toggle', background=[])
        self.style.layout('Toggle', [('Toggle.border', {
            'children': [('Toggle.padding', {
                'children': [('Toggle.toggle', {
                    'sticky': 'nswe'
                })],
                'sticky': 'nswe'
            })],
            'sticky':
            'nswe'
        })])
        # toggle sound
        self._im_sound = PhotoImage(master=self, file=IM_SOUND)
        self._im_mute = PhotoImage(master=self, file=IM_MUTE)
        self._im_sound_dis = PhotoImage(master=self, file=IM_SOUND_DIS)
        self._im_mute_dis = PhotoImage(master=self, file=IM_MUTE_DIS)
        self.style.element_create(
            'mute',
            'image',
            self._im_sound, ('selected', '!disabled', self._im_mute),
            ('selected', 'disabled', self._im_mute_dis),
            ('!selected', 'disabled', self._im_sound_dis),
            border=2,
            sticky='')
        self.style.layout('Mute', [('Mute.border', {
            'children': [('Mute.padding', {
                'children': [('Mute.mute', {
                    'sticky': 'nswe'
                })],
                'sticky': 'nswe'
            })],
            'sticky':
            'nswe'
        })])
        self.style.configure('Mute', relief='raised')
        # widget scrollbar
        self._im_trough = {}
        self._im_slider_vert = {}
        self._im_slider_vert_prelight = {}
        self._im_slider_vert_active = {}
        self._slider_alpha = Image.open(IM_SCROLL_ALPHA)
        for widget in ['Events', 'Tasks']:
            bg = CONFIG.get(widget, 'background', fallback='gray10')
            fg = CONFIG.get(widget, 'foreground')

            widget_bg = self.winfo_rgb(bg)
            widget_fg = tuple(
                round(c * 255 / 65535) for c in self.winfo_rgb(fg))
            active_bg = active_color(*widget_bg)
            active_bg2 = active_color(*active_color(*widget_bg, 'RGB'))

            slider_vert = Image.new('RGBA', (13, 28), active_bg)
            slider_vert_active = Image.new('RGBA', (13, 28), widget_fg)
            slider_vert_prelight = Image.new('RGBA', (13, 28), active_bg2)

            self._im_trough[widget] = tkPhotoImage(width=15,
                                                   height=15,
                                                   master=self)
            self._im_trough[widget].put(" ".join(
                ["{" + " ".join([bg] * 15) + "}"] * 15))
            self._im_slider_vert_active[widget] = PhotoImage(
                slider_vert_active, master=self)
            self._im_slider_vert[widget] = PhotoImage(slider_vert, master=self)
            self._im_slider_vert_prelight[widget] = PhotoImage(
                slider_vert_prelight, master=self)
            self.style.element_create('%s.Vertical.Scrollbar.trough' % widget,
                                      'image', self._im_trough[widget])
            self.style.element_create(
                '%s.Vertical.Scrollbar.thumb' % widget,
                'image',
                self._im_slider_vert[widget],
                ('pressed', '!disabled', self._im_slider_vert_active[widget]),
                ('active', '!disabled', self._im_slider_vert_prelight[widget]),
                border=6,
                sticky='ns')
            self.style.layout(
                '%s.Vertical.TScrollbar' % widget,
                [('%s.Vertical.Scrollbar.trough' % widget, {
                    'children': [('%s.Vertical.Scrollbar.thumb' % widget, {
                        'expand': '1'
                    })],
                    'sticky':
                    'ns'
                })])
        # --- tree
        columns = {
            _('Summary'): ({
                'stretch': True,
                'width': 300
            }, lambda: self._sort_by_desc(_('Summary'), False)),
            _('Place'): ({
                'stretch': True,
                'width': 200
            }, lambda: self._sort_by_desc(_('Place'), False)),
            _('Start'): ({
                'stretch': False,
                'width': 150
            }, lambda: self._sort_by_date(_('Start'), False)),
            _('End'): ({
                'stretch': False,
                'width': 150
            }, lambda: self._sort_by_date(_("End"), False)),
            _('Category'): ({
                'stretch': False,
                'width': 100
            }, lambda: self._sort_by_desc(_('Category'), False))
        }
        self.tree = Treeview(self, show="headings", columns=list(columns))
        for label, (col_prop, cmd) in columns.items():
            self.tree.column(label, **col_prop)
            self.tree.heading(label, text=label, anchor="w", command=cmd)
        self.tree.tag_configure('0', background='#ececec')
        self.tree.tag_configure('1', background='white')
        self.tree.tag_configure('outdated', foreground='red')

        scroll = AutoScrollbar(self,
                               orient='vertical',
                               command=self.tree.yview)
        self.tree.configure(yscrollcommand=scroll.set)

        # --- toolbar
        toolbar = Frame(self)
        self.img_plus = PhotoImage(master=self, file=IM_ADD)
        Button(toolbar, image=self.img_plus, padding=1,
               command=self.add).pack(side="left", padx=4)
        Label(toolbar, text=_("Filter by")).pack(side="left", padx=4)
        # --- TODO: add filter by start date (after date)
        self.filter_col = Combobox(
            toolbar,
            state="readonly",
            # values=("",) + self.tree.cget('columns')[1:],
            values=("", _("Category")),
            exportselection=False)
        self.filter_col.pack(side="left", padx=4)
        self.filter_val = Combobox(toolbar,
                                   state="readonly",
                                   exportselection=False)
        self.filter_val.pack(side="left", padx=4)
        Button(toolbar,
               text=_('Delete All Outdated'),
               padding=1,
               command=self.delete_outdated_events).pack(side="right", padx=4)

        # --- grid
        toolbar.grid(row=0, columnspan=2, sticky='we', pady=4)
        self.tree.grid(row=1, column=0, sticky='eswn')
        scroll.grid(row=1, column=1, sticky='ns')

        # --- restore data
        data = {}
        self.events = {}
        self.nb = 0
        try:
            with open(DATA_PATH, 'rb') as file:
                dp = Unpickler(file)
                data = dp.load()
        except Exception:
            l = [
                f for f in os.listdir(os.path.dirname(BACKUP_PATH))
                if f.startswith('data.backup')
            ]
            if l:
                l.sort(key=lambda x: int(x[11:]))
                shutil.copy(os.path.join(os.path.dirname(BACKUP_PATH), l[-1]),
                            DATA_PATH)
                with open(DATA_PATH, 'rb') as file:
                    dp = Unpickler(file)
                    data = dp.load()
        self.nb = len(data)
        backup()
        now = datetime.now()
        for i, prop in enumerate(data):
            iid = str(i)
            self.events[iid] = Event(self.scheduler, iid=iid, **prop)
            self.tree.insert('',
                             'end',
                             iid,
                             values=self.events[str(i)].values())
            tags = [str(self.tree.index(iid) % 2)]
            self.tree.item(iid, tags=tags)
            if not prop['Repeat']:
                for rid, d in list(prop['Reminders'].items()):
                    if d < now:
                        del self.events[iid]['Reminders'][rid]
        self.after_id = self.after(15 * 60 * 1000, self.check_outdated)

        # --- bindings
        self.bind_class("TCombobox",
                        "<<ComboboxSelected>>",
                        self.clear_selection,
                        add=True)
        self.bind_class("TCombobox", "<Control-a>", self.select_all)
        self.bind_class("TEntry", "<Control-a>", self.select_all)
        self.tree.bind('<3>', self._post_menu)
        self.tree.bind('<1>', self._select)
        self.tree.bind('<Double-1>', self._edit_on_click)
        self.menu.bind('<FocusOut>', lambda e: self.menu.unpost())
        self.filter_col.bind("<<ComboboxSelected>>", self.update_filter_val)
        self.filter_val.bind("<<ComboboxSelected>>", self.apply_filter)

        # --- widgets
        self.widgets = {}
        prop = {
            op: CONFIG.get('Calendar', op)
            for op in CONFIG.options('Calendar')
        }
        self.widgets['Calendar'] = CalendarWidget(self,
                                                  locale=CONFIG.get(
                                                      'General', 'locale'),
                                                  **prop)
        self.widgets['Events'] = EventWidget(self)
        self.widgets['Tasks'] = TaskWidget(self)
        self.widgets['Timer'] = Timer(self)
        self.widgets['Pomodoro'] = Pomodoro(self)

        self._setup_style()

        for item, widget in self.widgets.items():
            self.menu_widgets.add_checkbutton(
                label=_(item),
                command=lambda i=item: self.display_hide_widget(i))
            self.menu_widgets.set_item_value(_(item), widget.variable.get())
            add_trace(widget.variable,
                      'write',
                      lambda *args, i=item: self._menu_widgets_trace(i))

        self.icon.loop(self)
        self.tk.eval("""
apply {name {
    set newmap {}
    foreach {opt lst} [ttk::style map $name] {
        if {($opt eq "-foreground") || ($opt eq "-background")} {
            set newlst {}
            foreach {st val} $lst {
                if {($st eq "disabled") || ($st eq "selected")} {
                    lappend newlst $st $val
                }
            }
            if {$newlst ne {}} {
                lappend newmap $opt $newlst
            }
        } else {
            lappend newmap $opt $lst
        }
    }
    ttk::style map $name {*}$newmap
}} Treeview
        """)

        # react to scheduler --update-date in command line
        signal.signal(signal.SIGUSR1, self.update_date)

        # update selected date in calendar and event list every day
        self.scheduler.add_job(self.update_date,
                               CronTrigger(hour=0, minute=0, second=1),
                               jobstore='memo')

        self.scheduler.start()

    def _setup_style(self):
        # scrollbars
        for widget in ['Events', 'Tasks']:
            bg = CONFIG.get(widget, 'background', fallback='gray10')
            fg = CONFIG.get(widget, 'foreground', fallback='white')

            widget_bg = self.winfo_rgb(bg)
            widget_fg = tuple(
                round(c * 255 / 65535) for c in self.winfo_rgb(fg))
            active_bg = active_color(*widget_bg)
            active_bg2 = active_color(*active_color(*widget_bg, 'RGB'))

            slider_vert = Image.new('RGBA', (13, 28), active_bg)
            slider_vert.putalpha(self._slider_alpha)
            slider_vert_active = Image.new('RGBA', (13, 28), widget_fg)
            slider_vert_active.putalpha(self._slider_alpha)
            slider_vert_prelight = Image.new('RGBA', (13, 28), active_bg2)
            slider_vert_prelight.putalpha(self._slider_alpha)

            self._im_trough[widget].put(" ".join(
                ["{" + " ".join([bg] * 15) + "}"] * 15))
            self._im_slider_vert_active[widget].paste(slider_vert_active)
            self._im_slider_vert[widget].paste(slider_vert)
            self._im_slider_vert_prelight[widget].paste(slider_vert_prelight)

        for widget in self.widgets.values():
            widget.update_style()

    def report_callback_exception(self, *args):
        err = ''.join(traceback.format_exception(*args))
        logging.error(err)
        showerror('Exception', str(args[1]), err, parent=self)

    def save(self):
        logging.info('Save event database')
        data = [ev.to_dict() for ev in self.events.values()]
        with open(DATA_PATH, 'wb') as file:
            pick = Pickler(file)
            pick.dump(data)

    def update_date(self, *args):
        """Update Calendar's selected day and Events' list."""
        self.widgets['Calendar'].update_date()
        self.widgets['Events'].display_evts()
        self.update_idletasks()

    # --- bindings
    def _select(self, event):
        if not self.tree.identify_row(event.y):
            self.tree.selection_remove(*self.tree.selection())

    def _edit_on_click(self, event):
        sel = self.tree.selection()
        if sel:
            sel = sel[0]
            self.edit(sel)

    # --- class bindings
    @staticmethod
    def clear_selection(event):
        combo = event.widget
        combo.selection_clear()

    @staticmethod
    def select_all(event):
        event.widget.selection_range(0, "end")
        return "break"

    # --- show / hide
    def _menu_widgets_trace(self, item):
        self.menu_widgets.set_item_value(_(item),
                                         self.widgets[item].variable.get())

    def display_hide_widget(self, item):
        value = self.menu_widgets.get_item_value(_(item))
        if value:
            self.widgets[item].show()
        else:
            self.widgets[item].hide()

    def hide(self):
        self._visible.set(False)
        self.withdraw()
        self.save()

    def show(self):
        self._visible.set(True)
        self.deiconify()

    def _visibility_trace(self, *args):
        self.icon.menu.set_item_value(_('Manager'), self._visible.get())

    def display_hide(self, toggle=False):
        value = self.icon.menu.get_item_value(_('Manager'))
        if toggle:
            value = not value
            self.icon.menu.set_item_value(_('Manager'), value)
        self._visible.set(value)
        if not value:
            self.withdraw()
            self.save()
        else:
            self.deiconify()

    # --- event management
    def event_add(self, event):
        self.nb += 1
        iid = str(self.nb)
        self.events[iid] = event
        self.tree.insert('', 'end', iid, values=event.values())
        self.tree.item(iid, tags=str(self.tree.index(iid) % 2))
        self.widgets['Calendar'].add_event(event)
        self.widgets['Events'].display_evts()
        self.widgets['Tasks'].display_tasks()
        self.save()

    def event_configure(self, iid):
        self.tree.item(iid, values=self.events[iid].values())
        self.widgets['Calendar'].add_event(self.events[iid])
        self.widgets['Events'].display_evts()
        self.widgets['Tasks'].display_tasks()
        self.save()

    def add(self, date=None):
        iid = str(self.nb + 1)
        if date is not None:
            event = Event(self.scheduler, iid=iid, Start=date)
        else:
            event = Event(self.scheduler, iid=iid)
        Form(self, event, new=True)

    def delete(self, iid):
        index = self.tree.index(iid)
        self.tree.delete(iid)
        for k, item in enumerate(self.tree.get_children('')[index:]):
            tags = [
                t for t in self.tree.item(item, 'tags') if t not in ['1', '0']
            ]
            tags.append(str((index + k) % 2))
            self.tree.item(item, tags=tags)

        self.events[iid].reminder_remove_all()
        self.widgets['Calendar'].remove_event(self.events[iid])
        del (self.events[iid])
        self.widgets['Events'].display_evts()
        self.widgets['Tasks'].display_tasks()
        self.save()

    def edit(self, iid):
        self.widgets['Calendar'].remove_event(self.events[iid])
        Form(self, self.events[iid])

    def check_outdated(self):
        """Check for outdated events every 15 min."""
        now = datetime.now()
        for iid, event in self.events.items():
            if not event['Repeat'] and event['Start'] < now:
                tags = list(self.tree.item(iid, 'tags'))
                if 'outdated' not in tags:
                    tags.append('outdated')
                self.tree.item(iid, tags=tags)
        self.after_id = self.after(15 * 60 * 1000, self.check_outdated)

    def delete_outdated_events(self):
        now = datetime.now()
        outdated = []
        for iid, prop in self.events.items():
            if prop['End'] < now:
                if not prop['Repeat']:
                    outdated.append(iid)
                elif prop['Repeat']['Limit'] != 'always':
                    end = prop['End']
                    enddate = datetime.fromordinal(
                        prop['Repeat']['EndDate'].toordinal())
                    enddate.replace(hour=end.hour, minute=end.minute)
                    if enddate < now:
                        outdated.append(iid)
        for item in outdated:
            self.delete(item)
        logging.info('Deleted outdated events')

    def refresh_reminders(self):
        """
        Reschedule all reminders.

        Required when APScheduler is updated.
        """
        for event in self.events.values():
            reminders = [date for date in event['Reminders'].values()]
            event.reminder_remove_all()
            for date in reminders:
                event.reminder_add(date)
        logging.info('Refreshed reminders')

    # --- sorting
    def _move_item(self, item, index):
        self.tree.move(item, "", index)
        tags = [t for t in self.tree.item(item, 'tags') if t not in ['1', '0']]
        tags.append(str(index % 2))
        self.tree.item(item, tags=tags)

    @staticmethod
    def to_datetime(date):
        date_format = get_date_format("short", CONFIG.get("General",
                                                          "locale")).pattern
        dayfirst = date_format.startswith("d")
        yearfirst = date_format.startswith("y")
        return parse(date, dayfirst=dayfirst, yearfirst=yearfirst)

    def _sort_by_date(self, col, reverse):
        l = [(self.to_datetime(self.tree.set(k, col)), k)
             for k in self.tree.get_children('')]
        l.sort(reverse=reverse)

        # rearrange items in sorted positions
        for index, (val, k) in enumerate(l):
            self._move_item(k, index)

        # reverse sort next time
        self.tree.heading(col,
                          command=lambda: self._sort_by_date(col, not reverse))

    def _sort_by_desc(self, col, reverse):
        l = [(self.tree.set(k, col), k) for k in self.tree.get_children('')]
        l.sort(reverse=reverse, key=lambda x: x[0].lower())

        # rearrange items in sorted positions
        for index, (val, k) in enumerate(l):
            self._move_item(k, index)

        # reverse sort next time
        self.tree.heading(col,
                          command=lambda: self._sort_by_desc(col, not reverse))

    # --- filter
    def update_filter_val(self, event):
        col = self.filter_col.get()
        self.filter_val.set("")
        if col:
            l = set()
            for k in self.events:
                l.add(self.tree.set(k, col))

            self.filter_val.configure(values=tuple(l))
        else:
            self.filter_val.configure(values=[])
            self.apply_filter(event)

    def apply_filter(self, event):
        col = self.filter_col.get()
        val = self.filter_val.get()
        items = list(self.events.keys())
        if not col:
            for item in items:
                self._move_item(item, int(item))
        else:
            i = 0
            for item in items:
                if self.tree.set(item, col) == val:
                    self._move_item(item, i)
                    i += 1
                else:
                    self.tree.detach(item)

    # --- manager's menu
    def _post_menu(self, event):
        self.right_click_iid = self.tree.identify_row(event.y)
        self.tree.selection_remove(*self.tree.selection())
        self.tree.selection_add(self.right_click_iid)
        if self.right_click_iid:
            try:
                self.menu.delete(_('Progress'))
            except TclError:
                pass
            state = self.events[self.right_click_iid]['Task']
            if state:
                self._task_var.set(state)
                if '%' in state:
                    self._img_dot = PhotoImage(master=self, file=IM_DOT)
                else:
                    self._img_dot = tkPhotoImage(master=self)
                self.menu_task.entryconfigure(1, image=self._img_dot)
                self.menu.insert_cascade(0,
                                         menu=self.menu_task,
                                         label=_('Progress'))
            self.menu.tk_popup(event.x_root, event.y_root)

    def _delete_menu(self):
        if self.right_click_iid:
            self.delete(self.right_click_iid)

    def _edit_menu(self):
        if self.right_click_iid:
            self.edit(self.right_click_iid)

    def _set_progress(self):
        if self.right_click_iid:
            self.events[self.right_click_iid]['Task'] = self._task_var.get()
            self.widgets['Tasks'].display_tasks()
            if '%' in self._task_var.get():
                self._img_dot = PhotoImage(master=self, file=IM_DOT)
            else:
                self._img_dot = tkPhotoImage(master=self)
            self.menu_task.entryconfigure(1, image=self._img_dot)

    # --- icon menu
    def exit(self):
        self.save()
        rep = self.widgets['Pomodoro'].stop(self.widgets['Pomodoro'].on)
        if not rep:
            return
        self.menu_eyes.quit()
        self.after_cancel(self.after_id)
        try:
            self.scheduler.shutdown()
        except SchedulerNotRunningError:
            pass
        self.destroy()

    def settings(self):
        splash_supp = CONFIG.get('General', 'splash_supported', fallback=True)
        dialog = Settings(self)
        self.wait_window(dialog)
        self._setup_style()
        if splash_supp != CONFIG.get('General', 'splash_supported'):
            for widget in self.widgets.values():
                widget.update_position()

    # --- week schedule
    def get_next_week_events(self):
        """Return events scheduled for the next 7 days """
        locale = CONFIG.get("General", "locale")
        next_ev = {}
        today = datetime.now().date()
        for d in range(7):
            day = today + timedelta(days=d)
            evts = self.widgets['Calendar'].get_events(day)
            if evts:
                evts = [self.events[iid] for iid in evts]
                evts.sort(key=lambda ev: ev.get_start_time())
                desc = []
                for ev in evts:
                    if ev["WholeDay"]:
                        date = ""
                    else:
                        date = "%s - %s " % (
                            format_time(ev['Start'], locale=locale),
                            format_time(ev['End'], locale=locale))
                    place = "(%s)" % ev['Place']
                    if place == "()":
                        place = ""
                    desc.append(("%s%s %s\n" % (date, ev['Summary'], place),
                                 ev['Description']))
                next_ev[day.strftime('%A')] = desc
        return next_ev

    # --- tasks
    def get_tasks(self):
        # TODO: find events with repetition in the week
        # TODO: better handling of events on several days
        tasks = []
        for event in self.events.values():
            if event['Task']:
                tasks.append(event)
        return tasks
Example #15
0
class ListWidget:
    def __init__(self, command=None):
        self.topic_list = None
        outsideFrame = Frame()
        outsideFrame.config(padx=10, pady=10)
        outsideFrame.grid(row=1, column=0, sticky="wn")

        self.frame = LabelFrame(outsideFrame, text="Topics")
        self.frame.config(font=("Arial", 14), padx=10, pady=10)
        self.frame.grid(row=0, column=0)
        self._command = command

        self.topic_filter_input = Entry(self.frame, width=33)
        self.topic_filter_input.grid(row=0, column=0, pady=10)
        self.topic_filter_input.bind("<KeyRelease>", self.filter_topic)

        treeFrame = Frame(self.frame)
        treeFrame.grid(row=1, column=0)
        self.tree = Treeview(treeFrame, style="Custom.Treeview")
        self.tree.heading('#0', text='Topic')
        self.tree.pack()
        self.tree.bind("<ButtonRelease-1>", self.OnClick)
        self.tree.tag_configure('odd', background='#f9f9f9')
        self.tree.tag_configure('even', background='#DFDFDF')

        scroll_bar = Scrollbar(self.frame,
                               orient="vertical",
                               command=self.tree.yview)
        scroll_bar.grid(row=1, column=1, sticky='nsew')
        self.tree.configure(yscrollcommand=scroll_bar.set)

    def filter_topic(self, *args):
        inputed_topic = self.topic_filter_input.get()
        list = filter(lambda k: inputed_topic.lower() in k.lower(),
                      self.topic_list)
        self.prepare_list(list)

    def OnClick(self, event):
        item = self.tree.identify('item', event.x, event.y)
        if item == '':
            return
        selectedItem = self.tree.item(item, "text")
        self._command(selectedItem)

    def prepare_list(self, sorted_topic_list):
        self.clean()
        for topic in sorted_topic_list:
            self.insert(topic)

    def insert(self, line):
        type = 'even'
        if (len(self.tree.get_children()) % 2 == 1):
            type = 'odd'
        self.tree.insert("", "end", text=line, tags=(type, ))

    def clean(self):
        for i in self.tree.get_children():
            self.tree.delete(i)

    def destroy(self):
        self.frame.destroy()
Example #16
0
def digiclock(w):
	pane = tkinter.tix.PanedWindow(w, orientation='vertical')
	pane.pack(side=tkinter.tix.TOP, expand=1, fill=BOTH)
	f1 = pane.add('time',size=190)
	f2 = pane.add('options')
	
	f2pane = tkinter.tix.PanedWindow(f2, orientation='horizontal')
	f2pane.pack(side=tkinter.tix.TOP, expand=1, fill=BOTH)
	f2f1 = f2pane.add('alarm',size=150)
	f2f2 = f2pane.add('event')
	
	global al_status,al_time,m
	m='am'
	ts_status=ON
	al_status=OFF
	al_time=str()
	colour=['orange','red','violet','pink','blue','grey']
	def ConfigEvents():
		now=ctime().split()
		year=int(now[4])
		mon=now[1].lower()
		date=int(now[2])
		notes=CalLookUp( mon )
		for each_item in Entries.get_children():
			Entries.delete(each_item)
		ordered=[]
		for memo in notes: 
			if(int(memo) >= date):
				ordered.append(memo)
		ordered.sort()
		for memo in ordered:
			for note in notes[memo]:
				Entries.insert('', 'end', values=( memo, note[0], note[1]) )
	def displayTime(st,ts):
		global al_time,m
		sleep(3)
		day={'Mon'	:	'Monday'	,
			'Tue'  	:	'Tuesday'	,
			'Wed'	:	'Wednesday',
			'Thu'	:	'Thursday',
			'Fri'	:	'Friday'	,
			'Sat'	:	'Saturday',
			'Sun'	:	'Sunday'	}
		while(st):
			ct=ctime().split(' ')
			m='AM'
			if int(ct[3].split(':')[0])>11 : 
				m='PM'
				if int(ct[3].split(':')[0])>12 :	
					ct[3]=str( int( ct[3][:2] )-12 ) + ct[3][2:]
			if (ct[3].split(':')[0] == '00' ):	
				ct[3]='12' + ct[3][2:]
				ConfigEvents()
			#~ if (not int(ct[3].split(':')[2])%10):	ts.config( bg=colour[ int( int( ct[3].split(':')[2] )/10) ] )
			mhs=ct[3].split(':')
			mode=	{
					'time&date'	:'%s-%s-%s\n%s\n%0.2d:%0.2d:%0.2d %s'%(ct[1],ct[2],ct[4],day[ct[0]],int(mhs[0]),int(mhs[1]),int(mhs[2]),m),
					'time'		:'%0.2d:%0.2d:%0.2d %s'%(int(mhs[0]),int(mhs[1]),int(mhs[2]),m)
					}
			text	=mode['time&date']
			#~ print(ct)
			ts.config(text=text)
			#~ print(al_time,mode['time'],al_time==mode['time'])
			if(al_time==mode['time']):
				set.config( text='Stop' )
				cal.config( text='Expired @ ' + al_time[:-2] )
				thread.start_new_thread(lambda snd='ringout', repeat=ON :play( snd, repeat ) ,() )
			sleep(1)
	def sett():
		global al_status,sound_continueous,al_time
		if(al_status):
			al_status = OFF
			sound_continueous = OFF
			al_time = ''
			cal.config( text='No Alarm' )
			set.config( text='Set' )
		else:
			al_status = ON
			al_time = at.entry.get()+' '+ampm.entry.get()
			cal.config( text='Set @ ' + al_time )
			set.config( text='Remove' )
	bg='orange'
	#~ time frame
	tf=Frame( f1, bg='black' )
	ts=Label(		tf
				,text="rajiv.m1991\n@\ngmail.com"
				,font='times 40'
				,bg='violet'
				,width=11
				,fg='white')
	tf.pack(fill=BOTH)
	ts.pack(fill=X)
	#~ alarm frame
	af=Frame(f2f1,bg=bg)
	al=Label(	af
			,text="$ Alarm $"
			,font='times'
			,fg='white'
			,bg='black')
	at=LabelEntry( af, label='HH:MM:SS', bg=bg )
	at.label.config( fg='white', bg=bg )
	at.entry.config( width=13, borderwidth=0 )
	at.entry.insert( 0, '00:00:00' )
	ampm=LabelEntry( af, label='AM / PM ', bg=bg )
	ampm.entry.config( borderwidth=0 )
	ampm.label.config( fg='white', bg=bg)
	if( int( ctime().split(' ')[3].split(':')[0]) > 11 ):		ampm.entry.insert( 0,'PM' )
	else:	ampm.entry.insert( 0, 'AM' )
	set=Button(af
			,text='Set'
			,command=sett
			,fg='brown')
	ast=Label(	af
			,text='Alarm status:'
			,fg='white'
			,bg=bg
			,anchor='sw')
	cal=Label(	af
			,text='No Alarm'
			,fg='white'
			,bg='black'
			,anchor='sw')
	af.pack(fill=BOTH)
	al.pack(fill=X)
	at.pack(fill=X,padx=5,pady=5)
	ampm.pack(fill=X,padx=5,pady=5)
	set.pack()
	ast.pack(fill=X)
	cal.pack(fill=X)
	#~ options
	L=Label(f2f2,text="Upcoming Events")
	L.pack(fill=X)
	tree_columns = ("Dt", "Note", "Category")
	Entries=Treeview(	f2f2,
					columns=tree_columns,
					show="headings",
					height=5)
	vsb = Scrollbar(f2f2,orient="vertical", command=Entries.yview)
	Entries.configure(yscrollcommand=vsb.set)
	for col in tree_columns:
		Entries.heading(col, text=col.title())
	Entries.column(tree_columns[0],width=20)
	Entries.column(tree_columns[1],width=75)
	Entries.column(tree_columns[2],width=75)
	vsb.pack(side=RIGHT,fill=Y)
	Entries.pack(fill=BOTH)
	#~ start clock
	ConfigEvents()
	thread.start_new_thread(lambda st=ts_status ,ts=ts : displayTime(st,ts),())
	print('Digital Clock Successfully built')
Example #17
0
def Tree(fr0,csv_file,out_var,csv_delimiter=','):
    st1 = Style()
    st1.theme_use('default')

    st1.map('Treeview', foreground=fixed_map(st1,'foreground'),
            background=fixed_map(st1,'background'))

    fact = font.Font(font="TkDefaultFont").metrics('linespace')
    st1.configure('font.Treeview', rowheight=fact,
                  font=font.nametofont("TkDefaultFont"))
    # determine Heading font based on TkDefaultFont
    def_font = font.nametofont('TkDefaultFont')
    font_family = def_font.actual()['family']
    font_size = def_font.actual()['size'] + 1
    st1.configure('font.Treeview.Heading', font=(font_family,font_size,'bold'))

    # function to enable selection
    def select_item(evt):
        curItem = tree.focus()
        lvar.set(tree.item(curItem)['values'])
        out_var.set(tree.item(curItem)['values'])

    def sort_by(tree, col, descending):
        # When a column is clicked on sort tree contents .
        # grab values to sort
        data = [(tree.set(child, col), child) for child in tree.get_children('')]

        # reorder data
        data.sort(reverse=descending)
        for indx, item in enumerate(data):
            tree.move(item[1], '', indx)

        # switch the heading so that it will sort in the opposite direction
        tree.heading(col, command=lambda col=col: sort_by(tree, col, int(not descending)))

        # reconfigure tags after ordering
        list_of_items = tree.get_children('')
        for i in range(len(list_of_items)):
            tree.tag_configure(list_of_items[i], background=backg[i%2])

    tree_data = []

    backg = ["white",'#f0f0ff']

    with open(csv_file, newline='', encoding='utf-8-sig') as csvfile:
        treeCsv = csv.reader(csvfile, delimiter=csv_delimiter)

        for ix, row in enumerate(treeCsv):
            if ix == 0:
                tree_columns = row
            else:
                tree_data.append(row)

    # create Treeview widget
    tree = Treeview(fr0, column=tree_columns, show='headings',style='font.Treeview')
    tree.grid(column=0, row=0, sticky='nsew')
    tree.bind("<<TreeviewSelect>>", select_item)

    vsb = Scrollbar(fr0,orient="vertical", command=tree.yview)
    vsb.grid(column=1, row=0, sticky='ns')
    hsb = Scrollbar(fr0,orient="horizontal", command=tree.xview)
    hsb.grid(column=0, row=1,  sticky='ew')

    tree.configure(xscrollcommand=hsb.set,yscrollcommand=vsb.set)
    fr0.grid_columnconfigure(0, weight=1)
    fr0.grid_rowconfigure(0, weight=1)

    # insert header, data and tag configuration
    for ix,col in enumerate(tree_columns):
        tree.heading(col, text=col.title(),
            command=lambda c=col: sort_by(tree, c, 0))
        #tree.column(col,stretch=True)
        #tree.column(col,width=font.nametofont('TkHeadingFont').measure(col.title()),
                #stretch=False)
        tree.column(col,width=font.Font(family=font_family,size=font_size, weight="bold").measure(col.title()) + 10,
                stretch=False)
        #print(tree.column(col))

    # insert data row by row, then measure each items' width
    for ix, item in enumerate(tree_data):
        item_ID = tree.insert('', 'end', values=item)
        tree.item(item_ID, tags=item_ID)
        tree.tag_configure(item_ID, background=backg[ix%2])

        for indx, val in enumerate(item):
            #ilen = font.Font(family="Segoe UI", size=10, weight="normal").measure(val)
            ilen = font.nametofont('TkDefaultFont').measure(val)
            if tree.column(tree_columns[indx], width=None) < ilen +10:
                tree.column(tree_columns[indx], width=ilen + 10)
            # you should see the widths adjust
            #print('col',tree.column(tree_columns[indx]),ilen)

    # display selection
    lvar = StringVar()
    lbl = Label(fr0, textvariable=lvar, text="Ready")
    lbl.grid(column=0, row=2, sticky='nsew')
Example #18
0
def calender(w):
    global year, mon
    date_bg = "white"
    date_fg = "black"
    date_fgb = "blue"
    date_bgt = "white"
    date_fgt = "red"
    day_bg = "orange"
    day_fg = "white"
    mon_bg = "violet"
    mon_fg = "white"
    Magic_Sequence = "2345012356013456123460124560"
    month = {
        "jan": 0,
        "feb": 8,
        "mar": 25,
        "apr": 5,
        "may": 1,
        "jun": 9,
        "jul": 5,
        "aug": 13,
        "sep": 21,
        "oct": 17,
        "nov": 25,
        "dec": 21,
    }
    months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
    day = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]
    # ~ current year and month
    now = ctime().split()
    year = int(now[4])
    mon = now[1].lower()
    date = int(now[2])

    def Cal_config(modify=False):
        global year, mon
        mon_limit = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        now = ctime().split()
        cyear = int(now[4])
        cmon = now[1].lower()
        cdate = int(now[2])
        if modify == "go":
            year, mon = int(y.entry.get()), m.entry.get()
        elif modify:
            if months.index(mon) + modify > 11:
                year, mon = year + 1, "jan"
            elif months.index(mon) + modify < 0:
                year, mon = year - 1, "dec"
            else:
                mon = months[months.index(mon) + modify]
        monl.config(text="%s - %d" % (mon.title(), year))
        if not year % 4:
            mon_limit[1] = 29  # Leap year Check
        year_id = (year + 3) % 28
        Required_Sequence = Magic_Sequence[month[mon] :] + Magic_Sequence[: month[mon]]
        addition_factor = int(Required_Sequence[year_id])
        notes = CalLookUp(mon)
        d = 1
        for i in range(37):
            if i < addition_factor or d > mon_limit[months.index(mon)]:  # blank positions
                datebuttons[i].config(text="", bg=date_bg, activebackground=date_bg)
            else:  # positions with date
                bc, fc = date_bg, date_fg
                bracket = 0
                if year == cyear and mon == cmon and d == cdate:
                    bc, fc, bracket = date_bgt, date_fgt, 1
                if "%0.2d" % (d) in notes:
                    fc = date_fgb
                datebuttons[i].config(
                    text="%s%0.2d%s" % ("(" * bracket, d, ")" * bracket),
                    bg=bc,
                    fg=fc,
                    activebackground="yellow",
                    activeforeground="black",
                )
                d += 1
        for each_item in Entries.get_children():
            Entries.delete(each_item)
        ordered = []
        for memo in notes:
            ordered.append(memo)
        ordered.sort()
        for memo in ordered:
            for note in notes[memo]:
                Entries.insert("", "end", values=(memo, note[0], note[1]))
        print("Cal configured to", mon, year)
        # ~ main calender frame

    pane = tkinter.tix.PanedWindow(w, orientation="vertical")
    pane.pack(side=tkinter.tix.TOP, fill=BOTH)
    f1 = pane.add("top", size=190, expand="0", allowresize=0)
    f2 = pane.add("info", expand="0", allowresize=0)

    f1pane = tkinter.tix.PanedWindow(f1, orientation="horizontal")
    f1pane.pack(side=tkinter.tix.TOP, fill=BOTH)
    f1f1 = f1pane.add("calender", size=200, allowresize=0)
    f1f2 = f1pane.add("options", allowresize=0)

    # ~ month heading
    calhead = Frame(f1f1, bg=date_bg)
    back = Button(
        calhead,
        text="<<<",
        width=5,
        bg=date_bg,
        activebackground="red",
        activeforeground="white",
        borderwidth=0,
        command=lambda modify=-1: Cal_config(modify),
    )
    monl = Label(calhead, width=15, bg=mon_bg, fg=mon_fg)
    next = Button(
        calhead,
        text=">>>",
        width=5,
        bg=date_bg,
        activebackground="red",
        activeforeground="white",
        borderwidth=0,
        command=lambda modify=1: Cal_config(modify),
    )
    back.pack(side=LEFT)
    monl.pack(side=LEFT, padx=10)
    next.pack(side=LEFT)
    calhead.pack(fill=X)
    # ~ day lables
    DayFrame = Frame(f1f1, bg=day_bg)
    daylabels = []
    for i in range(7):
        daylabels.append(Label(DayFrame, text=day[i], width=3, bg=day_bg, fg=day_fg))
        daylabels[i].pack(side=LEFT, padx=2)
    DayFrame.pack(fill=X)
    # ~ date buttons
    datebuttons = []
    dfl = []
    for i in range(6):
        dfl.append(Frame(f1f1, bg=date_bg))
        dfl[i].pack(fill=X)
    j = 0
    for i in range(37):
        datebuttons.append(Button(dfl[j], width=3, borderwidth=0))
        datebuttons[i].pack(side=LEFT, padx=2)
        if not (i + 1) % 7:
            j += 1
        # ~ information frame
    mem = Label(f2, text="Memos :")
    disp_frame = tkinter.Frame(f2)
    tree_columns = ("Date", "Note", "Category")
    Entries = Treeview(disp_frame, columns=tree_columns, show="headings", height=5)
    vsb = Scrollbar(disp_frame, orient="vertical", command=Entries.yview)
    Entries.configure(yscrollcommand=vsb.set)
    for col in tree_columns:
        Entries.heading(col, text=col.title())
    Entries.column("Date", width=50)
    Entries.column("Note", width=150)
    Entries.column("Category", width=100)
    vsb.pack(side=RIGHT, fill=Y)
    Entries.pack(fill=BOTH)
    mem.pack(fill=X)
    disp_frame.pack(fill=BOTH)
    # ~ option frame
    L = Label(f1f2, text="More Options:")
    view = Frame(f1f2)
    y = ComboBox(view, editable=1)
    y.entry.config(width=5)
    y.entry.insert(0, year)
    m = ComboBox(view, editable=1)
    m.entry.config(width=4)
    m.entry.insert(0, mon)
    go = Button(f1f2, text="<<< Go", command=lambda modify="go": Cal_config(modify))
    for i in range(200):
        y.insert(END, "%d" % (i + 1901))
    for i in months:
        m.insert(END, i)
    y.pack(side=LEFT)
    m.pack()
    L.pack(fill=X)
    view.pack(fill=X)
    go.pack(fill=X)
    # ~ first config
    Cal_config()
Example #19
0
class MainWindowUI:

# |   1   |   2   |   3   |   4   |   5   |   6   |   7   |   8   |   9   |  10   |  11   |  12   |
# +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
# |                                     menu bar                                                  |
# +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
# |               |                                     search bar                                |
# |               |          search entry                                                 | button|
# |               +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
# |               |                                       |                                       |
# |               |                                       |                                       |
# |               |                                       |                                       |
# |   treeview    |                                       |                                       |
# |               |              text area 1              |               text area 2             |
# |               |                                       |                                       |
# |               |                                       |                                       |
# |               |                                       |                                       |
# |               |                                       |                                       |
# +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
# |   1   |   2   |   3   |   4   |   5   |   6   |   7   |   8   |   9   |  10   |  11   |  12   |

    # Rows
    fileTreeRow = filePathLabelsRow = 0
    searchTextRow = 1
    uniScrollbarRow = lineNumbersRow = textAreasRow = 2
    horizontalScrollbarRow = 3

    # Columns
    fileTreeCol = 0
    fileTreeScrollbarCol = 1
    leftLineNumbersCol = leftFilePathLabelsCol = 2    # should span at least two columns
    leftTextAreaCol = leftHorizontalScrollbarCol = 3
    uniScrollbarCol = 4
    rightLineNumbersCol = rightFilePathLabelsCol = 5  # should span at least two columns
    rightTextAreaCol = rightHorizontalScrollbarCol = 6

    # Colors
    whiteColor = '#ffffff'
    redColor = '#ffc4c4'
    darkredColor = '#ff8282'
    grayColor = '#dddddd'
    lightGrayColor = '#eeeeee'
    greenColor = '#c9fcd6'
    darkgreenColor = '#50c96e'
    yellowColor = '#f0f58c'
    darkYellowColor = '#ffff00'

    def __init__(self, window):
        self.main_window = window
        self.main_window.grid_rowconfigure(self.filePathLabelsRow, weight=0)
        self.main_window.grid_rowconfigure(self.searchTextRow, weight=0)
        self.main_window.grid_rowconfigure(self.textAreasRow, weight=1)

        self.main_window.grid_columnconfigure(self.fileTreeCol, weight=0)
        self.main_window.grid_columnconfigure(self.fileTreeScrollbarCol, weight=0)
        self.main_window.grid_columnconfigure(self.leftLineNumbersCol, weight=0)
        self.main_window.grid_columnconfigure(self.leftTextAreaCol, weight=1)
        self.main_window.grid_columnconfigure(self.uniScrollbarCol, weight=0)
        self.main_window.grid_columnconfigure(self.rightLineNumbersCol, weight=0)
        self.main_window.grid_columnconfigure(self.rightTextAreaCol, weight=1)
        self.menubar = Menu(self.main_window)
        self.menus = {}
        self.text_area_font = 'TkFixedFont'

    # Center window and set its size
    def center_window(self):
        sw = self.main_window.winfo_screenwidth()
        sh = self.main_window.winfo_screenheight()

        w = 0.7 * sw
        h = 0.7 * sh

        x = (sw - w)/2
        y = (sh - h)/2
        self.main_window.geometry('%dx%d+%d+%d' % (w, h, x, y))
        self.main_window.minsize(int(0.3 * sw), int(0.3 * sh))

    # Menu bar
    def add_menu(self, menuName, commandList):
        self.menus[menuName] = Menu(self.menubar,tearoff=0)
        for c in commandList:
            if 'separator' in c: self.menus[menuName].add_separator()
            else: self.menus[menuName].add_command(label=c['name'], command=c['command'], accelerator=c['accelerator'] if 'accelerator' in c else '')
        self.menubar.add_cascade(label=menuName, menu=self.menus[menuName])
        self.main_window.config(menu=self.menubar)

    # Labels
    def create_file_path_labels(self):
        self.leftFileLabel = Label(self.main_window, anchor='center', width=1000, background=self.lightGrayColor)
        self.leftFileLabel.grid(row=self.filePathLabelsRow, column=self.leftFilePathLabelsCol, columnspan=2)
        self.rightFileLabel = Label(self.main_window, anchor='center', width=1000, background=self.lightGrayColor)
        self.rightFileLabel.grid(row=self.filePathLabelsRow, column=self.rightFilePathLabelsCol, columnspan=2)

    # Search text entnry
    def create_search_text_entry(self, searchButtonCallback):
        self.searchTextDialog = SearchTextDialog(self.main_window, [self.leftFileTextArea, self.rightFileTextArea], searchButtonCallback)
        self.searchTextDialog.grid(row=self.searchTextRow, column=self.leftFilePathLabelsCol, columnspan=5, sticky=EW)

        self.searchTextDialog.grid_remove()

    # File treeview
    def create_file_treeview(self):
        self.fileTreeView = Treeview(self.main_window)
        self.fileTreeYScrollbar = Scrollbar(self.main_window, orient='vertical', command=self.fileTreeView.yview)
        self.fileTreeXScrollbar = Scrollbar(self.main_window, orient='horizontal', command=self.fileTreeView.xview)
        self.fileTreeView.configure(yscroll=self.fileTreeYScrollbar.set, xscroll=self.fileTreeXScrollbar.set)

        self.fileTreeView.grid(row=self.fileTreeRow, column=self.fileTreeCol, sticky=NS, rowspan=3)
        self.fileTreeYScrollbar.grid(row=self.fileTreeRow, column=self.fileTreeScrollbarCol, sticky=NS, rowspan=3)
        self.fileTreeXScrollbar.grid(row=self.horizontalScrollbarRow, column=self.fileTreeCol, sticky=EW)

        self.fileTreeView.tag_configure('red', background=self.redColor)
        self.fileTreeView.tag_configure('green', background=self.greenColor)
        self.fileTreeView.tag_configure('yellow', background=self.yellowColor)

        # hide it until needed
        self.fileTreeView.grid_remove()
        self.fileTreeYScrollbar.grid_remove()
        self.fileTreeXScrollbar.grid_remove()

    # Text areas
    def create_text_areas(self):
        self.leftFileTextArea = Text(self.main_window, padx=5, pady=5, width=1, height=1, bg=self.grayColor)
        self.leftFileTextArea.grid(row=self.textAreasRow, column=self.leftTextAreaCol, sticky=NSEW)
        self.leftFileTextArea.config(font=self.text_area_font)
        self.leftFileTextArea.config(wrap='none')

        self.rightFileTextArea = Text(self.main_window, padx=5, pady=5, width=1, height=1, bg=self.grayColor)
        self.rightFileTextArea.grid(row=self.textAreasRow, column=self.rightTextAreaCol, sticky=NSEW)
        self.rightFileTextArea.config(font=self.text_area_font)
        self.rightFileTextArea.config(wrap='none')

        # configuring highlight tags
        self.leftFileTextArea.tag_configure('red', background=self.redColor)
        self.leftFileTextArea.tag_configure('darkred', background=self.darkredColor)
        self.leftFileTextArea.tag_configure('gray', background=self.grayColor)
        self.leftFileTextArea.tag_configure('search', background=self.darkYellowColor)
        self.rightFileTextArea.tag_configure('green', background=self.greenColor)
        self.rightFileTextArea.tag_configure('darkgreen', background=self.darkgreenColor)
        self.rightFileTextArea.tag_configure('gray', background=self.grayColor)
        self.rightFileTextArea.tag_configure('search', background=self.darkYellowColor)

        # disable the text areas
        self.leftFileTextArea.config(state=DISABLED)
        self.rightFileTextArea.config(state=DISABLED)

    # Line numbers
    def create_line_numbers(self):
        self.leftLinenumbers = Text(self.main_window, width=3, padx=5, pady=5, height=1, bg=self.lightGrayColor)
        self.leftLinenumbers.grid(row=self.lineNumbersRow, column=self.leftLineNumbersCol, sticky=NS)
        self.leftLinenumbers.config(font=self.text_area_font)
        self.leftLinenumbers.tag_configure('line', justify='right')

        self.rightLinenumbers = Text(self.main_window, width=3, padx=5, pady=5, height=1, bg=self.lightGrayColor)
        self.rightLinenumbers.grid(row=self.lineNumbersRow, column=self.rightLineNumbersCol, sticky=NS)
        self.rightLinenumbers.config(font=self.text_area_font)
        self.rightLinenumbers.tag_configure('line', justify='right')

        # disable the line numbers
        self.leftLinenumbers.config(state=DISABLED)
        self.rightLinenumbers.config(state=DISABLED)

    # Scroll bars
    def scrollBoth(self, action, position, type=None):
        self.leftFileTextArea.yview_moveto(position)
        self.rightFileTextArea.yview_moveto(position)
        self.leftLinenumbers.yview_moveto(position)
        self.rightLinenumbers.yview_moveto(position)

    def updateScroll(self, first, last, type=None):
        self.leftFileTextArea.yview_moveto(first)
        self.rightFileTextArea.yview_moveto(first)
        self.leftLinenumbers.yview_moveto(first)
        self.rightLinenumbers.yview_moveto(first)
        self.uniScrollbar.set(first, last)

    def create_scroll_bars(self):
        self.uniScrollbar = Scrollbar(self.main_window)
        self.uniScrollbar.grid(row=self.uniScrollbarRow, column=self.uniScrollbarCol, sticky=NS)
        self.uniScrollbar.config(command=self.scrollBoth)
        self.leftFileTextArea.config(yscrollcommand=self.updateScroll)
        self.rightFileTextArea.config(yscrollcommand=self.updateScroll)
        self.leftLinenumbers.config(yscrollcommand=self.updateScroll)
        self.rightLinenumbers.config(yscrollcommand=self.updateScroll)

        leftHorizontalScrollbar = Scrollbar(self.main_window, orient=HORIZONTAL)
        leftHorizontalScrollbar.grid(row=self.horizontalScrollbarRow, column=self.leftHorizontalScrollbarCol, sticky=EW)
        leftHorizontalScrollbar.config(command=self.leftFileTextArea.xview)
        self.leftFileTextArea.config(xscrollcommand=leftHorizontalScrollbar.set)

        rightHorizontalScrollbar = Scrollbar(self.main_window, orient=HORIZONTAL)
        rightHorizontalScrollbar.grid(row=self.horizontalScrollbarRow, column=self.rightHorizontalScrollbarCol, sticky=EW)
        rightHorizontalScrollbar.config(command=self.rightFileTextArea.xview)
        self.rightFileTextArea.config(xscrollcommand=rightHorizontalScrollbar.set)
Example #20
0
class CopyFileFrame(CopilotInnerFrame):
    def __init__(self, master, config, state):
        super(CopyFileFrame, self).__init__(master, config)

        self._state = state

        self._item_paths = {}

        self._tree = Treeview(self._master, columns=('size'))
        self._tree.heading('size', text='Size')
        self._tree.grid(row=1, column=0, columnspan=3, sticky='nsew')
        self._tree.configure(yscrollcommand=self._sb.set)
        self._sb['command'] = self._tree.yview

        if self._state.action == 'copy':
            self._next_btn['text'] = 'Copy'
            self._frame_lbl['text'] = 'Copy File'
            self._populate_tree(self._config.file_root)
        elif self._state.action == 'delete':
            self._next_btn['text'] = 'Delete'
            self._frame_lbl['text'] = 'Delete File'
            self._populate_tree(self._state.to_device.part().mount())

        self._next_btn['command'] = self._next_cmd

    def _next_cmd(self):
        if self._state.action == 'copy':
            self._copy_file()
        elif self._state.action == 'delete':
            self._delete_file()

    def _copy_file(self):
        cur_item = self._tree.focus()
        cur_path = self._item_paths.get(cur_item, '')
        if cur_path != '':
            new_path = os.path.join(self._state.device_to_path, os.path.basename(cur_path))
            try:
                if os.path.exists(new_path):
                    if ConfirmFrame.show(
                        self._master, self._config,
                        'The file already exists in the destination.\n'
                        'Would you like to overwrite it?',
                        'Yes', 'No'
                    ):
                        shutil.copyfile(cur_path, new_path)
                else:
                    shutil.copyfile(cur_path, new_path)
            except PermissionError:
                OkFrame.show(
                    self._master, self._config,
                    'Error copying file:\n\nInvalid permissions'
                )
            except Exception as e:
                OkFrame.show(
                    self._master, self._config,
                    'An error occurred while copying the file:\n\n{}'.format(e)
                )

    def _delete_file(self):
        cur_item = self._tree.focus()
        cur_path = self._item_paths.get(cur_item, '')
        if cur_path != '':
            disp_path = cur_path[len(self._state.to_device.part().mount()):]
            try:
                if ConfirmFrame.show(
                    self._master, self._config,
                    'Are you sure you\'d like to delete this file?\n{}'.format(disp_path),
                    'Yes', 'No'
                ):
                    os.remove(cur_path)
                    self._tree.delete(self._tree.focus())
            except PermissionError:
                OkFrame.show(
                    self._master, self._config,
                    'Error deleting file:\n\nInvalid permissions'
                )
            except Exception as e:
                OkFrame.show(
                    self._master, self._config,
                    'An error occurred while deleting the file:\n\n{}'.format(e)
                )

    def _populate_tree(self, tree_root):
        self._item_paths = {}

        def insert_path(tree, path, parent_id):
            dirs = [e for e in scandir(path) if e.is_dir()]
            dirs.sort(key=lambda e: e.name)

            for d in dirs:
                dir_name = d.name
                dir_id = '{}-{}'.format(parent_id, dir_name)
                dir_path = os.path.join(path, dir_name)
                tree.insert(parent_id, 'end', dir_id, text=dir_name, tags=('dir'))
                try:
                    insert_path(tree, dir_path, dir_id)
                except:
                    pass

            files = [e for e in scandir(path) if e.is_file()]
            files.sort(key=lambda e: e.name)

            for idx, f in enumerate(files):
                file_name = f.name
                file_id = '{}-{}'.format(parent_id, file_name)
                file_stat = f.stat()
                file_size = sizeof_fmt(file_stat.st_size)
                file_path = os.path.join(path, file_name)
                self._item_paths[file_id] = file_path

                if idx % 2 == 0:
                    file_bg = 'file_even'
                else:
                    file_bg = 'file_odd'

                tree.insert(
                    parent_id,
                    'end',
                    file_id,
                    text=file_name,
                    tags=('file', file_bg),
                    values=(file_size)
                )

        insert_path(self._tree, tree_root, '')

        tree = self._tree
        tree.tag_configure('dir', font=self._config.item_font)
        tree.tag_configure('file', font=self._config.item_font)
        tree.tag_configure('file_odd', background='light grey')
    def __init__(self, root):
        #create object reference instance of database class as p
        p = Database()
        p.conn()
        self.root = root
        self.root.title("Etudiants et filiéres")
        self.root.geometry("1400x900")
        EID = StringVar
        Enom = StringVar()
        Eprenom = StringVar()
        Eage = StringVar()
        fID = StringVar()
        Fnom = StringVar()
        FIDF = StringVar()

        ###############################################fonctions etudiant#################################
        def clearFi():

            F_nom.delete(0, 'end')
            F_IDF.delete(0, 'end')
            tviewFl.delete(*tviewFl.get_children())

        def showAllFi():

            con = sqlite3.connect("EtudiantFilieres.db")
            c = con.cursor()
            c.execute("SELECT * FROM FILIERE ")
            rows = c.fetchall()
            if len(rows) == 0:
                MessageBox.showinfo("Information", "No Record exists")
            else:
                tviewFl.delete(*tviewFl.get_children())
                for row in rows:
                    tviewFl.insert('', 'end', values=row)

        def insertFi():
            ID = F_IDF.get()
            NOM = F_nom.get()

            if (F_nom.get() == "" or F_IDF.get() == ""):
                MessageBox.showinfo("Insert status", "All filds are required")
            else:
                con = sqlite3.connect("EtudiantFilieres.db")
                c = con.cursor()
                queery = "insert into FILIERE values (?,?)"
                c.execute(queery, (ID, NOM))
                c.execute("commit")

                MessageBox.showinfo("Insert status", "Inserted Successfully")
                F_nom.delete(0, 'end')
                F_IDF.delete(0, 'end')

                con.close()

        def deleteFi():

            if (F_IDF.get() == ""):
                MessageBox.showinfo("Delete status",
                                    "ID is compolsary for delete")
            else:

                con = sqlite3.connect("EtudiantFilieres.db")
                c = con.cursor()
                c.execute("SELECT * from FILIERE where IdFiliere ='" +
                          F_IDF.get() + "'")
                rows = c.fetchall()
                if len(rows) == 0:
                    MessageBox.showinfo("Delete status", "id not found!")
                else:
                    c.execute("SELECT * FROM ETUDIANT where IDFiliereK ='" +
                              F_IDF.get() + "'")
                    rows = c.fetchall()
                    if len(rows) == 0:
                        c.execute("delete from FILIERE where IdFiliere = ?",
                                  (F_IDF.get(), ))

                        c.execute("commit")
                        MessageBox.showinfo("Delete status",
                                            "Deleted Successfully !")

                    else:
                        c.execute("delete from FILIERE where IdFiliere = ?",
                                  (F_IDF.get(), ))

                        c.execute("delete from ETUDIANT where IDFiliereK = ?",
                                  (F_IDF.get(), ))

                        c.execute("commit")
                        MessageBox.showinfo("Delete status",
                                            "Deleted Successfully")
                        con.close()

        def updateFi():

            if (F_IDF.get() == ""):
                MessageBox.showinfo("Insert status",
                                    "ID is compolsary for delete")

            else:
                con = sqlite3.connect("EtudiantFilieres.db")
                c = con.cursor()
                c.execute("SELECT * FROM FILIERE where IdFiliere ='" +
                          F_IDF.get() + "'")
                rows = c.fetchall()
                if len(rows) == 0:
                    MessageBox.showinfo(
                        "Update status",
                        " id not found , try with another one  !")
                else:

                    c.execute("update FILIERE set IdFiliere='" + F_IDF.get() +
                              "' , nomF='" + F_nom.get() + "' ")
                    c.execute("commit")
                    MessageBox.showinfo("Update statut ",
                                        "Updated Successfully")

                    F_nom.delete(0, 'end')
                    F_IDF.delete(0, 'end')

                    con.close()

        def getFi():

            if (F_IDF.get() == ""):
                MessageBox.showinfo("Delete status",
                                    "ID is compolsary for delete")
            else:
                con = sqlite3.connect("EtudiantFilieres.db")
                c = con.cursor()
                c.execute("SELECT * FROM FILIERE where IdFiliere ='" +
                          F_IDF.get() + "'")
                rows = c.fetchall()
                if len(rows) == 0:
                    MessageBox.showinfo(
                        "Get status", " id not found, try with another one!")
                else:
                    c.execute("select * from FILIERE where IdFiliere ='" +
                              F_IDF.get() + "'")
                    rows = c.fetchall()

                    for row in rows:
                        F_nom.insert(0, row[1])

                    con.close()

        ############################################### fonctions Etudiant#############################################
        def clearEt():
            e_nom.delete(0, 'end')
            e_prenom.delete(0, 'end')
            e_age.delete(0, 'end')
            F_ID.delete(0, 'end')
            E_ID.delete(0, 'end')
            tviewEt.delete(*tviewEt.get_children())

        def insertEt():
            nom = e_nom.get()
            prenom = e_prenom.get()
            age = e_age.get()
            IDfiliere = F_ID.get()
            IDEtudiant = E_ID.get()

            if (nom == "" or prenom == "" or age == "" or IDfiliere == ""
                    or IDEtudiant == ""):
                MessageBox.showinfo("Insert status", "All filds are required")
            else:
                con = sqlite3.connect("EtudiantFilieres.db")
                c = con.cursor()
                c.execute("SELECT * FROM FILIERE where IdFiliere ='" +
                          IDfiliere + "'")
                rows = c.fetchall()
                if len(rows) == 0:
                    MessageBox.showinfo(
                        "Insert status",
                        "id filiére not found , try with another one ")
                else:

                    queery = "insert into Etudiant values (?,?,?,?,?)"
                    c.execute(queery,
                              (IDEtudiant, nom, prenom, age, IDfiliere))
                    c.execute("commit")

                    MessageBox.showinfo("Insert status",
                                        "Inserted Successfully")
                    e_nom.delete(0, 'end')
                    e_prenom.delete(0, 'end')
                    e_age.delete(0, 'end')
                    F_ID.delete(0, 'end')
                    E_ID.delete(0, 'end')
                    con.close()

        def deleteEt():
            if (E_ID.get() == ""):
                MessageBox.showinfo("Delete status",
                                    "ID is compolsary for delete")
            else:

                con = sqlite3.connect("EtudiantFilieres.db")
                c = con.cursor()
                c.execute("SELECT * FROM ETUDIANT where IdEtudiant  ='" +
                          E_ID.get() + "'")
                rows = c.fetchall()
                if len(rows) == 0:
                    MessageBox.showinfo(
                        "Delete status",
                        " id not found , try with another one !")
                else:
                    c.execute("delete from Etudiant where IdEtudiant = ?",
                              (E_ID.get(), ))
                    c.execute("commit")

                    MessageBox.showinfo("Delete status",
                                        "Deleted Successfully")
                    con.close()

        def updateEt():
            nom = e_nom.get()
            prenom = e_prenom.get()
            age = e_age.get()
            IDfiliere = F_ID.get()
            IDEtudiant = E_ID.get()

            if (nom == "" or prenom == "" or age == "" or IDfiliere == ""
                    or IDEtudiant == ""):
                MessageBox.showinfo("Update status", "All filds are required")
            else:
                con = sqlite3.connect("EtudiantFilieres.db")
                c = con.cursor()
                c.execute("SELECT * FROM ETUDIANT where IdEtudiant  ='" +
                          IDEtudiant + "'")
                rows = c.fetchall()
                if len(rows) == 0:
                    MessageBox.showinfo("Update status", " id not found !")
                else:
                    c.execute("SELECT * FROM FILIERE where IdFiliere ='" +
                              F_IDF.get() + "'")
                    rows = c.fetchall()
                    if len(rows) == 0:
                        MessageBox.showinfo(
                            "Update status",
                            " id Filiere not found , try with another id Filiere !"
                        )
                    else:
                        c.execute("update Etudiant set IdEtudiant='" +
                                  IDEtudiant + "' , nom='" + nom +
                                  "' , prenom= '" + prenom + "',age ='" + age +
                                  "' ,IDFiliereK = '" + IDfiliere + "' ")

                        c.execute("commit")
                        e_nom.delete(0, 'end')
                        e_prenom.delete(0, 'end')
                        e_age.delete(0, 'end')
                        F_ID.delete(0, 'end')
                        E_ID.delete(0, 'end')
                        MessageBox.showinfo("Update statut ",
                                            "Updated Successfully")
                        con.close()

        def getEt():
            if (E_ID.get() == ""):
                MessageBox.showinfo("Delete status",
                                    "ID is compolsary for delete")
            else:
                con = sqlite3.connect("EtudiantFilieres.db")
                c = con.cursor()
                c.execute("SELECT * FROM ETUDIANT where IdEtudiant  ='" +
                          E_ID.get() + "'")
                rows = c.fetchall()
                if len(rows) == 0:
                    MessageBox.showinfo("Get status", " id not found !")
                else:
                    c.execute("select * from Etudiant where IdEtudiant='" +
                              E_ID.get() + "'")
                    rows = c.fetchall()

                    for row in rows:
                        e_nom.insert(0, row[1])
                        e_prenom.insert(0, row[2])
                        e_age.insert(0, row[3])
                        F_ID.insert(0, row[1])
                    con.close()

        def showAllET():
            con = sqlite3.connect("EtudiantFilieres.db")
            c = con.cursor()
            c.execute("SELECT * FROM Etudiant")
            rows = c.fetchall()
            if len(rows) == 0:
                MessageBox.showinfo("Information", "No Record exists")
            else:
                tviewEt.delete(*tviewEt.get_children())
                for row in rows:
                    tviewEt.insert('', 'end', values=row)

        ############################################# frame header #############################

        MainFrame = Frame(self.root, bg="white")
        MainFrame.grid()
        HeadFrame = Frame(MainFrame,
                          bd=1,
                          padx=50,
                          pady=10,
                          bg="sea green",
                          relief=RIDGE)
        HeadFrame.pack(side=TOP)
        self.ITitle = Label(
            HeadFrame,
            text="    Institut National de Statistique et d'Economie Appliquée",
            bg="sea green",
            fg='black',
            font=("bold", 25))
        self.ITitle.grid()

        #########################################frame etudiant ################################
        FrameEtudiant = LabelFrame(root,
                                   text='Étudiant',
                                   width=650,
                                   height=645,
                                   bd=2,
                                   bg='sea green',
                                   font=('bold', 20)).place(x=14, y=102)
        frameEt = LabelFrame(FrameEtudiant,
                             width=632,
                             height=556,
                             bd=2,
                             font=('bold', 20)).place(x=23, y=130)
        tviewEt = Treeview(frameEt,
                           columns=(1, 2, 3, 4, 5),
                           show='headings',
                           height=12)
        tviewEt.place(x=56, y=430)

        tviewEt.heading(1, text='id étudinat')
        tviewEt.column(1, anchor='center', width=90)

        tviewEt.heading(2, text='nom')
        tviewEt.column(2, anchor='center', width=120)

        tviewEt.heading(3, text='prénom')
        tviewEt.column(3, anchor='center', width=120)

        tviewEt.heading(4, text='age')
        tviewEt.column(4, anchor='center', width=95)

        tviewEt.heading(5, text='id filière')
        tviewEt.column(5, anchor='center', width=125)

        scroll_et = Scrollbar(frameEt, orient=VERTICAL, command=tviewEt.yview)
        tviewEt.configure(yscroll=scroll_et.set)
        scroll_et.place(x=600, y=450)

        #################################### entresEtudiant ################################
        E_ID = Entry(root, width=32, borderwidth=4)
        E_ID.place(x=290, y=183)
        E_ID.focus()
        e_nom = Entry(root, width=32, borderwidth=4)
        e_nom.place(x=290, y=235)
        e_prenom = Entry(root, width=32, borderwidth=4)
        e_prenom.place(x=290, y=286)
        e_age = Entry(root, width=32, borderwidth=4)
        e_age.place(x=290, y=338)
        F_ID = Entry(root, width=32, borderwidth=4)
        F_ID.place(x=290, y=390)

        ################################ register etudiant ###################################
        EID = Label(root,
                    text=" ID étudiant:",
                    width=24,
                    height=2,
                    bg="PaleGreen3").place(x=50, y=180)
        Enom = Label(root, text=" Nom:", width=24, height=2,
                     bg="PaleGreen3").place(x=50, y=232)
        Eprenom = Label(root,
                        text="Prénom:",
                        width=24,
                        height=2,
                        bg="PaleGreen3").place(x=50, y=282)
        Eage = Label(root, text=" Age :", width=24, height=2,
                     bg="PaleGreen3").place(x=50, y=338)
        FID = Label(root,
                    text=" ID de filiére  :",
                    width=24,
                    height=2,
                    bg="PaleGreen3").place(x=50, y=390)

        #################################frame filiere###################################
        FrameFilere = LabelFrame(root,
                                 text='Filière',
                                 width=650,
                                 height=645,
                                 bg='sea green',
                                 bd=2,
                                 font=('bold', 20)).place(x=688, y=102)
        frameFl = LabelFrame(FrameFilere,
                             width=632,
                             height=556,
                             bd=2,
                             font=('bold', 20)).place(x=697, y=130)

        tviewFl = Treeview(frameFl, columns=(1, 2), show='headings', height=12)
        tviewFl.place(x=790, y=340)
        tviewFl.heading(1, text='id filière')
        tviewFl.column(1, anchor='center', width=130)
        tviewFl.heading(2, text='nom filière')
        tviewFl.column(2, anchor='center', width=330)
        scroll_fl = Scrollbar(frameFl, orient=VERTICAL, command=tviewFl.yview)
        tviewFl.configure(yscroll=scroll_fl.set)
        scroll_fl.place(x=1254, y=360)
        ################"###################ENTRIES FILIÈRE #######################

        F_IDF = Entry(root, width=32, borderwidth=4)
        F_IDF.place(x=990, y=278)
        F_nom = Entry(root, width=32, borderwidth=4)
        F_nom.place(x=990, y=228)
        F_nom.focus()
        ######################################### register filiere##################

        FIDF = Label(root,
                     text="ID filière ",
                     width=24,
                     height=2,
                     bg="PaleGreen3").place(x=740, y=275)
        Fnom = Label(root,
                     text="Nom filière :",
                     width=24,
                     height=2,
                     bg="PaleGreen3").place(x=740, y=225)

        ####################################button Etudiant#####################"

        insertEt = Button(FrameEtudiant,
                          text="save",
                          width=9,
                          height=2,
                          fg="black",
                          bg="honeydew2",
                          font=("Calibri", 15),
                          command=insertEt).place(x=21, y=698)
        deletetEt = Button(FrameEtudiant,
                           text="Delete",
                           width=9,
                           height=2,
                           fg="black",
                           bg="honeydew2",
                           font=("Calibri", 15),
                           command=deleteEt).place(x=129, y=698)
        updateEt = Button(FrameEtudiant,
                          text="Update ",
                          width=9,
                          height=2,
                          fg="black",
                          bg="honeydew2",
                          font=("Calibri", 15),
                          command=updateEt).place(x=237, y=698)
        getEt = Button(FrameEtudiant,
                       text="Get",
                       width=9,
                       height=2,
                       fg="black",
                       bg="honeydew2",
                       font=("Calibri", 15),
                       command=getEt).place(x=344, y=698)
        clearEt = Button(FrameEtudiant,
                         text="Clear",
                         width=9,
                         height=2,
                         fg="black",
                         bg="honeydew2",
                         font=("Calibri", 15),
                         command=clearEt).place(x=453, y=698)
        showAllET = Button(FrameEtudiant,
                           text="show all",
                           width=9,
                           height=2,
                           fg="black",
                           bg="honeydew2",
                           font=("Calibri", 15),
                           command=showAllET).place(x=561, y=698)

        ################################### button Filiere ######################
        insertFi = Button(FrameEtudiant,
                          text="Save",
                          width=9,
                          height=2,
                          fg="black",
                          bg="honeydew2",
                          font=("Calibri", 15),
                          command=insertFi).place(x=696, y=698)
        deletetFi = Button(FrameEtudiant,
                           text="Delete",
                           width=9,
                           height=2,
                           fg="black",
                           bg="honeydew2",
                           font=("Calibri", 15),
                           command=deleteFi).place(x=804, y=698)
        updateFi = Button(FrameEtudiant,
                          text="Update",
                          width=9,
                          height=2,
                          fg="black",
                          bg="honeydew2",
                          font=("Calibri", 15),
                          command=updateFi).place(x=912, y=698)
        getFi = Button(FrameEtudiant,
                       text="Get",
                       width=9,
                       height=2,
                       fg="black",
                       bg="honeydew2",
                       font=("Calibri", 15),
                       command=getFi).place(x=1020, y=698)
        clearFi = Button(FrameEtudiant,
                         text="Clear",
                         width=9,
                         height=2,
                         fg="black",
                         bg="honeydew2",
                         font=("Calibri", 15),
                         command=clearFi).place(x=1127, y=698)
        showAllFi = Button(FrameEtudiant,
                           text="show all",
                           width=9,
                           height=2,
                           fg="black",
                           bg="honeydew2",
                           font=("Calibri", 15),
                           command=showAllFi).place(x=1234, y=698)