1.treeview遍历
iids = tree.selection()
t = tree.get_children()
for i in t:
print(tree.item(i,'values'))
2. 如何将ttk treeview 的某一行转入编辑状态
事实上,(python 3)treeview有一个readonly属性。但我用的是python 2。
解决方案:在双击treeview时根据鼠标的位置定位单元格,然后在此单元格里面贴入一个Entry控件即可。
def on_detail_bom_line_db_click(self, event):
''' Executed, when a row is double-clicked. Opens
read-only EntryPopup above the item's column, so it is possible
to select text '''
# close previous popups
if self.entryPopup:
self.entryPopup.destroy()
# what row and column was clicked on
rowid = self.bom_lines.identify_row(event.y)
column = self.bom_lines.identify_column(event.x)
# clicked row parent id
parent = self.bom_lines.parent(rowid)
#print 'parent:'+parent
# do nothing if item is top-level
if parent == '':
pass
# get column position info
x,y,width,height = self.bom_lines.bbox(rowid, column)
# y-axis offset
pady = height // 2
# place Entry popup properly
url = self.bom_lines.item(rowid, 'text')
self.entryPopup = StickyEntry(self.bom_lines, url, width=12)
self.entryPopup.place( x=x, y=y+pady, anchor=W)
扩展了Entry,添加了一点点行为:
class StickyEntry(Entry):
def __init__(self, parent, text, **kw):
''' If relwidth is set, then width is ignored '''
#fa = super(self,StickyEntry)
#fa.__init__(parent, **kw)
apply(Entry.__init__, (self, parent), kw)
self.insert(0, text)
#self['state'] = 'readonly'
self['readonlybackground'] = 'white'
self['selectbackground'] = '#1BA1E2'
self['exportselection'] = False
self.focus_force()
self.bind("<Control-a>", self.selectAll)
self.bind("<Escape>", lambda *ignore: self.destroy())
def selectAll(self, *ignore):
''' Set selection on the whole text '''
self.selection_range(0, 'end')
# returns 'break' to interrupt default key-bindings
return 'break'
3. treeview 的 heigth属性咋回事?
比如设置为60(pixels),结果抛出屏幕很多。 原因是这个是行数!!!
4. Entry 的width似乎也不是像素为单位的!
随便设置一个数字,比如20,能有200pixel或者更多的效果。
经过验证,似乎是数字字符的个数(比如20,就刚好能放20个数字字符!)
具体以什么字符为基准未知!
5.如何给ttk treeview设置竖直滚动条?
添加一个Srollbar控件,并将其set函数丢给treeview的yscrollcommand进行绑定。
注意布局,Scrollbar控件最好紧挨着treeview,并且在右边。
vbar = ttk.ScrollBar(container, orient=VERTICAL, command = your_treeview.yview)
your_treeview.configure(yscrollcomand=vbar.set)
your_treeview.grid(row=0)
vbar.grid(row=0, column=1,sticky=NS)
6. 如何将ttk treeview中的内容清空?
调用其delete方法,如下:
items = your_treeview.get_children() [your_treeview.delete(item) for item in items]
7. 如何得到ttk treeview被双击的单元格的值?
获取单元格的值,使用treeview的get函数即可,参数 (row, column) , row-- iid , column - index of column (started with '#')
理论上讲,只通过控件是无解的。通过自己定义坐标边界的方式来解决,即给每一列定义宽度(像素单位)。event.x/y能够取到坐标。在分析此坐标落在哪一列的坐标范围内即可分析出。
def get_cell_value(self, event, tree=None, col_widths=None):
"""
获取ttk treeview某一个单元格的值(在鼠标事件中)
:param event:
:param tree:
:param col_widths:
:return:
"""
i