创建 Tkinter 表

Salman Mehmood 2024年2月15日
创建 Tkinter 表

你可以在更广泛的应用程序中将 GUI 用作独立或集成应用程序。

本教程展示了如何在 Python 中创建 Tkinter 表,并且我们将讨论与 Python 中的 Tkinter 表相关的方法。

在 Tkinter 中使用 Entry 组件创建表

Tkinter 帮助创建表格,但它不为表格组件提供用户界面。你可以通过在行和列中重复显示条目组件来创建表格。

然而,要制作一个六行四列的表格,我们将不得不使用一个 for 循环(见下文)。

for i in range(6):
    for j in range(4):

我们需要通过创建一个 Entry 类对象在这些循环中创建一个 Entry 组件(见下文)。

entry = Entry(gui, width=22, fg="blue", font=("Arial", 15, "bold"))

现在,我们需要在行和列中设置这个交集。这可以使用 grid() 方法来完成,我们可以在其中将行和列作为参数传递,如下所示。

# here row and column indicate
# row and column positions
entry.grid(row=row, column=column)

现在我们可以使用 insert() 方法将数据插入 Entry 组件(见下文)。

entry.insert(END, data)

insert() 方法有两个参数,ENDdataEnd 参数负责在 Entry() 组件中的先前数据的末尾添加连续数据。

你将自己创建 data 参数;它可以是列表、Excel 工作表或数据库。

这是在下面的系统中使用列表中的数据的逻辑方法。在这段代码中,我们获取一个包含 6 个元组的列表,每个元组包含四个值,分别是 Employee idNameCityAge

因此,我们将有一个每行 6 行 4 列的表。该程序还可以与 Excel 工作表或数据库一起使用,以表格格式显示所有数据。

from tkinter import *

# Table class


class Table:
    # Initialize a constructor
    def __init__(self, gui):

        # An approach for creating the table
        for i in range(total_rows):
            for j in range(total_columns):
                print(i)
                if i == 0:
                    self.entry = Entry(
                        gui,
                        width=20,
                        bg="LightSteelBlue",
                        fg="Black",
                        font=("Arial", 16, "bold"),
                    )
                else:
                    self.entry = Entry(gui, width=20, fg="blue", font=("Arial", 16, ""))

                self.entry.grid(row=i, column=j)
                self.entry.insert(END, employee_list[i][j])


# take the data
employee_list = [
    ("ID", "Name", "City", "Age"),
    (1, "Gorge", "California", 30),
    (2, "Maria", "New York", 19),
    (3, "Albert", "Berlin", 22),
    (4, "Harry", "Chicago", 19),
    (5, "Vanessa", "Boston", 31),
    (6, "Ali", "Karachi", 30),
]

# find total number of rows and
# columns in list
total_rows = len(employee_list)
total_columns = len(employee_list[0])

# create root window
gui = Tk()
table = Table(gui)
gui.mainloop()

输出:

tkinter 表

作者: Salman Mehmood
Salman Mehmood avatar Salman Mehmood avatar

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

LinkedIn