如何将焦点设置在 tkinter Treeview 列表的第一行

How do I set focus on the first row of a tkinter Treevew list

我希望设置树中第一行的焦点(突出显示状态),以便用户只需使用箭头向下或向上移动,而不必首先 select 一行。默认值应突出显示第 0 行。这里有一个示例程序作为示例。它允许用户通过左键单击 select 行,然后 window 将弹出该行的详细信息。

欢迎所有建议。谢谢

from tkinter import *
from tkinter import ttk
import tkinter as tk


# Display selected row
def msgwindow(xrow):
    curitem = tree.item(tree.focus())
    rowinfo=Toplevel(root) # Child window
    rowinfo.geometry("500x200")  # Size of the window
    rowinfo.title("selected row")
    row_str = tk.StringVar()
    l1 = tk.Label(rowinfo,  textvariable=row_str )
    l1.grid(row=1, column=0)
    row_str.set(curitem['values'][0] + ', ' + curitem['values'][1] + ', ' + curitem['values'][2])
    # Exit selected row window
    def exit_rowinfo(event):
        rowinfo.destroy()

    rowinfo.bind('<Return>', exit_rowinfo)

    # Define exit window button
    rowinfo_back_button = tk.Button(rowinfo, text='Back', padx=20, pady=10, command=lambda: exit_rowinfo(1))
    rowinfo_back_button.grid(row=0, column=1)

# End program
def exit_root(event):
    root.destroy()

tree_columns=('#1', '#2', '#3')

root = Tk()
tree = ttk.Treeview(root, columns=tree_columns, show='headings')
tree.heading('#1', text='First Name')
tree.heading('#2', text='Last Name')
tree.heading('#3', text='Email')
tree.column('#1', width=150)
tree.column('#2', width=150)
tree.column('#3', width=250)

# Define exit window button
tree_exit_button = tk.Button(root, text='Exit', padx=20, pady=10, command=lambda: exit_root(1))
tree_exit_button.grid(row=0, column=6, sticky=N + W)

# generate sample data
def generatetestdata(xtree, xnum):
    contacts = []
    for n in range(1, xnum+1):
        contacts.append((f'first {n}', f'last {n}', f'email{n}@example.com'))
    # adding data to the frame2 tree
    for contact in contacts:
        xtree.insert('', tk.END, values=contact)

generatetestdata(tree, 5)

tree.grid()
tree.bind('<ButtonRelease-1>', msgwindow)
root.bind('<Return>', exit_root)

root.mainloop()

您使用 focus_set 将焦点设置为整个小部件。要将树焦点设置到特定项目,您可以调用树视图上的 focus 方法,将它传递给您想要获得焦点的项目。

但是,听起来您似乎在询问除了设置焦点之外如何设置选区。仅设置焦点不会改变项目的突出显示状态。为此,您需要使用 selection_set.

设置选择

要想做自己想做的事,必须做到以下三点:

  • 将整个键盘焦点设置到树上,以便将键事件发送到它
  • 将内部树焦点设置到第一个项目,因为树将它接收到的所有键盘事件发送到焦点项目
  • 将选择设置为第一项以使其突出显示。

示例:

tree.focus_set()
children = tree.get_children()
if children:
    tree.focus(children[0])
    tree.selection_set(children[0])