Title: Use a popup menu to let users edit a tkinter Treeview in Python
Several of my recent posts have dealt with loading and displaying hierarchical data in a Treeview widget, but what if you want to modify the data? This post explains one way you can add, edit, move, and delete Treeview nodes interactively.
Building and Binding the Popup Menu
When the program starts, its build_ui method uses the following code to create the popup menu.
# Make the popup menu.
self.row_popup = tk.Menu(self.window, tearoff=False)
self.row_popup.add_command(label='Edit', command=self.edit_node)
self.row_popup.add_command(label='Add Child', command=self.add_node)
self.row_popup.add_separator()
self.row_popup.add_command(label='Move Up', command=self.move_up)
self.row_popup.add_command(label='Move Down', command=self.move_down)
self.row_popup.add_separator()
self.row_popup.add_command(label='Delete', command=self.delete_node)
This code creates a new tk.Menu. The tearoff=False parameter makes the menu not display a dashed line at the top (which just looks weird on a popup menu).
Next, the code adds some commands and separators the menu. When selected, each command calls am editing method described later. You can play all of the usual tricks with the popup menu. For example, you can add accelerators and icons to the commands.
Displaying the Menu
After it creates the Treeview widget, the program uses the following code to bind mouse clicks so they display the popup menu.
# Bind right-click. Button-3 for Windows and Linux.
# Button-2 or Control-Button-1 for macOS.
tree.bind('<Button-3>', self.show_popup)
if self.window.tk.call('tk', 'windowingsystem') == 'aqua':
tree.bind('<Button-2>', self.show_popup)
tree.bind('<Control-Button-1>', self.show_popup)
When you left-clicks the Treeview, the program calls its show_popup method. In Windows and Linux, you use Button-3 to show popup menus. In macOS, you use Button-2 or Control-Button-1. (I use Windows and haven't tested this in Linux or macOS so your mileage may vary.)
The following code shows the show_popup method that displays the popup menu.
def show_popup(self, event):
'''Display the popup menu for the row under the mouse.'''
# Find the row under the mouse.
self.selected_row_id = self.tree.identify_row(event.y)
if self.selected_row_id:
# Select the row under the mouse so actions apply to it.
self.tree.selection_set(self.selected_row_id)
self.tree.focus(self.selected_row_id)
# Display the menu at the cursor's screen coordinates.
try:
self.row_popup.tk_popup(event.x_root, event.y_root)
finally:
# Release the grab.
self.row_popup.grab_release()
This method uses the Treeview's identify_row method to find the row under the mouse. If there is such a row (in other words, the mouse isn't below all of the rows), the code gets that row's ID and gives it focus so it is highlighted. It then displays the popup menu at the current mouse position.
Modifying the Data
The following sections describe the methods invoked by the popup menu.
Editing Nodes
The following edit_node method lets you edit the selected node.
def edit_node(self):
'''Add a node below the selected node.'''
# Get the selected node.
selected = self.tree.selection()
if selected:
item_id = selected[0]
old_text = self.tree.item(item_id, 'text')
# Prompt for a new text value.
new_text = simpledialog.askstring(
title='Edit Node', prompt='New Text:',
initialvalue=old_text, parent=self.window)
if new_text is not None:
self.tree.item(item_id, text=new_text)
This code uses a tkinter simpledialog to let you enter a new text value for the node. This is about the bare minimum you could do for this feature. A more elaborate program might display a custom dialog with Entry widgets where you could enter name, title, job description, and other information.
If you enter a new value and click OK, the code updates the selected row's text.
Adding Nodes
The following add_node method lets you add a node below the selected node.
def add_node(self):
'''Add a node below the selected node.'''
# Get the selected node.
selected = self.tree.selection()
if selected:
# Prompt for a new text value.
new_text = simpledialog.askstring(
title='New Node', prompt='New Node:',
parent=self.window)
if new_text is not None:
# Insert the new node below the selected node.
item_id = selected[0]
self.tree.insert(parent=item_id, index='end',
text=new_text, open=True)
This code gets the selected node. If there is a selected node, it prompts for the new node's text and, if you enter some text and click OK, it adds the new node as a child of the selected node.
Moving Nodes
The following two methods move the selected node up or down.
def move_up(self):
'''Move the selected node up.'''
selected = self.tree.selection()
if selected:
item_id = selected[0]
current_index = self.tree.index(item_id)
parent = self.tree.parent(item_id)
self.tree.move(item_id, parent, current_index - 1)
def move_down(self):
'''Move the selected node down.'''
selected = self.tree.selection()
if selected:
item_id = selected[0]
current_index = self.tree.index(item_id)
parent = self.tree.parent(item_id)
self.tree.move(item_id, parent, current_index + 1)
The move_up method gets the selected node (if there is one), gets its ID, and finds its current index in its parent node. It then gets the node's parent and subtracts 1 from its index in the parent's child list to move it up. Note that the Treeview doesn't mind if you try to move a child off the top of the child list to position -1. If you try to move the top child up, the Treeview just leaves it at the top.
The move_down method performs the same steps except it increases the selected node's index in the parent's child list.
Deleting Nodes
The following delete_node method removes a node from the Treeview.
def delete_node(self):
'''Add a node below the selected node.'''
selected = self.tree.selection()
if selected:
self.tree.delete(selected[0])
This method simply gets the selected node and passes it to the Treeview's delete method. The delete method deletes the node and any descendants it may have.
Conclusion
This example builds a very simple Treeview editor. In my next post, I'll show how you can add a few more features to the program. Meanwhile, download the example to experiment with it and to see additional details.
|