python - 如何使 ttk.Treeview 的行可编辑?

标签 python treeview tkinter ttk

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/

相关文章:

python - 滚动发生值的最近索引

python - 是否有任何解决方法可以在对流层模板中使用 if 语句?

wpf - 在 WPF 中为 TreeViewItem 创建事件处理程序

python - 我应该如何在不丑陋的情况下在 Windows 上启动一个 Portable Python Tkinter 应用程序?

python - 获取全局鼠标位置并在python程序中使用?

Python 脚本匹配文件名中的特定文本并计算此类文件的数量

python - Django:Django-Rest-Framework 给出归因错误(分页)

Delphi TreeView 节点之间的拖放

c++ - 为 QML TreeView 创建模型

python - 如何在Python中使用tkinter按钮终止两个进程