How to use Tkinter to create a list

Preface

  ttk.Treeview is a component in the Tkinter module that provides a tree list that can be used to display hierarchical data. It has the following features and functions:

  1. Display hierarchy: ttk.Treeview supports displaying data in a tree structure. Each node can have child nodes, thus forming a hierarchical structure. Users can expand or collapse nodes to view or hide child nodes.
  2. List view: ttk.Treeview also supports displaying data in list form, similar to a table. Each column can define different fields and display corresponding data.
  3. Multiple columns support: You can create multiple columns by specifying the columns parameter when initializing ttk.Treeview. Each column can have its own header and width.
  4. Data binding: ttk.Treeview can be bound to a data source, making the insertion, deletion and editing of data more convenient. You can use the insert method to insert data into ttk.Treeview, the delete method to delete data, and the set method to update data.
  5. Style customization: You can customize the appearance of ttk.Treeview by setting styles, fonts, colors, etc. You can also set styles or labels for different rows and cells to achieve customized effects.
  6. Event handling: You can bind various event handlers to the ttk.Treeview component, such as click, double-click, selection change, etc. By handling these events, you can respond to user actions and execute related logic.

ttk.Treeview is a very powerful and flexible component in Tkinter that can be used to create various complex hierarchical lists and data display interfaces. You can configure and use ttk.Treeview according to your own needs to achieve customized tree list functions.

1. Method

import tkinter as tk
from tkinter import ttk


class GUI:

    def __init__(self):
        self.root = tk.Tk()
        self.root.title('演示窗口')
        self.root.geometry("600x380+1100+150")
        self.interface()

    def interface(self):
        """"界面编写位置"""
        pass


if __name__ == '__main__':
    a = GUI()
    a.root.mainloop()

1. Create lists and data and set styles

    def interface(self):
        """"界面编写位置"""
        # (1)创建样式
        style = ttk.Style()
        style.configure("Treeview", rowheight=20)  # 设置行高
        style.configure("Treeview.Heading", font=('Arial', 11, 'bold'))  # 设置表头字体

        # (2)创建 Treeview 控件,设置高度为10行
        self.tree = ttk.Treeview(self.root, height=10, style="Treeview")
        self.tree.grid(row=0, column=0, rowspan=10, columnspan=10, padx=60)

        # (3)定义列名
        self.tree["columns"] = ("Name", "Age", "City")

        # (4)设置列的标题名称,anchor可设置对其方式:居中(center)/左对齐(w)/右对齐(e),无anchor参数时,标题名称默认居中
        self.tree.heading("#0", text="序号", anchor="w")
        self.tree.heading("Name", text="姓名")
        self.tree.heading("Age", text="年龄")
        self.tree.heading("City", text="城市")

        # (5)设置列宽度(像素),无anchor参数时,列表中的数据除(#0)外其余都是默认左对齐
        self.tree.column("#0", width=50)
        self.tree.column("Name", width=100, anchor="center")
        self.tree.column("Age", width=90, anchor="center")
        self.tree.column("City", width=150, anchor="center")

        # (6)插入默认数据
        self.tree.insert("", tk.END, text="1", values=("张三", "25", "深圳"))

Insert image description here

explain:

  1. Create a style: First, create a ttk.Style() object, and set the row height and header font style of the list through the configure method.
  2. Create a Treeview control: Call the ttk.Treeview constructor to create a Treeview control named self.tree and place it in the grid layout of the parent window self.root, at the first row/column, spanning 10 rows /column, leaving 60 pixels left and right margins.
  3. Define column names: By setting the self.tree["columns"] property, a list containing three columns is defined, with the column names being "Name", "Age" and "City".
  4. Set the heading name of the column: By calling the self.tree.heading method, the heading name of each column is set. Among them, "#0" is the default index column, the title text is "Serial Number", and the alignment is left-aligned; the title of the "Name" column is "Name", no alignment is specified, and the default is center alignment; the "Age" column The title is "Age", no alignment is specified, and the default is center alignment; the title of the "City" column is "City", no alignment is specified, and the default is center alignment.
  5. Set column width: By calling the self.tree.column method, the width of each column is set. The "#0" column is 50 pixels wide, the "Name" column is 100 pixels wide, the "Age" column is 90 pixels wide, and the "City" column is 150 pixels wide. In the data columns, except for the "#0" column, which is left-aligned by default, the data in other columns are center-aligned by default.
  6. Insert default data: A data row is inserted in the Treeview by calling the self.tree.insert method. A data row with index "1" is inserted here, which contains name, age and city information.

2. Get list data

    def interface(self):
        """"界面编写位置"""
        # (1)创建样式......
        # (2)创建 Treeview 控件......
        # (3)定义列名......
        # (4)设置列的标题名称......
        # (5)设置列宽度(像素)......
        # (6)插入默认数据
        self.tree.insert("", tk.END, text="1", values=("张三", "25", "深圳"))
        self.tree.insert("", tk.END, text="2", values=("王五", "30", "上海"))

        # 创建按钮
        self.Button0 = tk.Button(self.root, text="获取数据", command=self.get_data)
        self.Button0.grid(row=11, column=0, ipadx=10)

        self.Button1 = tk.Button(self.root, text="获取全部数据", command=self.get_whole_data)
        self.Button1.grid(row=11, column=2, ipadx=10)
        # 添加文本框
        self.Label0 = tk.Label(self.root, text="打印日志:")
        self.Label0.grid(row=12, column=0, padx=60)
        self.w1 = tk.Text(self.root, width=50, height=5)
        self.w1.grid(row=13, column=0, columnspan=5, padx=60)

    def get_data(self):
        '''获取选中数据'''
        selected_items = self.tree.selection()
        if selected_items:
            for item in selected_items:
                row_data = self.tree.item(item)['values']
                self.w1.insert("1.0", f"Selected Row Data:{
      
      row_data}\n")
        else:
            self.w1.insert("1.0", "未选中数据\n")

    def get_whole_data(self):
        '''获取全部数据'''
        rows = self.tree.get_children()  # 获取所有的行ID
        # 遍历每一行
        for row in rows:
            # 获取该行的数据字典
            data = self.tree.item(row)
            self.w1.insert("1.0", f"{
      
      data['values']}\n")

Insert image description here

3. Add, edit, delete

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox


class GUI:

    def __init__(self):
        self.root = tk.Tk()
        self.root.title('演示窗口')
        self.root.geometry("600x380+1100+150")
        self.interface()

    def interface(self):
        """"界面编写位置"""
        # (1)创建 Treeview 控件, 设置高度为10行
        self.tree = ttk.Treeview(self.root, height=10)
        self.tree.grid(rowspan=10, columnspan=10, padx=30)
        # (2)定义列名
        self.tree["columns"] = ("Name", "Age", "City")
        # (3)设置列的标题名称
        self.tree.heading("#0", text="序号", anchor="w")
        self.tree.heading("Name", text="姓名")
        self.tree.heading("Age", text="年龄")
        self.tree.heading("City", text="城市")
        # (4)设置列宽度(像素)
        self.tree.column("#0", width=50)
        self.tree.column("Name", width=100, anchor="center")
        self.tree.column("Age", width=90, anchor="center")
        self.tree.column("City", width=150, anchor="center")
        # (5)插入默认数据
        self.tree.insert("", tk.END, text="1", values=("张三", "25", "深圳"))
        # 创建按钮
        self.Button0 = tk.Button(self.root, text="添加", command=self.add_page)
        self.Button0.grid(row=11, column=1, ipadx=10)
        self.Button1 = tk.Button(self.root, text="编辑", command=self.edit_page)
        self.Button1.grid(row=11, column=3, ipadx=10)
        self.Button2 = tk.Button(self.root, text="删除", command=self.delete_item)
        self.Button2.grid(row=11, column=5, ipadx=10)

    def add_page(self):
        self.Label0 = tk.Label(self.root, text="姓名")
        self.Label0.grid(row=0, column=11)

        self.entry00 = tk.StringVar()
        self.entry0 = tk.Entry(self.root, textvariable=self.entry00, width=15)
        self.entry0.grid(row=1, column=11)

        self.Label1 = tk.Label(self.root, text="年龄")
        self.Label1.grid(row=2, column=11)

        self.entry01 = tk.StringVar()
        self.entry1 = tk.Entry(self.root, textvariable=self.entry01, width=15)
        self.entry1.grid(row=3, column=11)

        self.Label02 = tk.Label(self.root, text="城市")
        self.Label02.grid(row=4, column=11)

        self.entry02 = tk.StringVar()
        self.entry2 = tk.Entry(self.root, textvariable=self.entry02, width=15)
        self.entry2.grid(row=5, column=11)

        self.Button_1 = tk.Button(self.root, text="确定", command=self.add_item)
        self.Button_1.grid(row=6, column=11, ipadx=10)

    def add_item(self):
        '''添加数据'''
        rows = self.tree.get_children()  # 获取所有的行ID
        name = self.entry00.get()
        age = self.entry01.get()
        city = self.entry02.get()
        if name and age and city:
            self.tree.insert("", tk.END, text=len(rows)+1, values=(name, age, city))
        else:
            self.Button_1.bind("<Button-1>", self.window("输入框不可以为空"))

    def edit_page(self):
        selected_items = self.tree.selection()
        if selected_items:
            for item in selected_items:
                row_data = self.tree.item(item)['values']

                self.Label0 = tk.Label(self.root, text="姓名")
                self.Label0.grid(row=0, column=11)

                self.entry00 = tk.StringVar()
                self.entry00.set(row_data[0])
                self.entry0 = tk.Entry(self.root, textvariable=self.entry00, width=15)
                self.entry0.grid(row=1, column=11)

                self.Label1 = tk.Label(self.root, text="年龄")
                self.Label1.grid(row=2, column=11)

                self.entry01 = tk.StringVar()
                self.entry01.set(row_data[1])
                self.entry1 = tk.Entry(self.root, textvariable=self.entry01, width=15)
                self.entry1.grid(row=3, column=11)

                self.Label02 = tk.Label(self.root, text="城市")
                self.Label02.grid(row=4, column=11)

                self.entry02 = tk.StringVar()
                self.entry02.set(row_data[2])
                self.entry2 = tk.Entry(self.root, textvariable=self.entry02, width=15)
                self.entry2.grid(row=5, column=11)

                self.Button_1 = tk.Button(self.root, text="确定", command=self.edit_item)
                self.Button_1.grid(row=6, column=11, ipadx=10)
        else:
            self.Button1.bind("<Button-1>", self.window("未选中数据"))

    def edit_item(self):
        '''编辑数据'''
        selected_item = self.tree.selection()
        name = self.entry00.get()
        age = self.entry01.get()
        city = self.entry02.get()
        if name and age and city:
            self.tree.item(selected_item, values=(name, age, city))
        else:
            self.Button_1.bind("<Button-1>", self.window("输入框不可以为空"))

    def delete_item(self):
        '''删除数据'''
        selected_item = self.tree.selection()
        if selected_item:
            self.tree.delete(selected_item)
        else:
            self.Button2.bind("<Button-1>", self.window("未选中数据"))

    def window(e, text):
        '''创建弹窗'''
        messagebox.showinfo("提示", text)


if __name__ == '__main__':
    a = GUI()
    a.root.mainloop()

Insert image description here

4. Hide the default index column

    def interface(self):
        """"界面编写位置"""
        # 创建 Treeview 控件;设置高度为10行;只显示列名行,隐藏索引列
        self.tree = ttk.Treeview(self.root, height=10, show="headings")
        self.tree.grid(row=0, column=0, rowspan=10, columnspan=10, padx=60)
        # 定义列名
        self.tree["columns"] = ("Name", "Age", "City")
        # 设置列的标题名称
        self.tree.heading("Name", text="姓名")
        self.tree.heading("Age", text="年龄")
        self.tree.heading("City", text="城市")
        # 设置列宽度(像素)
        self.tree.column("Name", width=100, anchor="center")
        self.tree.column("Age", width=90, anchor="center")
        self.tree.column("City", width=150, anchor="center")
        # 插入默认数据
        self.tree.insert("", tk.END, values=("张三", "25", "深圳"))

Insert image description here

Continuously updating...

Guess you like

Origin blog.csdn.net/qq_45664055/article/details/131355928
Recommended