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()
Пример #2
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()
 def test_checkboxtreeview_events(self):
     tree = CheckboxTreeview(self.window)
     tree.pack()
     self.window.update()
     tree.event_generate("<1>", x=10, y=10)
     self.window.update()
 def test_checkboxtreeview_init(self):
     tree = CheckboxTreeview(self.window)
     tree.pack()
     self.window.update()
Пример #6
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()
Пример #7
0
class search_display(cache_maintenance):

	#########################
	#   Field Populators	#
	#########################

	def taxon_branch_builder(self,database,key):
	# Populates tree branches with data
		
		# Set Taxon Dictionary
		dictionary = database[key]
		
		# Create Root
		top=self.search_tree.insert("", "end", dictionary['iid'], text=dictionary['name'], values=(dictionary['type'],dictionary['definition']),open = True)

		def individual_branch_builder(child_dictionary,parent_branch):
		# Recursive Function to Go Through an Unknown Number of Layers

			alpha_child_taxonomy = self.database_alphabetiser(child_dictionary)	
						
			for taxon in alpha_child_taxonomy:	
			
				# Create Lambda Dictionary
				x, d = -1, {}

				# Go Through Every Key (Numerical Values) in Current "children" Dictionary
				for new_key,new_dictionary in child_dictionary.items():

					if new_dictionary['iid'] == taxon:
				
						# Advance Branch Lambda Variable
						x = x + 1

						# Create New Branch
						d[x+1]=self.search_tree.insert(parent_branch, "end", new_dictionary['iid'], text=new_dictionary['name'],values=(new_dictionary['type'],new_dictionary['definition']),open = False)

						# Re-Run Recursive Function with New "children" Dictionary
						individual_branch_builder(new_dictionary['children'],d[x+1])

		# Begin Recursive Function
		individual_branch_builder(dictionary['children'],top)


	#########################
	#   Event Processing	#
	#########################		

	def get_checked_annotations(self):   
		self.annotation_list = (self.search_tree.get_checked())
		for annotation in self.annotation_list:

			# If that Item has a Parent and that Parent is not Already in the List
			if self.search_tree.parent(annotation) != "" and self.search_tree.parent(annotation) not in self.annotation_list:

				# Add Parent Item to the List
				self.annotation_list.append(self.search_tree.parent(annotation))
		   
		self.taxon_list_displayer(self.taxonomy,self.annotation_list)

	def result_viewer(self,event):		
		segment_event_data = event.widget
		segment_selection = segment_event_data.curselection()[0]
		selection_coordinates = self.export_list[segment_selection]	
		
		self.segment_displayer(selection_coordinates)
		
	def taxon_informer(self,event):
	# Send Selected ID to Iterator

		# Get Selected ID from Click Event
		self.clicked_item = self.search_tree.identify('item',event.x,event.y)

		# Send to iid_iterator
		self.iid_iterator(self.taxonomy,self.annotation_list,self.taxon_list_displayer)

	#####################
	#   Panel Display   #
	#####################		
	
	def note_displayer(self,selection_coordinates):
	# Display notes on segment
	
		self.note_text = Text(self.pane_two_bottom_right, wrap=WORD)
		self.note_text.configure(font=(10))
		self.note_text.pack(anchor="nw", expand=Y, fill=BOTH)
		try:
			full_note = self.database[selection_coordinates[0]]['items'][selection_coordinates[1]]['segments'][selection_coordinates[2]]['nisaba:notes']
		except(KeyError):
			pass
		else:
			note = full_note[0]
			signature = full_note[1]
			date = '{}/{}/{}'.format(full_note[2][6:8],full_note[2][4:6],full_note[2][:4])
			
			notes = '{} -{} ({})'.format(note,signature,date)
			self.note_text.insert("0.0",notes)
	
	def segment_displayer(self,selection_coordinates):
	
		self.pane_two_bottom_left.destroy()		
		self.pane_two_bottom_right.destroy()		
		self.pane_two_bottom_left = ttk.Frame(self.search_window)
		self.pane_two_bottom_left.place(relx=.25, rely = .45, relwidth=.32, relheight=.4)
		self.pane_two_bottom_right = ttk.Frame(self.search_window)
		self.pane_two_bottom_right.place(relx=.65, rely = .45, relwidth=.32, relheight=.4)
		
		self.collection_index = selection_coordinates[0]
		self.item_index = selection_coordinates[1]
		self.segment_index = selection_coordinates[2]
	
		# If the Segment is Text
		if self.database[self.collection_index]['items'][self.item_index]['item_type'] == 't':
		
			# Pull segmentation data
			start = self.database[self.collection_index]['items'][self.item_index]['segments'][self.segment_index]['start']
			end = self.database[self.collection_index]['items'][self.item_index]['segments'][self.segment_index]['end']

			# Create Text Box
			self.transcription_text = Text(self.pane_two_bottom_left, wrap=WORD)

			# Populate Text Box
			
			# Pull Transcription from self.database
			self.transcription_words = self.database[self.collection_index]['items'][self.item_index]['transcription'][0].split()
			
			# Get Snippets
			pre_start = start-20 if start > 20 else 0
			
			pre_transcription = ' '.join(self.transcription_words[pre_start:start]) + " "
			transcription = ' '.join(self.transcription_words[start:end]) + " "
			post_transcription = ' '.join(self.transcription_words[end:end+20])

			# Set Highlighting / Background Colours
			self.transcription_text.tag_config("faded", foreground="light gray", font=(10))
			self.transcription_text.tag_config("normal", font=(10))

			# Clear Existing Text
			self.transcription_text.insert(END,"...")
			self.transcription_text.delete("0.0",END)

			# Insert Snippet Text
			self.transcription_text.insert("0.0",pre_transcription[1:],('faded'))
			self.transcription_text.insert(END,transcription,('normal'))
			self.transcription_text.insert(END,post_transcription, ('faded'))

			# Display Textbox
			self.transcription_text.pack(anchor="nw", expand=Y, fill=BOTH)

		# If the Segment is an Image
		elif self.database[self.collection_index]['items'][self.item_index]['item_type'] == 'i':

			# Pull segmentation data
			self.top = int(self.database[self.collection_index]['items'][self.item_index]['segments'][self.segment_index]['top'])
			self.left = int(self.database[self.collection_index]['items'][self.item_index]['segments'][self.segment_index]['left'])
			self.bottom = int(self.database[self.collection_index]['items'][self.item_index]['segments'][self.segment_index]['bottom'])
			self.right = int(self.database[self.collection_index]['items'][self.item_index]['segments'][self.segment_index]['right'])
			
			# Create Image Canvas
			self.segment_imageCanvas = Canvas(self.pane_two_bottom_left)

			try:
				# Set image file
				self.filename = str(Path(self.raw_data_images_path) / self.database[self.collection_index]['items'][self.item_index]['image_file'])
				self.segment_image = PIL.Image.open(self.filename)
				
			except(FileNotFoundError):
				# Use stand in if file is not found
				self.filename = str(Path(self.raw_data_images_path) / 'sample.jpg')
				self.segment_image = PIL.Image.open(self.filename)
				
			# Find Image Size
			[self.segment_imageSizeWidth, self.segment_imageSizeHeight] = self.segment_image.size
			self.segment_image_original_ratio = self.segment_imageSizeHeight / self.segment_imageSizeWidth

			# Find Crop Coordinates
			self.segment_top_x_coordinate =  int(self.left*self.segment_imageSizeWidth / 100)
			self.segment_top_y_coordinate = int(self.top*self.segment_imageSizeHeight / 100)
			self.segment_bottom_x_coordinate = int(self.right*self.segment_imageSizeWidth / 100)
			self.segment_bottom_y_coordinate = int(self.bottom*self.segment_imageSizeHeight / 100)

			# Crop Image
			self.segment_image = self.segment_image.crop((self.segment_top_x_coordinate,
														  self.segment_top_y_coordinate,
														  self.segment_bottom_x_coordinate,
														  self.segment_bottom_y_coordinate))

			# Compute Ratios
			[self.cropped_image_width, self.cropped_image_height] = self.segment_image.size
			self.cropped_image_ratio_h = self.cropped_image_height / self.cropped_image_width
			self.cropped_image_ratio_w = self.cropped_image_width /self.cropped_image_height
			
			# Implement Ratios for Portrait Images 
			if self.cropped_image_width < self.cropped_image_height:
				self.segment_sizeRatio = 600 / self.cropped_image_height
				self.segment_newImageSizeHeight = int(self.cropped_image_height*self.segment_sizeRatio)
				self.segment_newImageSizeWidth = int(self.segment_newImageSizeHeight*self.cropped_image_ratio_w)
			
			# Implement Ratios for Landscape Images
			else:
				self.segment_sizeRatio = 600 / self.cropped_image_width
				self.segment_newImageSizeWidth = int(self.cropped_image_width*self.segment_sizeRatio)
				self.segment_newImageSizeHeight = int(self.segment_newImageSizeWidth*self.cropped_image_ratio_h)

			# Resize Image to Fit Canvas
			self.segment_image = self.segment_image.resize((self.segment_newImageSizeWidth, self.segment_newImageSizeHeight), PIL.Image.ANTIALIAS)

			# Prepare Image for Insertion
			self.segment_photoImg = PIL.ImageTk.PhotoImage(self.segment_image)

			# Display Image Canvas
			self.segment_imageCanvas.config(width=self.segment_newImageSizeWidth+10, height = self.segment_newImageSizeHeight+10, background="light gray")
			self.segment_imageCanvas.pack()

			# Add Image to Canvas
			self.segment_imageCanvas.create_image(self.segment_newImageSizeWidth/2+6,
												  self.segment_newImageSizeHeight/2+6,
												  image=self.segment_photoImg,
												  anchor="center")
	
		# Display Notes
		self.note_displayer(selection_coordinates)
	
	def taxon_list_displayer(self,database,current_id):
	# Displays Taxon Editor Panel
	
		# Delete Any Existing Information
		try:
			self.pane_two.destroy()
			self.pane_two_bottom_left.destroy()
			self.pane_two_bottom_right.destroy()
		except (NameError, AttributeError):
			pass
		
		self.export_list = []
		
		# Setup search Window Panels
		self.pane_two = ttk.Frame(self.search_window)
		self.pane_two.place(y=15, relx=.25, relwidth=.74, relheight=.4)
		self.pane_two_bottom_left = ttk.Frame(self.search_window)
		self.pane_two_bottom_left.place(relx=.25, rely = .45, relwidth=.32, relheight=.4)
		self.pane_two_bottom_right = ttk.Frame(self.search_window)
		self.pane_two_bottom_right.place(relx=.65, rely = .45, relwidth=.32, relheight=.4)
		
		# Set up segment list scrollbar
		self.scrollbar = Scrollbar(self.pane_two)
		self.scrollbar.pack(side=RIGHT,fill=Y)

		# Set Up segment listbox
		self.segments = Listbox(self.pane_two)
		self.segments.pack(anchor=W, fill=BOTH, expand=True)
		self.get_annotations_button = Button(self.pane_two, text="Search For Taxons", command=self.get_checked_annotations)
		self.get_annotations_button.pack()
		self.list_of_items = ""
        
		#Populate Segment List Box
		for collection_number,dictionary in self.database.items():
			if collection_number != 'users':
				for item_number,item_dictionary in self.database[collection_number]['items'].items():
					for segment_number,segment_dictionary in self.database[collection_number]['items'][item_number]['segments'].items():
						self.relatedterms = []
						if 'annotations' in segment_dictionary:
							for annotation in segment_dictionary['annotations']:
								self.relatedterms.append(annotation[0])
													  
							# If the selected term is in the item list
							if all(elem in self.relatedterms for elem in current_id):
								
								self.list_of_items = self.list_of_items + (collection_number + "/" + item_number+ "/" + segment_number + "; ")
                                
								# If the segment is text
								if self.database[collection_number]['items'][item_number]['item_type'] == "t":
								
									if 'fabio:pageRange' in self.database[collection_number]['items'][item_number]:
	
										if 'dc:description' in self.database[collection_number]['items'][item_number]['segments'][segment_number]:
	
											display_item = "Text " + str(int(segment_number) +1) + ' of Page ' + self.database[collection_number]['items'][item_number]['fabio:pageRange'][0] + ' of ' + self.database[collection_number]['dc:title'][0] + ': ' + self.database[collection_number]['items'][item_number]['segments'][segment_number]['dc:description'][0] 
											
										else:
											display_item = "Text " + str(int(segment_number) +1) + ' of Page ' + self.database[collection_number]['items'][item_number]['fabio:pageRange'][0] + ' of ' + self.database[collection_number]['dc:title'][0]
										
									else: 
									
										if 'dc:description' in self.database[collection_number]['items'][item_number]['segments'][segment_number]:
											
											display_item = 'Text ' + str(int(item_number) + 1) + ":" + str(int(segment_number) +1) + ' of ' + self.database[collection_number]['dc:title'][0] + ': ' + self.database[collection_number]['items'][item_number]['segments'][segment_number]['dc:description'][0] 
										
										else: 
										
											display_item = 'Text ' + str(int(item_number) + 1) + ":" + str(int(segment_number) +1) + ' of ' + self.database[collection_number]['dc:title'][0]

								# If the segment is an image
								elif self.database[collection_number]['items'][item_number]['item_type'] == "i":

									display_item = 'Image ' + str(int(item_number) + 1) + ":" + str(int(segment_number) +1) + ' of ' + self.database[collection_number]['dc:title'][0]

								# Display the number and title
								segment = display_item
								self.segments.insert(END, segment)
								
								# Save to export list
								self.export_list.append([collection_number,item_number,segment_number])
			
		# Bind scrollbar to listbox
		self.segments.config(yscrollcommand=self.scrollbar.set)
		self.scrollbar.config(command=self.segments.yview)
		
		# Bind command to double-click segment
		self.segments.bind('<Double-Button>', self.result_viewer)

		# Print list of items
		self.citationlist = ttk.Entry(self.pane_two)
		self.citationlist.insert(0,self.list_of_items[:-2])
		self.citationlist.pack(expand=YES, fill=X)

	def taxon_tree_displayer(self):
	# Displays search Tree Panel
	
		window_width = self.search_window.winfo_screenwidth()
		window_height = self.search_window.winfo_screenheight()

		# Create Tree
		self.search_tree = CheckboxTreeview(self.pane_one,height=int(window_height),selectmode='browse',show='tree')

		# Create Tree Layout
		self.search_tree.column("#0", width=int(window_width/2), stretch=1)		

		# Alphabetise search
		alpha_search = []
		for item,dictionary in self.taxonomy.items():
			alpha_search.append(dictionary['iid'])
		alpha_search = sorted(alpha_search)
		
		# Go through search alphabetically and build branches
		for taxon in alpha_search:
			self.iid_iterator(self.taxonomy,taxon,self.taxon_branch_builder)

		self.get_annotations_button = Button(self.pane_two, text="Search For Taxons", command=self.get_checked_annotations)

		# Display Tree
		self.search_tree.pack()
		self.get_annotations_button.pack(anchor="nw")
		
		self.search_tree.update()
		
	########################
	#		 Main		 #
	########################	
		
	def search_viewer(self,window):
	# Displays the search Panels

		# Set Icon Assets
		# Menu Bar Icons made by Pixel Buddha (https://www.flaticon.com/authors/pixel-buddha) from http://www.flaticon.com  CC-BY (http://creativecommons.org/licenses/by/3.0/)
		self.up_level_icon=PhotoImage(file=Path(self.assets_path) / 'uplevel.png')
		self.add_icon=PhotoImage(file=Path(self.assets_path) / 'add.png')
		self.delete_icon=PhotoImage(file=Path(self.assets_path) / 'delete.png')
		self.save_icon=PhotoImage(file=Path(self.assets_path) / 'save.png')
		self.refresh_icon=PhotoImage(file=Path(self.assets_path) / 'refresh.png')

		##################
		# Window Cleanup #
		##################

		# Delete Previous Panels and Menus or Create New Window
		try:
			self.pane_one.destroy()
			self.pane_two.destroy()
			self.pane_three.destroy()
		except (NameError, AttributeError):
			pass

		###################
		# search Window #
		###################

		# Setup search Window
		self.search_window = window

		# Setup search Window Panels
		self.pane_one = ttk.Frame(self.search_window)
		self.pane_two = ttk.Frame(self.search_window)
		self.pane_one.place(y=15, relwidth=.20, relheight=.85)
		self.pane_two.place(y=15, relx=.25, relwidth=.74, relheight=.4)

		#menubar.add_command(label="Add New Root", command=self.root_adder)

		# Set Up Annotation Selection (Tree) Panel 
		self.annotation_list = []
		self.taxon_tree_displayer()
Пример #8
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)
Пример #9
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)
Пример #10
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()
Пример #11
0
f1 = tk.Frame(root, width=490, height=490)
f1.pack()

can = tk.Canvas(f1)

tree = CheckboxTreeview(can)
tree.column('#0', minwidth=350, stretch=True)
tree.insert("", "end", "1", text="1" + '2')

tree.insert("1", "end", "11", text="11")
tree.insert("1",
            "end",
            "12",
            text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')
tree.insert("11",
            "end",
            "111",
            text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')

tree.insert("",
            "end",
            "2",
            text="Anantha" + "kumar" + 'Kondra' + 'Anantha Kumar Kondra')
tree.pack(expand=True, fill=tk.BOTH)
xscrol = ttk.Scrollbar(can, orient=tk.HORIZONTAL, command=tree.xview)
xscrol.pack(anchor=tk.S, fill=tk.X, side=tk.BOTTOM)
tree.configure(xscroll=xscrol.set)
can.grid(row=0, column=0, sticky=tk.N + tk.S + tk.E + tk.W)

root.mainloop()