0

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

欢迎所有建议。谢谢

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()

4

1 回答 1

1

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

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

做你想做的事,你必须做以下三件事:

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

例子:

tree.focus_set()
children = tree.get_children()
if children:
    tree.focus(children[0])
    tree.selection_set(children[0])
于 2021-02-03T21:17:47.533 回答