微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Tkinter Treeview 中插入新行?

如何解决如何在 Tkinter Treeview 中插入新行?

我正在处理树视图,其中一列(地址)中的文本无法放入一行。我的代码如下所示:

# Create the invoice window
    invoice = Tk()
    invoice.title("Invoices")
    invoice.geometry("1800x1000")

    # Create treeview frame
    tree_frame = Frame(invoice)
    tree_frame.pack(pady=10)

    # Create scrollbar for treeview
    tree_scroll = Scrollbar(tree_frame)
    tree_scroll.pack(side=RIGHT,fill=Y)

    # Create treeview
    tree = ttk.Treeview(tree_frame,yscrollcommand=tree_scroll.set,selectmode="extended")
    tree.pack()

    # Configure scrollbar
    tree_scroll.config(command=tree.yview)

    # Define the columns of the treeview
    tree['columns'] = (
    "Invoice Number","Company Name","Company Address","VAT Number","Total","Currency","Invoice Date")

    # Place the columns
    tree.column("#0",width=0,stretch=NO)
    tree.column("Invoice Number",anchor=CENTER,width=140)
    tree.column("Company Name",width=140)
    tree.column("Company Address",width=140)
    tree.column("VAT Number",width=140)
    tree.column("Total",width=140)
    tree.column("Currency",width=140)
    tree.column("Invoice Date",width=140)

    # Create headings for columns
    tree.heading("#0",text="",anchor=W)
    tree.heading("Invoice Number",text="Invoice Number",anchor=CENTER)
    tree.heading("Company Name",text="Company Name",anchor=CENTER)
    tree.heading("Company Address",text="Company Address",anchor=CENTER)
    tree.heading("VAT Number",text="VAT Number",anchor=CENTER)
    tree.heading("Total",text="Total",anchor=CENTER)
    tree.heading("Currency",text="Currency",anchor=CENTER)
    tree.heading("Invoice Date",text="Invoice Date",anchor=CENTER)

如何实现一个新行,以便当地址到达空格末尾时,它会从新行开始?当然,整行应该是一样的高度。

解决方法

有一个 minwidth 选项可以设置可以收缩多少列的最小宽度,但我认为地址太长,您想改用文本换行:

您需要为此导入 textwrap 模块:

import textwrap

首先定义一个函数来换行:

def wrap(string,length=8):
    if len(companyAddress) >= 10: # this if loop is only for when you don't know the length of the address and want to add newline after it reaches certain length. Otherwise remove the if loop and leave the return statement in.
        
        return '\n'.join(textwrap.wrap(string,length))

就是这样。现在,如果要插入数据,只需在需要包装的值上调用该函数即可。

tree.insert("","end",iid=0,text="",values=("invoice number",...(values)...,wrap("insert company address here")))

只需在要包装的任何其他值上调用此函数即可。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。