Użycie strzałki w dół aby przeskoczyć z ostatniego do pierwszego wiersza w Treeview
Kod używa bind()
aby wywołać funkcję gdy zostaje wciśnieta strzałka w dół Down
w Treeview
.
Funkcja sprawdza czy jesteśmy w ostatnim wierszu
last = tree.get_children()[-1]
if tree.focus() == last:
i przenosi fokus oraz selekcje do pierwszego wiersza, oraz przewija okno do tego wiersza.
Wysyła także napis "break"
aby Treeview
nie użył tego zdarzenia do przejścia z pierwszego do drugiego wiersza.
first = tree.get_children()[0]
tree.selection_set(first) # move selection
tree.focus(first) # move focus
tree.see(first) # scroll to show it
return "break" # don't send event to TreeView
Podobna funkcja jest dla strzałki w górę Up
aby przeskoczyć z pierwszego do ostatniego wiersza.
import tkinter as tk
from tkinter import ttk
# --- functions ---
def jump_to_first(event):
last = tree.get_children()[-1]
if tree.focus() == last:
first = tree.get_children()[0]
tree.selection_set(first) # move selection
tree.focus(first) # move focus
tree.see(first) # scroll to show it
return "break" # don't send event to TreeView
def jump_to_last(event):
first = tree.get_children()[0]
if tree.focus() == first:
last = tree.get_children()[-1]
tree.selection_set(last) # move selection
tree.focus(last) # move focus
tree.see(last) # scroll to show it
return "break" # don't send event to TreeView
# --- main ---
root = tk.Tk()
tree = ttk.Treeview(root)
tree.pack()
tree.bind('<Down>', jump_to_first)
tree.bind('<Up>', jump_to_last)
# create many rows so it will have to scroll them
for x in range(1, 21):
tree.insert('', 'end', text='Row {:02}'.format(x))
root.mainloop()
If you like it
Buy a Coffee
Buy a Coffee