[英]Switch to ttk.TreeView with Tab key correctly
我有一個Tkinter窗口,其中有一個文本框和ttk.TreeView
子類。 運行程序時,我在文本框中輸入文本,然后切換到樹形視圖。 當我嘗試使用Tab
鍵執行此操作時,似乎焦點不在切換到表格,而是切換到滾動條,因此在按上/下鍵時,滾動了表格內容,但未選擇。 如何使用Tab
鍵切換到表格本身?
工作范例:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk
import tkinter.ttk as ttk
class TV(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.CreateUI()
self.LoadTable()
self.grid(sticky = (tk.N,tk.S,tk.W,tk.E))
parent.grid_rowconfigure(0, weight = 1)
parent.grid_columnconfigure(0, weight = 1)
def CreateUI(self):
tv = ttk.Treeview(self,yscrollcommand=sc.set,height=30)
tv['columns'] = ('Col1', 'Col2', 'Col3')
tv.heading("#0", text='id')
tv.heading('Col1', text='Col1')
tv.heading('Col2', text='Col2')
tv.heading('Col3', text='Col3')
tv.grid(sticky = (tk.N,tk.S,tk.W,tk.E))
self.treeview = tv
self.treeview.bind('<1>',self.OnClick)
self.grid_rowconfigure(0, weight = 1)
self.grid_columnconfigure(0, weight = 1)
def LoadTable(self):
for i in range(100):
self.treeview.insert('', 'end', iid=str(i+1), text='1', values=(2, 3, 4))
def OnClick(self,event):
rowid=self.treeview.identify_row(event.y)
self.treeview.selection_set(rowid)
root=tk.Tk()
sv=tk.StringVar()
filt=tk.Entry(root,textvariable=sv)
filt.grid(row=0,column=0,sticky='nw')
sc=tk.Scrollbar(root)
sc.grid(row=1,column=1,sticky='ns')
ic_list=TV(root)
ic_list.grid(row=1,column=0,sticky='ns')
sc.config(command=ic_list.treeview.yview)
ic_list.treeview.selection_set('1')
filt.focus()
root.mainloop()
回答自己和那些感興趣的人。 首先,我禁用了滾動條,以避免額外按下Tab
:
sc=tk.Scrollbar(root, takefocus=0)
然后,由於以下答案,我添加了一個用於獲得焦點的處理程序:
def on_get_focus(self, event):
self.treeview.selection_set(self.treeview.get_children('')[0]) #set selection on the first item
self.treeview.focus_set()
self.treeview.focus(self.treeview.get_children('')[0])
# here I added the code for OnClick event
# in CreateUI()
self.bind('<FocusIn>',self.on_get_focus)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.