Um ein Kontextmenü zu öffnen, wenn du mit der rechten Maustaste auf ein Feld in der Treeview klickst, musst du die Methode tag_bind Methode verwenden.
import tkinter as tk
from tkinter import ttk
class GridViewApp:
def __init__(self, root):
self.root = root
self.root.title("GridView Beispiel")
self.gridview = ttk.Treeview(self.root, columns=("Column 1", "Column 2", "Column 3"), show="headings")
self.gridview.heading("Column 1", text="Spalte 1", command=lambda: self.sort_column("Column 1"))
self.gridview.heading("Column 2", text="Spalte 2", command=lambda: self.sort_column("Column 2"))
self.gridview.heading("Column 3", text="Spalte 3", command=lambda: self.sort_column("Column 3"))
self.gridview.pack()
self.populate_grid()
self.context_menu = tk.Menu(self.root, tearoff=0)
self.context_menu.add_command(label="Aktion 1", command=self.context_action_1)
self.context_menu.add_command(label="Aktion 2", command=self.context_action_2)
self.gridview.bind("<Button-3>", self.show_context_menu)
def populate_grid(self):
for i in range(1, 10):
self.gridview.insert("", "end", values=(f"Zeile {i}", f"Wert {i*2}", f"{i+5}"))
def sort_column(self, column):
data = [(self.gridview.set(child, column), child) for child in self.gridview.get_children("")]
data.sort(reverse=False) # Set reverse=True for descending order
for index, item in enumerate(data):
self.gridview.move(item[1], "", index)
def show_context_menu(self, event):
item = self.gridview.identify_row(event.y)
if item:
self.gridview.selection_set(item)
self.context_menu.post(event.x_root, event.y_root)
def context_action_1(self):
selected_item = self.gridview.selection()[0]
values = self.gridview.item(selected_item)["values"]
print("Aktion 1 für:", values)
def context_action_2(self):
selected_item = self.gridview.selection()[0]
values = self.gridview.item(selected_item)["values"]
print("Aktion 2 für:", values)
def main():
root = tk.Tk()
app = GridViewApp(root)
root.mainloop()
if __name__ == "__main__":
main()