在 Tkinter 中如何最好地在表格中显示数据?


一般来说,我们会以表格的形式来呈现数据。一个表格包含一组行和列。表格中的数据将以行和列的形式顺序地存储。

假设我们正在构建一个 Tkinter 应用程序,其中我们必须将学生数据存储在表格中的某个位置。该表格结构包含 3 列,用于存储学生的姓氏、名字和学号。为了显示此类信息,Tkinter 提供了一个 **Notebook** 小部件,我们可以在其中以表格的形式存储数据。

实例

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Create an object of Style widget
style = ttk.Style()
style.theme_use('clam')

# Add a Treeview widget
tree = ttk.Treeview(win, column=("FName", "LName", "Roll No"), show='headings', height=5)
tree.column("# 1", anchor=CENTER)
tree.heading("# 1", text="FName")
tree.column("# 2", anchor=CENTER)
tree.heading("# 2", text="LName")
tree.column("# 3", anchor=CENTER)
tree.heading("# 3", text="Roll No")

# Insert the data in Treeview widget
tree.insert('', 'end', text="1", values=('Amit', 'Kumar', '17701'))
tree.insert('', 'end', text="1", values=('Ankush', 'Mathur', '17702'))
tree.insert('', 'end', text="1", values=('Manisha', 'Joshi', '17703'))
tree.insert('', 'end', text="1", values=('Shivam', 'Mehrotra', '17704'))

tree.pack()

win.mainloop()

输出

如果我们运行上述代码,它将显示一个包含表格的窗口,该表格中有一些学生数据。

更新于: 18-6-2021

6K+ 浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.