Is there any way to use ttk Treeview with editable rows?
我的意思是它应该更像一张 table 。例如,双击该项目使#0 列“可编辑”。
如果这不可能,任何允许鼠标选择项目的方法都可以。我在 tkdocs 或其他文档中没有发现任何提及。
最佳答案
经过长时间的研究,我还没有发现这样的功能,所以我猜是有的。 Tk 是非常简单的接口(interface),允许程序员从基础构建“高级”功能。所以我想要这样的行为。
def onDoubleClick(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
# self.destroyPopups()
# what row and column was clicked on
rowid = self._tree.identify_row(event.y)
column = self._tree.identify_column(event.x)
# get column position info
x,y,width,height = self._tree.bbox(rowid, column)
# y-axis offset
# pady = height // 2
pady = 0
# place Entry popup properly
text = self._tree.item(rowid, 'text')
self.entryPopup = EntryPopup(self._tree, rowid, text)
self.entryPopup.place( x=0, y=y+pady, anchor=W, relwidth=1)
这是一个类中的方法,它将 ttk.Treeview 组合为 self._tree
然后 EntryPopup 是 Entry 的非常简单的子类:
class EntryPopup(Entry):
def __init__(self, parent, iid, text, **kw):
''' If relwidth is set, then width is ignored '''
super().__init__(parent, **kw)
self.tv = parent
self.iid = iid
self.insert(0, text)
# self['state'] = 'readonly'
# self['readonlybackground'] = 'white'
# self['selectbackground'] = '#1BA1E2'
self['exportselection'] = False
self.focus_force()
self.bind("<Return>", self.on_return)
self.bind("<Control-a>", self.select_all)
self.bind("<Escape>", lambda *ignore: self.destroy())
def on_return(self, event):
self.tv.item(self.iid, text=self.get())
self.destroy()
def select_all(self, *ignore):
''' Set selection on the whole text '''
self.selection_range(0, 'end')
# returns 'break' to interrupt default key-bindings
return 'break'
关于python - 如何使 ttk.Treeview 的行可编辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18562123/