我希望设置树中第一行的焦点(突出显示状态),以便用户只需要使用箭头向下或向上移动,而不必先选择一行。默认应突出显示第 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()