繁体   English   中英

GUI中的Python Tkinter列表框文本编辑

[英]Python Tkinter listbox text edit in GUI

有没有办法编辑列表框项目而不是删除它?

我正在使用带有列表框的 tkinter GUI。 现在我的列表框可以包含例如 10 个项目。 如果我想更改一个项目的文本,有没有办法做到?

我知道我可以创建一个按钮来删除单个项目,但是有什么方法可以同时编辑一个项目?

列表框不支持直接编辑列表框内的项目。 您必须为用户提供一种输入数据的机制,然后您可以只替换列表框中的单个项目。

话虽如此,tkinter 为您提供了让用户双击项目并更改它所需的所有工具。 这是一个示例的快速破解。 简而言之,当您双击时,它会在您单击的项目上叠加一个条目小部件,当您按下返回键时,它会将项目保存到列表框。

import tkinter as tk

class EditableListbox(tk.Listbox):
    """A listbox where you can directly edit an item via double-click"""
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)
        self.edit_item = None
        self.bind("<Double-1>", self._start_edit)

    def _start_edit(self, event):
        index = self.index(f"@{event.x},{event.y}")
        self.start_edit(index)
        return "break"

    def start_edit(self, index):
        self.edit_item = index
        text = self.get(index)
        y0 = self.bbox(index)[1]
        entry = tk.Entry(self, borderwidth=0, highlightthickness=1)
        entry.bind("<Return>", self.accept_edit)
        entry.bind("<Escape>", self.cancel_edit)

        entry.insert(0, text)
        entry.selection_from(0)
        entry.selection_to("end")
        entry.place(relx=0, y=y0, relwidth=1, width=-1)
        entry.focus_set()
        entry.grab_set()

    def cancel_edit(self, event):
        event.widget.destroy()

    def accept_edit(self, event):
        new_data = event.widget.get()
        self.delete(self.edit_item)
        self.insert(self.edit_item, new_data)
        event.widget.destroy()

root = tk.Tk()
lb = EditableListbox(root)
vsb = tk.Scrollbar(root, command=lb.yview)
lb.configure(yscrollcommand=vsb.set)

vsb.pack(side="right", fill="y")
lb.pack(side="left", fill="both", expand=True)

for i in range(100):
    lb.insert("end", f"Item #{i+1}")

root.mainloop()

截屏

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM