Title: Improve the tkinter Treeview popup example in Python
My post Display large icons on tkinter's Treeview widget in Python lets you edit the hierarchical data in a Treeview widget. It works, but it also has a few confusing issues. For example, if you right-click on the first among a node's children and select Move Up, nothing happens because that node is already the first of its parent's children.
It's even more confusing when you select Move Up or Move Down on an only child. You might think that it would move the node to the next parent above its current parent, but again nothing happens.
That example also lets you delete the root node, which deletes every other node with it, but it provides no way to create a new root node.
This example addresses those issues.
Building Popups
To let you add new root nodes, the program uses separate popup menus when you right-click on a node or on the Treeview's body. Here's the code that creates the two popup menus.
# Make the body popup menu.
self.body_popup = tk.Menu(self.window, tearoff=False)
self.body_popup.add_command(label='Add Root', command=self.add_root)
# Make the row 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 first creates the popup to display when you right-clicks on the Treeview but not on any node. That popup has a single Add Root command.
The snippet then creates the row_popup menu as in the previous example.
Displaying Popups
When you right-click the Treeview, the following show_popup method executes much as it did in the earlier post.
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)
# See if there is a row under the mouse.
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)
# Enable and disable appropriate commands.
self.enable_popup_commands(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()
else:
# Display the body popup at the cursor's screen coordinates.
try:
self.body_popup.tk_popup(event.x_root, event.y_root)
finally:
# Release the grab.
self.body_popup.grab_release()
The method gets the selected row's ID. If there is a selected row, it sets focus to that row as before. It then calls enable_popup_commands (described shortly) to enable and disabled commands appropriately for the clicked row. It then displays the popup as in the previous post.
If you right-clicked on the Treeview's body and not on a row, the code displays the body_popup menu.
Here's the enable_popup_commands method.
def enable_popup_commands(self, row_id):
'''Enable and disable appropriate popup menu commands.'''
# Don't let the user delete root nodes.
parent = self.tree.parent(row_id)
if parent:
self.row_popup.entryconfig('Delete', state='normal')
else:
self.row_popup.entryconfig('Delete', state='disabled')
# Don't move the node up/down if it's the first/last child.
num_siblings = len(self.tree.get_children(parent))
index = self.tree.index(row_id)
if index == 0:
# It's the first child. Do not allow Move Up.
self.row_popup.entryconfig('Move Up', state='disabled')
else:
# It's not the first child. Allow Move Up.
self.row_popup.entryconfig('Move Up', state='normal')
if index == num_siblings - 1:
# It's the last child. Do not allow Move Down.
self.row_popup.entryconfig('Move Down', state='disabled')
else:
# It's not the last child. Allow Move Down.
self.row_popup.entryconfig('Move Down', state='normal')
This method gets parent of the clicked node. If the node has no parent, it's a top-level root node. If the node is a root node, the code disables the Delete command so you cannot delete it. If the node has a parent, the code enables the Delete command.
Next, the code gets the number of sibling nodes (nodes that have the same parent as the clicked node) and the clicked node's index in its sibling list. If the node's index is 0, the node is the first sibling so it cannot be moved up in the list and the code disables the Move Up command. Conversely, if the clicked node is last in its sibling list, it cannot be moved down so the code disables the Move Down command. Note that the code disables both commands if the clicked node is an only child.
Putting Down Roots
When you right-click on the Treeview's body, the program displays the one-item popup menu shown on the right. The last piece of new code in this example is the add_root method, which executes when you select Add Root from this menu.
def add_root(self):
'''Add a a new root node.'''
# Prompt for a new text value.
new_text = simpledialog.askstring(
title='New Root', prompt='New Root:',
parent=self.window)
if new_text is not None:
# Insert the new node at the end of the tree.
self.tree.insert(parent='', index='end',
text=new_text, open=True)
This method prompts for the new root's name and then adds it to the tree. It sets the new node's parent ID to an empty string to make it a top-level root node.
Conclusion
Enabling and disabling commands makes it easy to see what commands are appropriate when you right-click different nodes. For example, you can't select Move Up on a first sibling and be mystified when it doesn't move.
There are still some changes that you might like to make in a real application. For example, you might want to ask for confirmation before deleting a node because there's no way to undo that change. An accidental deletion could be particularly disastrous because deleting a node also deletes all of its descendants. I left this out to keep the example simple, but it should be easy to add.
This example lets you add new root nodes but prevents you from deleting root nodes, but it would probably make more sense to do one or the other. If you want the initial root node to remain permanent, you may not want to allow adding more roots. If you allow adding roots, you may want to also allow deleting them. I made the example like this to show how prevent deletions and how to add roots, but it should be easy for you to change.
Depending on your application, you might want to make other changes. Hopefully this example gives you the tools you need to make those changes.
Download the example to experiment with it and to see additional details.
|