Exemplo n.º 1
0
class StrategyShareToplevel(Parent):
    """
    Toplevel to display a list of strategy with checkboxes to allow
    selecting which should be shared.
    """
    def __init__(self, master, client, database, strategy_frame, **kwargs):
        """
        :param master: master widget
        :param client: network.strategy.client.StrategyClient
        :param database: results.strategies.StrategyDataBase
        :param strategy_frame: frames.strategy.StrategyFrame
        :param kwargs: SnapToplevel keyword arguments
        """
        resizable = kwargs.pop("resizable", False)
        self._client = client
        self._database = database
        self._frame = strategy_frame
        Parent.__init__(self, master, **kwargs)
        self.wm_title("GSF Parser: Strategy Sharing")
        self.wm_resizable(resizable, resizable)
        # Configure the Treeview
        self.tree = CheckboxTreeview(master=self, height=16)
        self.tree.column("#0", width=200)
        self.tree.heading("#0", text="Strategy")
        self.tree.config(show=("headings", "tree"))
        self.scroll_bar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.config(yscrollcommand=self.scroll_bar.set)
        self.update_strategy_tree()
        self.share_button = ttk.Button(self, text="Share Strategies", command=self.share_strategies)
        self.grid_widgets()

    def grid_widgets(self):
        self.tree.grid(row=1, column=1, sticky="nswe", padx=5, pady=5)
        self.scroll_bar.grid(row=1, column=2, sticky="ns", padx=(0, 5), pady=5)
        self.share_button.grid(row=2, column=1, columnspan=2, sticky="nswe", padx=5, pady=(0, 5))

    def share_strategies(self):
        for strategy in self.strategies_to_share:
            self._client.send_strategy(strategy)
        messagebox.showinfo("Info", "Selected Strategies sent.")

    def update_strategy_tree(self):
        self.tree.delete(*self.tree.get_children(""))
        for strategy in sorted(self._database.keys()):
            self.tree.insert("", tk.END, iid=strategy, text=strategy)

    @property
    def strategies_to_share(self):
        for strategy in self.tree.get_checked():
            yield self._database[strategy]
Exemplo n.º 2
0
class LeftPanel:
    def __init__(self, root, frame):
        self.root = root
        self.frame = Frame(frame)

        # Create the toolbar as a frame

        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=1)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=1)
        self.frame.grid_rowconfigure(1, minsize=70)

        self.img1 = Image.open("icons/open-folder.png").convert('RGBA')
        self.useImg1 = ImageTk.PhotoImage(self.img1)

        self.path = os.path.dirname(__file__)

        #self.style = ttk.Style()
        #self.style.configure('Treeview', rowheight=40)
        self.tree =  CheckboxTreeview(self.frame)

        #self.tree.pack(expand=YES, fill=BOTH)
        self.tree.heading("#0", text="Ficheiros")

        self.dir = self.tree.insert('', 'end', text=self.path, open=True)
        self.Subs(self.path, self.dir)


        self.tree.grid(row=0, column=0, columnspan=2, padx=4, pady=4, sticky=ALL)

        Button(self.frame, image=self.useImg1, width=70, height=70, command=self.browse_button).grid(row=2, column=1, padx=4, pady=4, sticky=E)

        self.frame.pack(side=TOP, fill=BOTH)

    def Subs(self, path, parent):
        for p in os.listdir(path):
            abspath = os.path.join(path, p)
            parent_element = self.tree.insert(parent, 'end', text=p, open=True)
            if os.path.isdir(abspath):
                self.Subs(abspath, parent_element)

    def browse_button(self):
        self.path = tkFileDialog.askdirectory()


    def set_dir(self):
        sourcePath = str(self.path)
        os.chdir(sourcePath)
    def generate_tree(self):
        root = tk.Tk()
        tree = CheckboxTreeview(root)
        #root.withdraw()

        visited = {ID: False for ID in self.id_to_name}
        for parent in self.dict:
            if visited[parent] == False:
                visited[parent] = True
                tree.insert("",
                            "end",
                            parent,
                            text=self.get_name_from_id(parent))
                self.generate_tree_dfs(parent, visited, tree)

        def callback():
            print(tree.get_checked())

        expanded = False
        btn_text = tk.StringVar()

        def expand_collapse(expanded):
            if expanded == False:
                expanded = True
                tree.expand_all()
                btn_text.set("Collapse All")
            else:
                expanded = False
                tree.collapse_all()
                btn_text.set("Expand All")

        submit = tk.Button(root, text="Submit", command=callback)
        exp_col_b = tk.Button(root,
                              textvariable=btn_text,
                              command=expand_collapse(expanded))

        root.geometry('500x500')
        #root.resizeable()
        exp_col_b.pack()
        tree.pack(fill=tk.BOTH)
        submit.pack()

        root.mainloop()
Exemplo n.º 4
0
class TreeviewConstructor(object):
    logger = CustomAdapter(logging.getLogger(str(__name__)), None)

    @debug(lvl=logging.NOTSET, prefix='')
    def __init__(self, master, frame_main, checkwidth=0):
        self.master = master  # Done
        self.frame = frame_main  # Done
        self.col_obj_dict = {}  # Done
        self.column_lst = []  # Done
        self.col_disp_lst = []  # Done
        self.item_obj_dict = {}
        self.treeview = CheckboxTreeview(self.frame)  # Done
        self.ysb = ttk.Scrollbar(self.frame)  # Done
        self.xsb = ttk.Scrollbar(self.frame)  # Done
        self.checkwidth = checkwidth
        self.manager = BusyManager(self.frame)
        self.populate_frame()  # Done

    @debug(lvl=logging.NOTSET, prefix='')
    def populate_frame(self):
        self.frame.columnconfigure(0, weight=1)  # Done
        self.frame.rowconfigure(0, weight=1)  # Done
        self.treeview.grid(row=0, column=0, sticky=tk.NSEW)  # Done
        self.ysb.config(orient=tk.VERTICAL, command=self.treeview.yview)  # Done
        self.xsb.config(orient=tk.HORIZONTAL, command=self.treeview.xview)  # Done
        self.treeview['yscroll'] = self.ysb.set  # Done
        self.treeview['xscroll'] = self.xsb.set  # Done
        self.ysb.grid(row=0, column=1, sticky=tk.NS)  # Done
        self.xsb.grid(row=1, column=0, sticky=tk.EW)  # Done

    @debug(lvl=logging.NOTSET, prefix='')
    def populate_cols(self):
        col_obj = TreeColumn(order=0,
                             col_id='#0',
                             hdr_txt="",
                             anchor=tk.W,
                             stretch=tk.NO,
                             minwidth=0,
                             width=self.checkwidth,
                             display=False)
        TreeviewConstructor.logger.log(logging.NOTSET, "Column ID: {col_id} Header Text: {hdr_txt}".
                                       format(col_id=col_obj.col_id, hdr_txt=col_obj.hdr_txt))
        self.col_obj_dict[col_obj.col_id] = col_obj

        for col_key, column in sorted(self.col_obj_dict.items(), key=lambda x: x[1].order):
            self.column_lst.append(column.col_id)
            if column.display:
                self.col_disp_lst.append(column.col_id)

        self.treeview.config(columns=self.column_lst, displaycolumns=self.col_disp_lst)
        self.treeview.tag_configure('red', foreground='red2')
        self.treeview.tag_configure('evenrow', background='gray85')
        self.treeview.tag_configure('oddrow', background='white')

        for col in self.col_obj_dict.values():
            TreeviewConstructor.logger.log(
                logging.NOTSET,
                "Column ID: {col_id} Header Text: {hdr_txt} Anchor: {anchor}".format(
                    col_id=col.col_id, hdr_txt=col.hdr_txt, anchor=col.anchor))
            if col.hdr_txt in (None, ""):
                header = col.col_id
            else:
                header = col.hdr_txt
            self.treeview.heading(column=col.col_id,
                                  text=header,
                                  anchor=col.anchor,
                                  command=lambda _col=col.col_id: self.treeview_sort_column(_col, False))
            self.treeview.column(col.col_id, minwidth=col.minwidth, width=col.width, stretch=col.stretch)

    @debug(lvl=logging.DEBUG, prefix='')
    def populate_items(self):
        for item in self.item_obj_dict.values():
            TreeRow.logger.log(logging.NOTSET, "Item Info: {0}".format(item.iid))
            self.treeview.insert(item.parent, item.index, iid=item.iid, values=item.values_list)
            for tag in item.tags_list:
                self.treeview.tag_add(item.iid, tag)

    @debug(lvl=logging.DEBUG, prefix='')
    def stripe_rows(self):
        for item in self.item_obj_dict.values():
            self.treeview.tag_del(item.iid, 'evenrow')
            self.treeview.tag_del(item.iid, 'oddrow')
            row_num = self.treeview.index(item.iid)
            if row_num % 2 == 0:
                self.treeview.tag_add(item.iid, 'evenrow')
            elif row_num % 2 != 0:
                self.treeview.tag_add(item.iid, 'oddrow')

    @debug(lvl=logging.DEBUG, prefix='')
    def treeview_sort_column(self, col, reverse):
        self.manager.busy()
        item_list = [(self.treeview.set(k, col), k) for k in self.treeview.get_children('')]
        item_list.sort(reverse=reverse)
        # rearrange items in sorted positions
        for index, (val, k) in enumerate(item_list):
            self.treeview.move(k, '', index)
        self.stripe_rows()
        # reverse sort next time
        self.treeview.heading(col, command=lambda: self.treeview_sort_column(col, not reverse))
        self.manager.not_busy()

    @debug(lvl=logging.DEBUG, prefix='')
    def tv_refresh(self):
        # self.manager.busy()
        item_list = list(self.treeview.get_children(''))
        item_list.sort(key=lambda x: int(x))
        for item_iid, item_obj in sorted(self.item_obj_dict.items()):
            TreeRow.logger.log(logging.NOTSET, "Item ID: {0}".format(item_iid))
            # l = self.treeview.get_children('')
            for index, k in enumerate(item_list):
                TreeRow.logger.log(logging.NOTSET, "k: {0}".format(k))
                if str(item_iid) == str(k):
                    self.treeview.delete(k)
                    item_obj.index = index
                    self.treeview.insert(item_obj.parent, item_obj.index, iid=item_obj.iid, values=item_obj.values_list)
                    item_list.remove(k)
                    break
        self.stripe_rows()
Exemplo n.º 5
0
class PanelMixin:
    def build_right_materials(self, *args, **kwargs):
        for widget in self.right_mat_tab.winfo_children():
            widget.destroy()

        i = 0
        for mat_loc in self.materials.values():
            for (name, (material, button)) in mat_loc.items():
                # for i, (name, (material, button)), in enumerate(self.materials.items()):
                if button is None:
                    button = tk.Button(
                        master=self.right_mat_tab,
                        text=name,
                        bg=material.color,
                        fg=contrasting_text_color(material.color[1:]),
                        command=self.material_button_generator(material))
                print(self.cbtv.get_checked())
                if name in self.cbtv.get_checked():
                    button.grid(column=i % 3,
                                row=i // 3,
                                pady=self.ICON_PADDING,
                                padx=self.ICON_PADDING)
                else:
                    button.grid_forget()
                i += 1

    def build_bottom_bar(self):
        self.shape_frame = tk.Frame(self.bottom_frame)
        self.shape_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        self.coord_frame = tk.Frame(self.bottom_frame)
        self.coord_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        self.fill_frame = tk.Frame(self.bottom_frame)
        self.fill_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        self.snap_frame = tk.Frame(self.bottom_frame)
        self.snap_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        line_button = tk.Button(self.shape_frame, text='Line')
        line_button.config(command=self.shape_func_generator([
            partial(self.paint_2pt_shape_start, shape='line'),
            partial(self.paint_2pt_shape_move, shape='line'),
            partial(self.paint_2pt_shape_end, shape='line')
        ], line_button))
        line_button.grid(row=0, column=0)

        rectangle_button = tk.Button(self.shape_frame, text='Rectangle')
        rectangle_button.config(command=self.shape_func_generator([
            partial(self.paint_2pt_shape_start, shape='rectangle'),
            partial(self.paint_2pt_shape_move, shape='rectangle'),
            partial(self.paint_2pt_shape_end, shape='rectangle')
        ], rectangle_button))
        rectangle_button.grid(row=1, column=0)

        circle_button = tk.Button(self.shape_frame, text='Circle')
        circle_button.config(command=self.shape_func_generator([
            partial(self.paint_2pt_shape_start, shape='circle'),
            partial(self.paint_2pt_shape_move, shape='circle'),
            partial(self.paint_2pt_shape_end, shape='circle')
        ], circle_button))
        circle_button.grid(row=0, column=1)

        ellipse_button = tk.Button(self.shape_frame, text='Ellipse')
        ellipse_button.config(
            command=self.shape_func_generator('ellipse', ellipse_button))
        ellipse_button.grid(row=1, column=1)

        arc_button = tk.Button(self.shape_frame, text='Arc')
        arc_button.config(command=self.shape_func_generator([
            partial(self.paint_3pt_shape_start, shape='arc'),
            partial(self.paint_3pt_shape_move_1st, shape='arc'),
            partial(self.paint_3pt_shape_2nd_pt, shape='arc')
        ], arc_button))
        arc_button.grid(row=0, column=2)

        ellipse_button.config(state=tk.DISABLED)
        arc_button.config(state=tk.DISABLED)

        freehand_button = tk.Button(self.shape_frame, text='Freehand')
        freehand_button.config(command=self.shape_func_generator([
            self.paint_freehand_start, self.paint_freehand_move,
            self.paint_freehand_end
        ], freehand_button))
        freehand_button.grid(row=1, column=2)

        self.shape_buttons = [
            line_button, rectangle_button, circle_button, ellipse_button,
            arc_button, freehand_button
        ]

        ttk.Separator(self.shape_frame,
                      orient=tk.VERTICAL).grid(row=0,
                                               column=3,
                                               rowspan=2,
                                               sticky=tk.N + tk.S)
        self.increase_scaling_factor = tk.Button(self.coord_frame,
                                                 text='Zoom In',
                                                 command=self.zoom_in)
        self.decrease_scaling_factor = tk.Button(self.coord_frame,
                                                 text='Zoom Out',
                                                 command=self.zoom_out)
        self.increase_scaling_factor.grid(row=1, column=0)
        self.decrease_scaling_factor.grid(row=1, column=1)

        # self.scaling_factor_scale = tk.Scale(self.coord_frame, from_=1, to=20, orient=tk.HORIZONTAL, command=self.rebuild_img, repeatinterval=300)
        # self.scaling_factor_scale.set(self.scaling_factor)
        # self.scaling_factor_scale.grid(row=1, column=0, columnspan=2, sticky=tk.E+tk.W)
        ttk.Separator(self.coord_frame,
                      orient=tk.VERTICAL).grid(row=0,
                                               column=2,
                                               rowspan=2,
                                               sticky=tk.N + tk.S)
        show_button = tk.Button(self.snap_frame,
                                text='show',
                                command=self.show_bitmap)
        show_button.pack()
        # delete_button = tk.Button(self.shape_frame, text='Delete')
        # freehand_button.config(command=selection_fro.erasor_bind)
    def show_bitmap(self):
        print(self.bitmap)
        top = tk.Toplevel()
        img = Image.fromarray(self.bitmap)
        img = img.convert('RGB')
        img.show()
        img = ImageTk.PhotoImage(image=img)
        logolbl = tk.Label(top, image=img)
        logolbl.grid()

    def build_left_objects_notebook(self):
        self.left_obj_tab = tk.Frame(self.left_notebook)
        self.left_notebook.add(self.left_obj_tab, text='Objects')

    def build_left_materials_notebook(self):
        self.left_mat_tab = tk.Frame(self.left_notebook)
        self.left_notebook.add(self.left_mat_tab, text='Materials')

    def build_left_materials(self):
        self.cbtv = CheckboxTreeview(master=self.left_mat_tab)
        self.cbtv.pack()
        for cat_name, mat_cat in self.materials.items():
            self.cbtv.insert("", "end", cat_name, text=cat_name)
            for name, (mat, button) in mat_cat.items():
                self.cbtv.insert(cat_name, "end", name, text=name)
                # var = cb
                # check = tk.Checkbutton(master=self.left_mat_tab, text=name, variable=var)
                # check.pack(side=tk.TOP)
        self.cbtv.bind('<<TreeviewSelect>>', self.build_right_materials)

    def build_right_materials_notebook(self):
        self.right_mat_tab = tk.Frame(self.right_notebook)
        self.right_notebook.add(self.right_mat_tab, text='Materials')

        self.build_right_materials()

    def build_right_objects_notebook(self):
        self.right_obj_tab = tk.Frame(self.right_notebook)
        self.right_notebook.add(self.right_obj_tab, text='Objects')
        self.build_right_objects()

    def build_right_objects(self):
        for i, icon in enumerate(glob.glob('../game/data/images/*')):
            col = i % 3
            row = i // 3
            print(row, col)
            img = Image.open(icon)
            img = img.resize((50, 50), Image.ANTIALIAS)
            self.object_icons.append(ImageTk.PhotoImage(img))
            button = tk.Button(self.right_obj_tab,
                               image=self.object_icons[-1],
                               text=icon.split('/')[-1],
                               compound='top')
            # self.buttons.append(button)
            button.grid(row=row,
                        column=col,
                        pady=self.ICON_PADDING,
                        padx=self.ICON_PADDING)

    def undo(self, event):
        print('undo!')
        if self.current_paint_stroke == 0:
            return
        self.current_paint_stroke -= 1
        self.scene_view.delete('stroke_' + str(self.current_paint_stroke))

    def shape_func_generator(self, paint_functions, button):
        def func():
            for b in self.shape_buttons:
                b.config(fg=self.fg_default, bg=self.bg_default)
            button.config(fg=self.active_shape_fg, bg=self.active_shape_bg)
            self.scene_view.bind("<Button-1>", paint_functions[0])
            self.scene_view.bind("<B1-Motion>", paint_functions[1])
            self.scene_view.bind("<ButtonRelease-1>", paint_functions[2])
            self.active_shape_button = button

        return func

    def material_button_generator(self, material):
        def func():
            self.current_material = material
            bg = material.color
            fg = contrasting_text_color(material.color[1:])
            self.active_shape_fg = fg
            self.active_shape_bg = bg
            if self.active_shape_button is not None:
                self.active_shape_button.config(fg=fg, bg=bg)

        return func
 def test_checkboxtreeview_methods(self):
     tree = CheckboxTreeview(self.window)
     tree.pack()
     self.window.update()
     tree.insert("", "end", "1", text="1")
     tree.insert("1", "end", "11", text="11")
     tree.insert("11", "end", "111", text="111")
     tree.insert("11", "end", "112", text="112")
     self.window.update()
     tree.state()
     self.window.update()
     tree.state(['disabled'])
     self.window.update()
     tree.state(['!disabled'])
     self.window.update()
     tree.collapse_all()
     self.window.update()
     tree.expand_all()
     self.window.update()
     tree.tag_add("1", "item")
     self.assertTrue(tree.tag_has("item", "1"))
     self.window.update()
     tree.change_state("1", "checked")
     self.assertTrue(tree.tag_has("checked", "1"))
     self.assertFalse(tree.tag_has("unchecked", "1"))
     self.assertFalse(tree.tag_has("tristate", "1"))
     self.assertTrue(tree.tag_has("item", "1"))
     self.window.update()
     tree.tag_del("1", "item")
     self.assertFalse(tree.tag_has("item", "1"))
     self.window.update()
     tree._check_descendant("1")
     self.assertTrue(tree.tag_has("checked", "11"))
     self.assertTrue(tree.tag_has("checked", "111"))
     self.assertTrue(tree.tag_has("checked", "112"))
     self.window.update()
     tree._uncheck_descendant("1")
     self.assertTrue(tree.tag_has("unchecked", "11"))
     self.assertTrue(tree.tag_has("unchecked", "111"))
     self.assertTrue(tree.tag_has("unchecked", "112"))
     self.window.update()
     tree._check_ancestor("111")
     self.assertTrue(tree.tag_has("tristate", "11"))
     self.window.update()
     tree._check_ancestor("112")
     self.assertTrue(tree.tag_has("checked", "11"))
     self.window.update()
     tree._uncheck_ancestor("111")
     self.assertTrue(tree.tag_has("tristate", "11"))
     self.window.update()
     tree._uncheck_ancestor("112")
     self.assertTrue(tree.tag_has("unchecked", "11"))
     self.window.update()
     tree._tristate_parent("111")
     self.assertTrue(tree.tag_has("tristate", "11"))
     self.assertTrue(tree.tag_has("tristate", "1"))
     self.window.update()
     tree.change_state("1", "checked")
     tree._check_descendant("1")
     self.assertEqual(tree.get_checked(), ["111", "112"])
     self.window.update()
Exemplo n.º 7
0
# -*- coding: utf-8 -*-

# Copyright (c) Juliette Monsel 2017
# For license see LICENSE

from ttkwidgets import CheckboxTreeview
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk

root = tk.Tk()

tree = CheckboxTreeview(root)
tree.pack()

tree.insert("", "end", "1", text="1")
tree.insert("1", "end", "11", text="11")
tree.insert("1", "end", "12", text="12")
tree.insert("11", "end", "111", text="111")
tree.insert("", "end", "2", text="2")

root.mainloop()
Exemplo n.º 8
0
class TreeviewConstructor(ttk.Frame):
    logger = CustomAdapter(logging.getLogger(str(__name__)), None)

    @debug(lvl=logging.DEBUG, prefix='')
    def __init__(self, master, *args, **kwargs):
        self.col_obj_dict = {}
        self.column_lst = []
        self.col_disp_lst = []
        self.item_obj_dict = {}
        self.master = master

        # noinspection PyArgumentList
        super().__init__(self.master, *args, **kwargs)

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        self.treeview = CheckboxTreeview(self)
        TreeviewConstructor.logger.log(logging.DEBUG, "10")
        self.treeview.grid(row=0, column=0, sticky=tk.NSEW)
        TreeviewConstructor.logger.log(logging.DEBUG, "11")

        self.ysb = ttk.Scrollbar(self)
        TreeviewConstructor.logger.log(logging.DEBUG, "12")
        self.ysb.grid(row=0, column=1, sticky=tk.NS)
        TreeviewConstructor.logger.log(logging.DEBUG, "13")
        self.ysb.config(orient=tk.VERTICAL, command=self.treeview.yview)
        TreeviewConstructor.logger.log(logging.DEBUG, "14")

        self.xsb = ttk.Scrollbar(self)
        TreeviewConstructor.logger.log(logging.DEBUG, "15")
        self.xsb.grid(row=1, column=0, sticky=tk.EW)
        TreeviewConstructor.logger.log(logging.DEBUG, "16")
        self.xsb.config(orient=tk.HORIZONTAL, command=self.treeview.xview)
        TreeviewConstructor.logger.log(logging.DEBUG, "17")

        self.treeview['yscroll'] = self.ysb.set
        TreeviewConstructor.logger.log(logging.DEBUG, "18")
        self.treeview['xscroll'] = self.xsb.set
        TreeviewConstructor.logger.log(logging.DEBUG, "19")
        # self.manager = BusyManager(self.frame)

    @debug(lvl=logging.DEBUG, prefix='')
    def populate_cols(self, checkwidth):
        col_obj = TreeColumn(order=0,
                             col_id='#0',
                             hdr_txt="",
                             anchor=tk.W,
                             stretch=tk.NO,
                             minwidth=0,
                             width=checkwidth,
                             display=False)
        TreeviewConstructor.logger.log(
            logging.DEBUG, "Column ID: {col_id} Header Text: {hdr_txt}".format(
                col_id=col_obj.col_id, hdr_txt=col_obj.hdr_txt))
        self.col_obj_dict[col_obj.col_id] = col_obj

        for col_key, column in sorted(self.col_obj_dict.items(),
                                      key=lambda x: x[1].order):
            self.column_lst.append(column.col_id)
            if column.display:
                self.col_disp_lst.append(column.col_id)

        self.treeview.config(columns=self.column_lst,
                             displaycolumns=self.col_disp_lst)
        self.treeview.tag_configure('red',
                                    foreground='red4',
                                    background='IndianRed1')
        self.treeview.tag_configure('parent_evenrow', background='gray85')
        self.treeview.tag_configure('child_evenrow', background="honeydew3")
        self.treeview.tag_configure('parent_oddrow', background='white')
        self.treeview.tag_configure('child_oddrow', background="honeydew2")

        for col in self.col_obj_dict.values():
            TreeviewConstructor.logger.log(
                logging.DEBUG,
                "Column ID: {col_id} Header Text: {hdr_txt} Anchor: {anchor}".
                format(col_id=col.col_id,
                       hdr_txt=col.hdr_txt,
                       anchor=col.anchor))
            if col.hdr_txt in (None, ""):
                header = col.col_id
            else:
                header = col.hdr_txt
            if col.col_id == '#0':
                self.treeview.heading(column=col.col_id,
                                      text="",
                                      anchor=col.anchor,
                                      command=lambda _col=col.col_id: self.
                                      treeview_sort_column(_col, False))
            else:
                self.treeview.heading(column=col.col_id,
                                      text=header,
                                      anchor=col.anchor,
                                      command=lambda _col=col.col_id: self.
                                      treeview_sort_column(_col, False))

            self.treeview.column(col.col_id,
                                 minwidth=col.minwidth,
                                 width=col.width,
                                 stretch=col.stretch)

    @debug(lvl=logging.DEBUG, prefix='')
    def populate_items(self):
        for item in self.item_obj_dict.values():
            TreeviewConstructor.logger.log(logging.NOTSET,
                                           "Item Info: {0}".format(item.iid))
            self.treeview.insert(item.parent,
                                 item.index,
                                 iid=item.iid,
                                 values=item.values_list)
            for tag in item.tags_list:
                self.treeview.tag_add(item.iid, tag)

    @debug(lvl=logging.DEBUG, prefix='')
    def stripe_rows(self):
        for item in self.item_obj_dict.values():
            self.treeview.tag_del(item.iid, 'parent_evenrow')
            self.treeview.tag_del(item.iid, 'child_evenrow')
            self.treeview.tag_del(item.iid, 'parent_oddrow')
            self.treeview.tag_del(item.iid, 'child_oddrow')
            row_num = self.treeview.index(item.iid)
            if row_num % 2 == 0:
                if item.parent == "":
                    self.treeview.tag_add(item.iid, 'child_evenrow')
                else:
                    self.treeview.tag_add(item.iid, 'parent_evenrow')
            elif row_num % 2 != 0:
                if item.parent == "":
                    self.treeview.tag_add(item.iid, 'child_oddrow')
                else:
                    self.treeview.tag_add(item.iid, 'parent_oddrow')

    @debug(lvl=logging.DEBUG, prefix='')
    def treeview_sort_column(self, col, reverse):
        # self.manager.busy()
        item_list = [(self.treeview.set(k, col), k)
                     for k in self.treeview.get_children('')]
        item_list.sort(reverse=reverse)
        # rearrange items in sorted positions
        for index, (val, k) in enumerate(item_list):
            self.treeview.move(k, '', index)
        self.stripe_rows()
        # reverse sort next time
        self.treeview.heading(
            col, command=lambda: self.treeview_sort_column(col, not reverse))
        # self.manager.not_busy()

    @debug(lvl=logging.DEBUG, prefix='')
    def tv_refresh(self):
        # self.manager.busy()
        item_list = list(self.treeview.get_children(''))
        item_list.sort(key=lambda x: int(x))
        for item_iid, item_obj in sorted(self.item_obj_dict.items()):
            TreeviewConstructor.logger.log(logging.DEBUG,
                                           "Item ID: {0}".format(item_iid))
            # l = self.treeview.get_children('')
            for index, k in enumerate(item_list):
                TreeviewConstructor.logger.log(logging.DEBUG,
                                               "k: {0}".format(k))
                if str(item_iid) == str(k):
                    self.treeview.delete(k)
                    item_obj.index = index
                    self.treeview.insert(item_obj.parent,
                                         item_obj.index,
                                         iid=item_obj.iid,
                                         values=item_obj.values_list)
                    item_list.remove(k)
                    break
        self.stripe_rows()
        # self.manager.not_busy()

    @debug(lvl=logging.DEBUG, prefix='')
    def add_column(self,
                   order=None,
                   col_id=None,
                   hdr_txt="",
                   anchor=tk.W,
                   stretch=tk.YES,
                   minwidth=0,
                   width=50,
                   display=True,
                   desc=None):
        col_obj = TreeColumn(order=order,
                             col_id=col_id,
                             hdr_txt=hdr_txt,
                             anchor=anchor,
                             stretch=stretch,
                             minwidth=minwidth,
                             width=width,
                             display=display,
                             desc=desc)
        self.col_obj_dict[col_obj.col_id] = col_obj

    @debug(lvl=logging.NOTSET, prefix='')
    def add_item(self, iid, parent="", index=tk.END, values_dict=None):
        item_obj = TreeRow(treeview_const=self,
                           iid=iid,
                           parent=parent,
                           index=index,
                           values_dict=values_dict)
        self.item_obj_dict[item_obj.iid] = item_obj

    @debug(lvl=logging.DEBUG, prefix='')
    def columns_from_query(self, query, hide_list=None, pref_order=None):
        if pref_order is None:
            pref_order = []
        if hide_list is None:
            hide_list = []

        col_order = 1
        col_order += len(pref_order)
        TreeviewConstructor.logger.log(
            logging.DEBUG,
            "Column Order Starting Value: {0}".format(str(col_order)))

        for desc in query.column_descriptions:
            name = desc.get('name').replace("'", "").replace('"', "")
            TreeviewConstructor.logger.log(logging.DEBUG,
                                           "Column Name: {0}".format(name))
            disp = True
            if name in hide_list:
                disp = False
            cust_order = col_order
            if name in pref_order:
                cust_order = pref_order.index(name) + 1
            self.add_column(order=cust_order,
                            col_id=name.replace(" ", "_"),
                            hdr_txt=name,
                            display=disp,
                            desc=desc)
            if name not in pref_order:
                col_order += 1

    @debug(lvl=logging.DEBUG, prefix='')
    def rows_from_query(self,
                        query,
                        id_col="line_number",
                        limit=None,
                        parent_col=None):
        counter = 1
        for row in query.all():
            temp_dict = {}
            for col_obj in self.col_obj_dict.values():
                # noinspection PyProtectedMember
                value = row._asdict().get(col_obj.hdr_txt)
                if isinstance(value, str):
                    value.replace("{", "").replace("}", "")
                temp_dict[str(col_obj.order)] = value
            counter += 1
            if counter == limit:
                break
            parent = ""
            if parent_col is not None:
                # noinspection PyProtectedMember
                if str(row._asdict().get(id_col)) != str(
                        row._asdict().get(parent_col)):
                    # noinspection PyProtectedMember
                    parent = str(row._asdict().get(parent_col))
            # noinspection PyProtectedMember
            self.add_item(iid=str(row._asdict().get(id_col)),
                          values_dict=temp_dict,
                          parent=parent)

    @debug(lvl=logging.DEBUG, prefix='')
    def populate_query(self,
                       query,
                       hide_list=None,
                       pref_order=None,
                       id_col="line_number",
                       limit=None,
                       checkwidth=0,
                       parent_col=None):
        the_query = query
        self.columns_from_query(the_query, hide_list, pref_order)
        self.populate_cols(checkwidth=checkwidth)
        self.rows_from_query(the_query, id_col, limit, parent_col)
        self.populate_items()
        self.stripe_rows()
Exemplo n.º 9
0
class CompareApp():

    def __init__(self, master, title):
        self.master = master
        self.master.title(title)
        self.pathList = set([])
        self.fileLists = []
        self.groupFiles = {}
        self.InitUI()

    def InitUI(self):
        self.wholeContainer = tk.Frame(self.master)
        self.wholeContainer.pack()

        button_width = 3  ### (1)
        button_padx = "2m"  ### (2)
        button_pady = "1m"  ### (2)
        buttons_frame_padx = "3m"  ### (3)
        buttons_frame_pady = "2m"  ### (3)
        buttons_frame_ipadx = "3m"  ### (3)
        buttons_frame_ipady = "1m"  ### (3)

        self.buttons_frame = tk.Frame(self.wholeContainer, height=10,
                                      width=980)  ###
        self.buttons_frame.pack(
            side=tk.TOP,  ###
            fill=tk.BOTH,
            expand=tk.YES,
            anchor="w",
            ipadx=buttons_frame_ipadx,
            ipady=buttons_frame_ipady,
            padx=buttons_frame_padx,
            pady=buttons_frame_pady,
        )
        self.button1 = tk.Button(self.buttons_frame, command=self.Add)
        self.button1.configure(text="Add")
        self.button1.focus_force()
        self.button1.configure(
            width=button_width,  ### (1)
            padx=button_padx,  ### (2)
            pady=button_pady  ### (2)
        )
        self.button1.pack(side=tk.LEFT)
        self.button2 = tk.Button(self.buttons_frame, command=self.Remove)
        self.button2.configure(text="Remove")
        self.button2.configure(
            width=6,  ### (1)
            padx=button_padx,  ### (2)
            pady=button_pady  ### (2)
        )
        self.button2.pack(side=tk.LEFT)

        self.btnCompare = tk.Button(self.buttons_frame, command=self.compareFiles)
        self.btnCompare.configure(text="Compare Files")
        self.btnCompare.pack(side=tk.LEFT)
        self.btnCompare.bind("<Return>", self.compareFiles)

        self.btnDel = tk.Button(self.buttons_frame, command=self.deleteSelectedFiles)
        self.btnDel.configure(text="Deleted Selected")
        self.btnDel.pack(side=tk.LEFT)
        self.btnCompare.bind("<Return>", self.deleteSelectedFiles)

        # top frame
        self.top_frame = tk.Frame(self.wholeContainer, relief=tk.RIDGE,
                                  height=100,
                                  width=980,padx=10, pady=10)
        self.top_frame.pack(side=tk.TOP,
                            fill=tk.BOTH,
                            expand=tk.YES,
                            )  ###
        # left frame
        self.left_frame = tk.Frame(self.top_frame, relief=tk.RIDGE,
                                  height=100,
                                  width=500, )
        self.left_frame.grid(row=0, column=0, sticky=("nsew"))
        # right frame
        self.right_frame = tk.Frame(self.top_frame, relief=tk.RIDGE,
                                  height=100,
                                  width=100, )
        self.right_frame.grid(row=0, column=1, sticky=("nsew"))
        self.top_frame.columnconfigure(0, weight=1)
        self.top_frame.rowconfigure(0, weight=1)
        self.top_frame.columnconfigure(1, weight=2)
        self.top_frame.rowconfigure(1, weight=2)


        self.boxScroll = tk.Scrollbar(self.left_frame, orient="vertical", command=self.boxScrollFun)
        self.boxScroll.pack(side=tk.RIGHT,fill=tk.BOTH,expand=tk.NO,)
        self.folderBox = tk.Listbox(self.left_frame, selectmode=tk.MULTIPLE, relief=tk.RIDGE,
                                  height=20,
                                  width=10, yscrollcommand=self.boxScroll.set, )
        self.folderBox.pack(side=tk.LEFT,fill=tk.BOTH,expand=tk.YES,)
        #self.boxScroll.pack(side="right", fill="y")

        self.checkScroll = tk.Scrollbar(self.right_frame, orient="vertical", command=self.checkScrollFun)
        self.checkScroll.pack(side=tk.RIGHT,fill=tk.BOTH,expand=tk.NO,)

        self.checkwithfile = CheckboxTreeview(self.right_frame, height=20, yscrollcommand=self.checkScroll.set)
        self.checkwithfile.pack(side=tk.LEFT,fill=tk.BOTH,expand=tk.YES,)

        # bottom frame
        self.bottom_frame = tk.Frame(self.wholeContainer,
                                     relief=tk.RIDGE,
                                     height=20,
                                     width=970,padx=10, pady=10
                                     )  ###
        self.bottom_frame.pack(side=tk.BOTTOM,
                               fill=tk.BOTH,
                               expand=tk.YES,
                               )  ###


        self.output = tkscrolled.ScrolledText(self.bottom_frame, width=970, height=20, wrap='word')
        self.output.config(state=tk.DISABLED)
        self.output.pack(side=tk.LEFT)


    def boxScrollFun(self, *args):
        return self.folderBox.yview

    def checkScrollFun(self, *args):
        return self.checkwithfile.yview

    def Add(self):

        # otherwise ask the user what new file to open
        pathname = filedialog.askdirectory()
        pathname = os.path.abspath(pathname)
        print(pathname)
        if pathname in self.pathList:
            print("folder already exist" + pathname)
            return
        else:
            self.pathList.add(pathname)
            for id, path in enumerate(self.pathList):
                if path == pathname:
                    self.folderBox.insert(id, pathname)
        if os.path.exists(pathname):
            for i in self.checkwithfile.get_children():
                self.checkwithfile.delete(i)
            #self.fileLists = {}
            self.groupFiles = {}
        else:
            print("folder not found:"+pathname)
            return

        allFiles = set(self.fileLists)
        allFiles.update(self.getAllFileListByPath(pathname))
        #print("allFiles:")
        #print(allFiles)
        self.fileLists = list(allFiles)
        #print("converted fileLists:")
        #print(self.fileLists)
        self.renewFileList()

    def renewFileList(self):
        fileList = [0 for i in range(len(self.fileLists))]
        for i in range(len(self.fileLists)):
            if os.path.exists(self.fileLists[i]):
                fileList[i]=(self.fileLists[i], os.path.getsize(self.fileLists[i]))
            else:
                print("remove not exist file:"+self.fileLists[i])
                fileList.pop(i)
        fileList.sort(key=lambda filename: filename[1], reverse=True)
        for i in range(len(fileList)):
            self.fileLists[i] = fileList[i][0]
        print("file list:")
        print(self.fileLists)
        print("file list end")
        self.groupFileListSameSize()
        print("groupFiles:")
        print(self.groupFiles)
        index=0
        for fileSize, fileList in self.groupFiles.items():
            rootIndex = "r_" + str(index)
            sizeCal = str(fileSize)+'b'
            if fileSize > 1024:

                if fileSize > 1024*1024:
                    if fileSize >1024*1024*1024:
                        if fileSize >1024*1024*1024*1024:
                            sizeCal = "{:.3f}".format(float(fileSize) / (1024*1024*1024*1024)) + 'T'
                        else:
                            sizeCal = "{:.3f}".format(float(fileSize) / (1024*1024*1024)) + 'G'
                    else:
                        sizeCal = "{:.3f}".format(float(fileSize) / (1024*1024)) + 'M'
                else:
                    sizeCal = "{:.3f}".format(float(fileSize) / 1024) + 'k'
            fileNum = len(fileList)
            self.checkwithfile.insert('', "end", rootIndex, text=sizeCal+'('+str(fileNum)+')')

            self.checkwithfile.tag_configure("evenrow", background='white', foreground='black')
            self.checkwithfile.tag_configure("oddrow", background='black', foreground='white')
            for i in range(len(fileList)):
                childIndex = "c_"+str(fileSize)+'_i_'+str(i)
                textC = fileList[i]
                print("textC:"+textC)
                self.checkwithfile.insert(rootIndex, "end", childIndex, text=fileList[i])
            index = index+1

    def Remove(self):
        print("selected:")
        for i in self.folderBox.curselection():
            print(i)
            filePath = self.folderBox.get(i)
            print(filePath)
            self.folderBox.delete(i)
            self.pathList.remove(filePath)
        #selected_text_list = [self.folderBox.get(i) for i in self.folderBox.curselection()]
        #print(selected_text_list)
        for i in self.checkwithfile.get_children():
            self.checkwithfile.delete(i)
        # self.fileLists = {}
        self.groupFiles = {}
        if len(self.pathList) > 0:
            allFiles = set([])
            for pathname in self.pathList:
                allFiles.update(self.getAllFileListByPath(pathname))
            self.fileLists = list(allFiles)
            self.renewFileList()

    def getAllFileListByPath(self, pathname):
        fileSet = set([])
        try:
            if os.path.isdir(pathname):
                fileList = os.listdir(pathname)
                print('pathname')
                print(pathname)
                print('filelist:')
                print(fileList)

                for file in fileList:
                    if not file.startswith('.'):
                        fullPath = pathname + os.sep +  file
                        if os.path.exists(fullPath):
                            if os.path.isdir(fullPath):
                                fileSet.update(self.getAllFileListByPath(fullPath))
                            else:
                                fileSet.add(fullPath)
            elif os.path.exists(pathname):
                fileSet.add(pathname)

        except IOError:
            wx.LogError("Cannot open Directoy '%s'." % pathname)
        return fileSet

    def compareFiles(self):
        print("compare")

        for i in self.checkwithfile.get_children():
            self.checkwithfile.delete(i)
        rootIn = 0
        for fileSize, fileList in self.groupFiles.items():
            rootIndex = "r_" + str(rootIn)
            sizeCal = str(fileSize)+'b'
            if fileSize > 1024:

                if fileSize > 1024*1024:
                    if fileSize >1024*1024*1024:
                        if fileSize >1024*1024*1024*1024:
                            sizeCal = "{:.3f}".format(float(fileSize) / (1024*1024*1024*1024)) + 'T'
                        else:
                            sizeCal = "{:.3f}".format(float(fileSize) / (1024*1024*1024)) + 'G'
                    else:
                        sizeCal = "{:.3f}".format(float(fileSize) / (1024*1024)) + 'M'
                else:
                    sizeCal = "{:.3f}".format(float(fileSize) / 1024) + 'k'
            fileNum = len(fileList)
            self.checkwithfile.insert('', "end", rootIndex, text=sizeCal+'('+str(fileNum)+')')


            indexFileGroup = {}
            groupedSameList = self.compareSameSizeFiles(fileList)

            childIn = 0
            for groupIndex in range(len(groupedSameList)):
                #indexFileGroup[child] = fileList[groupIndex]


                textC = fileList[groupIndex]
                print("textC:"+textC)
                self.checkwithfile.tag_configure("evenrow", background='white', foreground='black')
                self.checkwithfile.tag_configure("oddrow", background='black', foreground='white')
                for i in range(len(groupedSameList[groupIndex])):
                    childIndex = "c_" + str(fileSize) + '_i_' + str(childIn)
                    if groupIndex % 2 == 0:
                        self.checkwithfile.insert(rootIndex, "end", childIndex, text=fileList[i], tags=('evenrow',))
                    else:
                        self.checkwithfile.insert(rootIndex, "end", childIndex, text=fileList[i], tags=('oddrow',))
                    if i > 0:
                        self.checkwithfile.change_state(childIndex, 'checked')


                    childIn = childIn + 1

            rootIn = rootIn+1


    def compareSameSizeFiles(self, fileList):
        groupComparedFiles=[]
        groupMap = []
        compareIndex = ""
        groupComparedFiles.append(groupMap)
        for index in range(len(fileList)):
            fileName = fileList[index]
            groupMap = []
            if len(groupComparedFiles) == 1 and len(groupComparedFiles[0]) == 0:
                groupComparedFiles[0].append(fileName)
                continue

            for i in range(len(groupComparedFiles)):
                (groupIndex, fileIndex) = self.getIndexInGroup(groupComparedFiles, fileName)
                if groupIndex == -1:
                    outputStr = "Comparing: " + groupComparedFiles[i][0] + " and " + fileName + "\n"
                    self.output.config(state=tk.NORMAL)
                    self.output.insert("end", outputStr)
                    self.output.see("end")
                    self.output.config(state=tk.DISABLED)
                    if filecmp.cmp(groupComparedFiles[i][0], fileName):
                        groupComparedFiles[i].append(fileName)
                        break
                    else:
                        groupMap.append(fileName)
                        groupComparedFiles.append(groupMap)


        print("groupComparedFiles:")
        print(groupComparedFiles)
        return groupComparedFiles

    def getIndexInGroup(self, groupList, fileName):
        for groupIndex in range(len(groupList)):
            for fileIndex in range(len(groupList[groupIndex])):
                if groupList[groupIndex][fileIndex] == fileName:
                    return (groupIndex, fileIndex)
        return  (-1, -1)

    def groupFileListSameSize(self):

        if (len(self.fileLists)>0):
            fileSize = os.path.getsize(self.fileLists[0])
            groupList = []
            groupList.append(self.fileLists[0])
            for i in range(len(self.fileLists)-1):
                fileNewSize = os.path.getsize(self.fileLists[i+1])
                if(fileSize != fileNewSize):
                    self.groupFiles[fileSize] = groupList
                    fileSize = fileNewSize
                    groupList = []
                groupList.append(self.fileLists[i+1])
            if len(groupList) > 0:
                self.groupFiles[fileSize] = groupList

    def deleteSelectedFiles(self):
        print("enter deleteSelectedFiles")
        for i in self.checkwithfile.get_children():
            orgLen = len(self.checkwithfile.get_children(i))
            newLen = orgLen
            for item in self.checkwithfile.get_children(i):
                if self.checkwithfile.tag_has("checked", item):
                    fileName = self.checkwithfile.item(item)['text']
                    print(fileName)
                    os.chmod(fileName, stat.S_IWUSR)
                    os.remove(fileName)
                    self.checkwithfile.delete(item)
                    newLen -= 1
            if orgLen > newLen:
                text = self.checkwithfile.item(i)['text'].replace("("+str(orgLen)+")", "("+str(newLen)+")")
                self.checkwithfile.item(i, text=text)
Exemplo n.º 10
0
root = tk.Tk()
root.geometry('600x600')
root.title("Checkbox example")

f1 = tk.Frame(root, width=595, height=595, background='blue', bd=1)
f1.grid(row=0, column=0)
checkingFrame = tk.Frame(f1, width=590, height=590, background='yellow', bd=1)
checkingFrame.grid(row=0, column=0, padx=5, pady=5)
canvas_tree = tk.Canvas(checkingFrame, bg='white')
canvas_tree.grid(row=0, column=0)

main_tree = CheckboxTreeview(canvas_tree, show='tree')
main_tree.column("#0", width=500, minwidth=600, stretch=True)
main_tree.configure(height=10)

main_tree.insert("", "end", "1", text="1" + '2')
main_tree.insert("1", "end", "11", text="11")
main_tree.insert("1",
                 "end",
                 "12",
                 text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')
main_tree.insert("11",
                 "end",
                 "111",
                 text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')
main_tree.insert("",
                 "end",
                 text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')
main_tree.insert("",
                 "end",
                 text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')
Exemplo n.º 11
0
class ScriptManager:
    """
    Open the scripts window manager
    """
    folder_icon = None
    def __init__(self, parent):
        """
            parent: the tkinter parent view to use for this window construction.
        """
        self.parent = parent
        self.app = tk.Toplevel(parent)
        self.app.title("Scripts Manager")
        self.app.resizable(True, True)
        self.rvalue = None
        appFrame = ttk.Frame(self.app)
         #PANED PART
        self.paned = tk.PanedWindow(appFrame, height=300)
        #RIGHT PANE : TAble
        self.viewframe = ttk.Frame(self.paned)
        self.file_tree = CheckboxTreeview(self.viewframe)
        self.file_tree['columns'] = ('name', 'category')
        self.file_tree.heading('#0', text='Name')
        self.file_tree.column("#0", stretch=tk.YES, minwidth=300, width=300)
        self.file_tree.heading('#1', text='Category')
        self.file_tree.column("#1", stretch=tk.YES, minwidth=300, width=300)
        self.file_tree.pack(fill=tk.BOTH, expand=True)
        btn_pane = ttk.Frame(self.viewframe)
        self.execute_icone = tk.PhotoImage(file = Utils.getIcon("execute.png"))
        btn_execute = ttk.Button(btn_pane, text="Execute", image=self.execute_icone, command=self.executedSelectedScripts, tooltip="Execute all selected scripts", style="Toolbutton")        
        btn_execute.pack(side=tk.RIGHT, padx=3, pady=5)
        self.open_folder_icone = tk.PhotoImage(file = Utils.getIcon("folder.png"))
        btn_openPathForUser = ttk.Button(btn_pane, text="Execute", image=self.open_folder_icone, command=self.openPathForUser, tooltip="Open scripts folder", style="Toolbutton")        
        btn_openPathForUser.pack(side=tk.RIGHT, padx=3, pady=5)
        
        btn_pane.pack(fill=tk.X, side=tk.BOTTOM, anchor=tk.E)
        #LEFT PANE : Treeview
        self.frameTw = ttk.Frame(self.paned)
        self.treevw = ttk.Treeview(self.frameTw)
        self.treevw.pack()
        scbVSel = ttk.Scrollbar(self.frameTw,
                                orient=tk.VERTICAL,
                                command=self.treevw.yview)
        self.treevw.configure(yscrollcommand=scbVSel.set)
        self.treevw.grid(row=0, column=0, sticky=tk.NSEW)
        scbVSel.grid(row=0, column=1, sticky=tk.NS)
        self.treevw.grid(row=0, column=0, sticky=tk.NSEW)
        scbVSel.grid(row=0, column=1, sticky=tk.NS)
        self.paned.add(self.frameTw)
        self.paned.add(self.viewframe)
        self.paned.pack(fill=tk.BOTH, expand=1)
        self.frameTw.rowconfigure(0, weight=1) # Weight 1 sur un layout grid, sans ça le composant ne changera pas de taille en cas de resize
        self.frameTw.columnconfigure(0, weight=1) # Weight 1 sur un layout grid, sans ça le composant ne changera pas de taille en cas de resize

        appFrame.pack(fill=tk.BOTH, ipady=10, ipadx=10, expand=True)

        self.treevw.bind("<<TreeviewSelect>>", self.onTreeviewSelect)
        try:
            self.app.wait_visibility()
            self.app.focus_force()
            self.app.lift()
        except tk.TclError:
            pass
        self.refreshUI()

    def refreshUI(self):
        for widget in self.treevw.winfo_children():
            widget.destroy()
        script_dir = self.getScriptsDir()
        if self.__class__.folder_icon is None:
            self.__class__.folder_icon = ImageTk.PhotoImage(Image.open(Utils.getIcon("folder.png")))
        parent = self.treevw.insert("", "end", " ", text="Scripts", image=self.__class__.folder_icon, open=True)
        self.treevw.focus(parent)
        self.treevw.selection_set(parent)
        for root, subFolders, files in os.walk(script_dir):
            root_name = root.replace(script_dir, "")
            for folder in subFolders:
                if folder.startswith("__") or folder.endswith("__"):
                    continue
                folder_iid = os.path.join(root_name, folder)
                parent_node = parent if root_name == "" else root_name
                self.treevw.insert(parent_node, "end", folder_iid, text=folder, image=self.__class__.folder_icon)
        self.openScriptFolderView()
        
    def getScriptsDir(self):
        return os.path.join(Utils.getMainDir(), "scripts/")

    def onTreeviewSelect(self, _event=None):
        
        selec = self.treevw.selection()
        if len(selec) == 0:
            return None
        item = selec[0]
        self.openScriptFolderView(str(item))

    def openScriptFolderView(self, script_folder=""):
        full_script_path = os.path.join(self.getScriptsDir(), script_folder.strip())
        script_shown = set()
        self.file_tree.delete(*self.file_tree.get_children())

        for root, _, files in os.walk(full_script_path):
            for file in files:
                filepath = root + '/' + file
                if file.endswith(".py"):
                    script_shown.add(filepath)
        scripts_list = sorted(script_shown)
        script_dir = self.getScriptsDir()
        for script in scripts_list:
            scriptName = os.path.basename(script)
            category_name = os.path.dirname(script.replace(script_dir, ""))
            self.file_tree.insert("", "end", script, text=scriptName, values=(category_name))
        

    def executedSelectedScripts(self):
        for selected in self.file_tree.get_checked():
            self.executeScript(selected)

    def executeScript(self, script_path):
        script_dir = self.getScriptsDir()
        category_name = os.path.dirname(script_path.replace(script_dir, ""))
        script_name = ".".join(os.path.splitext(os.path.basename(script_path))[:-1])
        module = os.path.join("pollenisatorgui/scripts/",category_name, script_name).replace("/", '.')
        imported = importlib.import_module(module)
        success, res = imported.main(APIClient.getInstance())
        if success:
            tk.messagebox.showinfo("Script finished", f"Script {script_name} finished.\n{res}")
        else:
            tk.messagebox.showwarning("Script failed", f"Script {script_name} failed.\n{res}")

    def openPathForUser(self):
        selection = self.treevw.selection()
        if selection:
            folder = os.path.join(self.getScriptsDir(), selection[0])
        else:
            folder = self.getScriptsDir()
        Utils.openPathForUser(folder)
Exemplo n.º 12
0
class main_Tab:
    def __init__(self, master, main_path=''):
        self.main_path = main_path
        self.master = master
        self.modules_config = {}  #{module_name : }
        self.modules = {}

        self.fio = ''
        self.org = ''

        #Профили аудита
        self.profiles = {}
        self.current_profile_options = {}

        #Левый фрейм включает данные об аудиторе и о существующих профилях
        leftFrame = ttk.Frame(master)
        self.auditor_Frame = ttk.LabelFrame(leftFrame, text='Данные аудитора')
        self.profiles_Frame = VerticalScrolledFrame(leftFrame,
                                                    text='Профили аудита')

        #Правый фрейм включает редактор текущего профиля и кнопку запуска аудита
        rightFrame = ttk.Frame(master)
        self.current_Frame = ttk.LabelFrame(rightFrame, text='Текущий профиль')
        self.btn_Frame = ttk.Frame(rightFrame)

        #Область данных об аудиторе
        fio_Label = ttk.Label(self.auditor_Frame, text='ФИО')
        self.fio_Entry = ttk.Entry(self.auditor_Frame, font=16, width=30)
        self.fio_Label = ttk.Label(self.auditor_Frame, font=16, width=30)
        org_Label = ttk.Label(self.auditor_Frame, text='Организация')
        self.org_Entry = ttk.Entry(self.auditor_Frame, font=16, width=30)
        self.org_Label = ttk.Label(self.auditor_Frame, font=16, width=30)
        self.fio_OK_btn = ttk.Button(self.auditor_Frame,
                                     text='OK',
                                     width=5,
                                     command=self.accept_auditor)

        fio_Label.grid(row=1, column=0, sticky='new', padx=10)
        self.fio_Entry.grid(row=2, column=0, sticky='nsew', padx=10)
        org_Label.grid(row=3, column=0, sticky='new', padx=10)
        self.org_Entry.grid(row=4, column=0, sticky='nsew', padx=10)
        self.fio_OK_btn.grid(row=5, column=0, sticky='se', padx=10)

        self.profileView = CheckboxTreeview(self.current_Frame)
        self.save_audit_btn = ttk.Button(self.btn_Frame,
                                         text='Сохранить профиль',
                                         command=self.save_btn_click)
        self.run_audit_btn = ttk.Button(self.btn_Frame,
                                        text='Запустить аудит',
                                        command=self.run_audit)

        self.ysb = ttk.Scrollbar(self.current_Frame,
                                 orient='vertical',
                                 command=self.profileView.yview)
        self.profileView.configure(yscroll=self.ysb.set)
        ttk.Style().configure('Vertical.TScrollbar',
                              troughcolor='#f6f4f2',
                              relief=tk.GROOVE)
        ttk.Style().configure('Treeview', background="#ffffff")
        ttk.Style().configure('Frame', background="#f6f4f2")

        #Размещения на фреймах
        leftFrame.pack(side=tk.LEFT, anchor='nw', fill=tk.Y)
        rightFrame.pack(side=tk.LEFT, anchor='nw', expand=1, fill=tk.BOTH)

        self.auditor_Frame.pack(side=tk.TOP,
                                anchor='nw',
                                padx=5,
                                pady=5,
                                fill=tk.X)
        self.profiles_Frame.pack(side=tk.TOP,
                                 anchor='sw',
                                 padx=5,
                                 pady=10,
                                 fill=tk.BOTH,
                                 expand=1)

        self.current_Frame.pack(side=tk.TOP,
                                anchor='nw',
                                padx=5,
                                pady=5,
                                fill=tk.BOTH,
                                expand=1)
        self.btn_Frame.pack(side=tk.TOP, anchor='nw', fill=tk.X)

        self.ysb.pack(side=tk.RIGHT, anchor='n', fill=tk.Y)
        self.profileView.pack(side=tk.TOP, anchor='nw', fill=tk.BOTH, expand=1)
        self.save_audit_btn.pack(side=tk.LEFT, anchor='sw', padx=5, pady=5)
        self.run_audit_btn.pack(side=tk.LEFT,
                                anchor='se',
                                padx=5,
                                pady=5,
                                fill=tk.X,
                                expand=1)

        self.auditor_Frame.grid_rowconfigure(2, minsize=30)
        self.loadProfiles()
        self.profileView.bind("<Button-1>", self.check_uncheck_item, True)

    def run_audit(self):
        for tab_name, tab in self.modules.items():
            tab.run_audit()

    def sync_vars(self):
        for tab_name, tab in self.modules.items():
            if type(self.current_profile_options[tab_name][1]) != type({}):
                i = 0
                for var in tab.vars:
                    var.set(self.current_profile_options[tab_name][1][i])
                    i += 1
            else:
                i = len(tab.vars) - 1
                for second_tab_name, second_tab in self.current_profile_options[
                        tab_name][1].items():
                    for j in range(len(second_tab[1]) - 1, -1, -1):
                        tab.vars[i].set(second_tab[1][j])
                        i -= 1

    def accept_auditor(self):
        if self.fio_OK_btn.cget('text') == 'OK':
            self.fio = self.fio_Entry.get()
            self.org = self.org_Entry.get()

            self.fio_OK_btn.configure(text='Изменить', width=10)

            self.fio_Entry.grid_remove()
            self.org_Entry.grid_remove()

            self.fio_Label.configure(text=self.fio)
            self.org_Label.configure(text=self.org)
            self.fio_Label.grid(row=2, column=0, sticky='nsew', padx=10)
            self.org_Label.grid(row=4, column=0, sticky='nsew', padx=10)
        else:
            self.fio_OK_btn.configure(text='OK', width=5)
            self.fio_Entry.grid()
            self.org_Entry.grid()

            self.fio_Label.grid_remove()
            self.org_Label.grid_remove()

    def loadProfiles(self):
        for child in self.profiles_Frame.interior.winfo_children():
            child.destroy()
        #self.profiles_Frame.pack(side=tk.TOP, anchor='sw', padx=5, pady = 10, fill=tk.BOTH, expand=1)
        try:
            with open(self.main_path + '/profiles.json') as file:
                self.profiles = json.load(file)
        except:
            with open(self.main_path + '/profiles.json', 'w') as file:
                json.dump(self.profiles, file)

        prof_count = len(self.profiles)
        self.var = tk.IntVar()
        for i in range(prof_count):
            tk.Radiobutton(self.profiles_Frame.interior,
                           variable=self.var,
                           value=i,
                           indicator=0,
                           height=3,
                           text=list(self.profiles.keys())[i],
                           selectcolor="#f19572",
                           activebackground="#f19572",
                           command=self.changeCurrentProfile).pack(side=tk.TOP,
                                                                   anchor='nw',
                                                                   fill=tk.X,
                                                                   padx=5,
                                                                   pady=2)

    def dumpProfiles(self):
        with open(self.main_path + '/profiles.json', 'w') as file:
            json.dump(self.profiles, file)

    def changeCurrentProfile(self):
        currentProfileName = list(self.profiles.keys())[self.var.get()]
        self.current_profile_options = copy.deepcopy(
            self.profiles[currentProfileName])
        self.profileView.heading('#0',
                                 text=list(
                                     self.profiles.keys())[self.var.get()],
                                 anchor='w')
        self.initTree()
        self.sync_vars()
        #self.profiles_Label.configure(text=self.var.get())

    def save_btn_click(self):
        self.saveDialog = tk.Toplevel()
        save_frame = ttk.Frame(self.saveDialog)
        self.saveDialog.focus_set()

        width = self.master.winfo_screenwidth() // 5 + 96
        height = self.master.winfo_screenheight() // 5
        dw = (self.master.winfo_screenwidth() - width) // 2
        dh = (self.master.winfo_screenheight() - height) // 2
        self.saveDialog.geometry('{}x{}+{}+{}'.format(width, height, dw, dh))

        self.saveDialog.resizable(False, False)
        self.saveDialog.title('Сохранение профиля')

        # Настройка виджетов в окне ввода пароля
        save_Label = ttk.Label(save_frame, text='Названия профиля')
        self.save_Entry = ttk.Entry(save_frame, font=16)
        save_Btn = ttk.Button(save_frame, text='Сохранить', width=15)

        self.save_Entry.bind('<Return>', self.save_click)
        save_Btn.bind('<Button-1>', self.save_click)

        save_Label.grid(row=1, column=0)
        self.save_Entry.grid(row=2, column=0, padx=10, sticky='nsew')
        save_Btn.grid(row=3, column=0, padx=10, pady=20, sticky='e')

        save_frame.pack(fill=tk.BOTH)
        save_frame.grid_rowconfigure(1, minsize=height // 3)
        save_frame.grid_rowconfigure(2, minsize=30)
        save_frame.grid_columnconfigure(0, minsize=width)
        self.save_Entry.focus_set()

    def save_click(self, event):
        """Функция-обработчик нажатия кнопки """
        profile_name = self.save_Entry.get()
        self.profiles[profile_name] = self.current_profile_options
        self.dumpProfiles()
        self.loadProfiles()
        self.saveDialog.destroy()
        self.initTree()

    def initTree(self):
        if self.current_profile_options == {}:
            self.current_profile_options = dict(
                self.profiles["Профиль по умолчанию"])

        for (key, value) in self.current_profile_options.items():
            if self.modules_config.__contains__(key):
                if not self.profileView.exists(key):
                    self.profileView.insert("", "end", key, text=key)

                self.profileView.change_state(key, value[0])
                value = value[1]

                if type(value) == type("1"):
                    i = 0
                    for func_key in self.modules_config[key][0].keys():
                        func_key = func_key.replace('\n', ' ')

                        if not self.profileView.exists(key + func_key + "_" +
                                                       str(i)):
                            self.profileView.insert(key,
                                                    "end",
                                                    key + func_key + "_" +
                                                    str(i),
                                                    text=func_key)

                        if value[i] == '0':
                            self.profileView.change_state(
                                key + func_key + "_" + str(i), 'unchecked')
                        if value[i] == '1':
                            self.profileView.change_state(
                                key + func_key + "_" + str(i), 'checked')
                        i += 1
                else:
                    j = 0
                    for (second_key, second_value) in dict(value).items():

                        if not self.profileView.exists(second_key):
                            self.profileView.insert(key,
                                                    "end",
                                                    second_key,
                                                    text=second_key)

                        self.profileView.change_state(second_key,
                                                      second_value[0])
                        second_value = second_value[1]

                        if type(value[second_key][1]) == type("1"):
                            i = 0
                            for func_key in self.modules_config[key][0][
                                    j].keys():
                                func_key = func_key.replace('\n', ' ')

                                if not self.profileView.exists(second_key +
                                                               func_key + "_" +
                                                               str(i)):
                                    self.profileView.insert(
                                        second_key,
                                        "end",
                                        second_key + func_key + "_" + str(i),
                                        text=func_key)

                                if value[second_key][1][i] == '0':
                                    self.profileView.change_state(
                                        second_key + func_key + "_" + str(i),
                                        'unchecked')
                                if value[second_key][1][i] == '1':
                                    self.profileView.change_state(
                                        second_key + func_key + "_" + str(i),
                                        'checked')
                                i += 1
                        j += 1

    def check_uncheck_item(self, event):
        x, y, widget = event.x, event.y, event.widget
        elem = widget.identify("element", x, y)
        if "image" in elem:
            # a box was clicked
            item = self.profileView.identify_row(y)
            children = self.profileView.get_children(item)
            parents = []
            parent = widget.parent(item)
            i = 0
            while parent != '':
                parents.append(parent)
                parent = widget.parent(parent)
            if parents and children == ():
                tag = self.profileView.item(parents[-1], "tags")
                self.current_profile_options[parents[-1]][0] = tag[0]
                if len(parents) == 2:
                    tag = self.profileView.item(parents[0], "tags")
                    self.current_profile_options[parents[-1]][1][
                        parents[-2]][0] = tag[0]
                    tag = self.profileView.item(item, "tags")

                    i = int(item.split('_')[1])
                    varL = self.current_profile_options[parents[-1]][1][
                        parents[-2]][1][0:i]
                    varR = self.current_profile_options[parents[-1]][1][
                        parents[-2]][1][i + 1:]

                    if "checked" in tag:
                        self.current_profile_options[parents[-1]][1][
                            parents[-2]][1] = varL + '1' + varR
                    else:
                        self.current_profile_options[parents[-1]][1][
                            parents[-2]][1] = varL + '0' + varR
                else:
                    tag = self.profileView.item(item, "tags")

                    i = int(item.split('_')[1])
                    varL = self.current_profile_options[parents[-1]][1][0:i]
                    varR = self.current_profile_options[parents[-1]][1][i + 1:]

                    if "checked" in tag:
                        self.current_profile_options[
                            parents[-1]][1] = varL + '1' + varR
                    else:
                        self.current_profile_options[
                            parents[-1]][1] = varL + '0' + varR
            else:
                tag = self.profileView.item(item, "tags")
                self.current_profile_options[item][0] = tag[0]
                profile_1 = ''
                for child in self.profileView.get_children(item):
                    children = self.profileView.get_children(child)
                    if children != ():
                        tag = self.profileView.item(child, "tags")
                        self.current_profile_options[item][1][child][0] = tag[
                            0]
                        profile = ''
                        for s_child in self.profileView.get_children(child):
                            tag = self.profileView.item(s_child, "tags")
                            if 'checked' in tag:
                                profile += '1'
                            else:
                                profile += '0'
                        self.current_profile_options[item][1][child][
                            1] = profile
                    else:
                        tag = self.profileView.item(child, "tags")
                        if 'checked' in tag:
                            profile_1 += '1'
                        else:
                            profile_1 += '0'
                        self.current_profile_options[item][1] = profile_1
        self.sync_vars()
Exemplo n.º 13
0
def Main():
    window = tkinter.Tk()
    window.title('Security Checker')  # Title
    window.geometry('500x350+450+200')  # Resolution
    window['padx'] = 8
    # window.iconbitmap(default="Appwheel.ico")  # App icon
    title_font = tkfont.Font(family='Arial', size=10,
                             weight="bold")  # Fonts within the App
    label1 = ttk.Label(text="Check the boxes:",
                       font=title_font)  # Writings within the App
    label1.grid(row=0, column=0, sticky="nw", pady=8)

    window.grid_columnconfigure(0, weight=1)
    window.grid_columnconfigure(1, weight=1)
    window.grid_columnconfigure(2, weight=3)
    window.grid_columnconfigure(3, weight=2)
    window.grid_columnconfigure(4, weight=2)
    window.grid_rowconfigure(0, weight=1)
    window.grid_rowconfigure(1, weight=10)
    window.grid_rowconfigure(2, weight=2)
    window.grid_rowconfigure(3, weight=3)
    window.grid_rowconfigure(4, weight=3)

    tree = CheckboxTreeview  # Variable tree equals tree view
    # Edit dictionaries as you like
    # Dict #1
    cisco = {
        1: "enable secret",
        2: "aaa new-model",
        3: "service-password encryption",
        4: "ip ssh version 2",
        5: "motd",
        6: "no logging console",
        7: "no logging monitor",
        8: "vtp password"
    }
    # Dict 2
    smbv1_patch = {
        100: "KB4012598",
        101: "KB4012212",
        102: "KB4012215",
        103: "KB4012213",
        104: "KB4012216",
        105: "KB4012214",
        106: "KB4012217",
        107: "KB4012606",
        108: "KB4013198",
        109: "KB4013429"
    }

    # What should not be present in a configuration files
    should_not_be = [
        "enable password", "snmp-server community public",
        "transport input telnet", "EnableSMB1Protocol              : True"
    ]

    scrollbar1 = ttk.Scrollbar(window, orient="vertical",
                               command=tree.yview)  # Scroll bar
    scrollbar1.grid(row=1, column=6, sticky='nse')

    tree = CheckboxTreeview(yscrollcommand=scrollbar1)
    tree.grid(column=0, columnspan=6, row=1, sticky="news")  # Tree position

    tree.insert("", "end", "1", text="1. CISCO Hardening")
    tree.insert("1", "end", "sub0", text="1.1 Generic configs")
    tree.insert("sub0", "end", cisco[1], text="1.1.1 Password Hash")
    tree.insert("sub0", "end", cisco[3], text="1.1.2 Password Encryption")
    tree.insert("sub0", "end", cisco[2], text="1.1.3 AAA configuration")
    tree.insert("sub0", "end", cisco[4], text="1.1.4 SSH version 2")
    tree.insert("sub0", "end", cisco[5], text="1.1.5 MOTD")
    tree.insert("sub0", "end", cisco[8], text="1.1.6 VTP Password")
    tree.insert("sub0", "end", cisco[6], text="1.1.7 No logging console")
    tree.insert("sub0", "end", cisco[7], text="1.1.8 No logging monitor")

    tree.insert("", "end", "2", text="2. Microsoft SMBv1 Patching Check")
    tree.insert("2",
                "end",
                smbv1_patch[100],
                text="2.1 Windows Vista & Server 2008 (KB4012598)")
    tree.insert("2", "end", "sub10", text="2.2 Windows 7 & Server 2008 R2")
    tree.insert("sub10", "end", smbv1_patch[101], text="2.2 KB4012212")
    tree.insert("sub10", "end", smbv1_patch[102], text="2.3 KB4012215")

    tree.insert("2",
                "end",
                "sub11",
                text="2.4 Windows 8.1 & Server 2012 & 2012 R2")
    tree.insert("sub11", "end", smbv1_patch[103], text="2.4 KB4012213")
    tree.insert("sub11", "end", smbv1_patch[104], text="2.5 KB4012216")
    tree.insert("sub11", "end", smbv1_patch[105], text="2.6 KB4012214")
    tree.insert("sub11", "end", smbv1_patch[106], text="2.7 KB4012217")

    tree.insert("2", "end", "sub12", text="2.8 Windows 10 & Server 2016")
    tree.insert("sub12", "end", smbv1_patch[107], text="2.8 KB4012606")
    tree.insert("sub12", "end", smbv1_patch[108], text="2.7 KB4013198")
    tree.insert("sub12", "end", smbv1_patch[109], text="2.8 KB4013429")

    button2 = ttk.Button(text="Quit", command=sys.exit)  # Close Button
    button2.grid(row=4, column=0, sticky='ws', padx=10,
                 pady=10)  # Close button position

    checked_boxes = list()  # List for appending selected boxes
    lines_in_conf_file = list()  # List for appending the read file
    passed = str('Passed\t\t')
    not_passed = str('Not Passed\t\t')

    def box_select(just):  # Function for appending selected boxes
        checked_boxes.append(tree.get_checked())

    tree.bind('<<TreeviewSelect>>', box_select)

    def file_open():

        if len(tree.get_checked()) > 0:
            readfile = filedialog.askopenfilename(initialdir="/",
                                                  title="Select "
                                                  "configuration"
                                                  " file",
                                                  filetypes=(("txt "
                                                              "files",
                                                              "*.txt *.html"),
                                                             ("all "
                                                              "files", "*.*")))

            try:
                with open(readfile, "r", encoding='utf-8') as opened_file:
                    for i in opened_file:
                        pass
                    encodings = 'utf-8'
            except UnicodeDecodeError:
                encodings = 'utf-16'

            with open(readfile, "r", encoding=encodings) as opened_file:
                for read_line in opened_file:
                    lines_in_conf_file.append(read_line.strip('\n'))
                with open("temp.txt", "a") as conf:  # Opens file --ONCE--
                    for clause in checked_boxes[-1]:  # Loops over selection
                        for line in lines_in_conf_file:  # Loops over conf file
                            if clause in line:  # Checks what equals between loops
                                conf.write("{}".format(passed) + clause +
                                           "\n")  # Writing them into a file
                                break  # Ends IF statement and continues with
                        else:  # a loop on a conf file
                            if clause in should_not_be:  # Checks if selection in not wanted list
                                conf.write(
                                    "{}".format(passed) + clause +
                                    "\n")  # if yes, writes to a file "PASSED"
                            else:
                                conf.write(
                                    "{}".format(not_passed) + clause +
                                    "\n")  # if not, writes to a file "NOT
                                # PASSED"

                checked_configs()

        else:
            pop_up_msg()

    def checked_configs():
        checked = tkinter.Tk()
        # checked.iconbitmap(default="Appwheel.ico")  # App icon
        checked.geometry('650x500+650+300')  # Resolution
        checked.wm_title("Security Checker")

        checked.grid_columnconfigure(0, weight=1)
        checked.grid_columnconfigure(1, weight=1)
        checked.grid_columnconfigure(2, weight=3)
        checked.grid_columnconfigure(3, weight=2)
        checked.grid_columnconfigure(4, weight=2)
        checked.grid_rowconfigure(0, weight=1)
        checked.grid_rowconfigure(1, weight=10)
        checked.grid_rowconfigure(2, weight=2)
        checked.grid_rowconfigure(3, weight=3)
        checked.grid_rowconfigure(4, weight=3)

        label2 = ttk.Label(checked,
                           text='Security check report:',
                           font=title_font)
        label2.grid(row=0, column=0, sticky='ew', padx=10, pady=10)

        button3 = ttk.Button(checked, text="Quit", command=sys.exit)
        button3.grid(row=4, column=0, sticky='ws', padx=10, pady=10)

        def save_report_to_file():
            save_file = filedialog.asksaveasfile(mode='w',
                                                 defaultextension=".txt",
                                                 initialdir="/",
                                                 title="Save "
                                                 "report",
                                                 filetypes=(("txt "
                                                             "files", "*.txt"),
                                                            ("all "
                                                             "files", "*.*")))
            if save_file:
                with open('temp.txt', 'r') as temp_file:
                    for i in temp_file:
                        save_file.write(i)
                    else:
                        return

        button4 = ttk.Button(checked,
                             text="Save to..",
                             command=save_report_to_file)
        button4.grid(row=4, column=5, sticky='es', padx=10, pady=10)

        checked = Text(checked)
        checked.grid(column=0, columnspan=6, row=1, sticky="news")
        checked.insert('1.0', ''.join(open("temp.txt", "r")))

        checked.mainloop()

    def pop_up_msg():
        popup = tkinter.Tk()
        # popup.iconbitmap(default="Appwheel.ico")  # App icon
        popup.wm_title("Security Checker")

        label3 = ttk.Label(
            popup,
            text='Please select at least 1 checkbox to continue',
            font=title_font)
        label3.grid(row=0, column=0, sticky='ew', padx=10, pady=10)

        button5 = ttk.Button(popup, text="Okay", command=popup.destroy)
        button5.grid(row=1, column=0, padx=10, pady=10)

        popup.mainloop()

    button1 = ttk.Button(text="Next", command=file_open)
    button1.grid(row=4, column=5, sticky='es', padx=10,
                 pady=10)  # Open's Browse Button

    window.mainloop()