Python Tkinter 表格组件

需求

我想在 tkinter 做的 python GUI 程序中加入一个表格,由于官方库没有表格这个组件,只能找社区组件或者自己造一个表格组件。

方案一

通过 grid 布局功能,造一个简单的表格。缺点是和其他组件配合构造 GUI 就不太方便。

使用

from tkinter import *

root = Tk()

height = 10
width = 5
cells = {}
for i in range(height): #Rows
    for j in range(width): #Columns
        b = Entry(root, text="")
        b.grid(row=i, column=j)
        cells[(i,j)] = b

mainloop()

方案二

采用社区已有组件 tksheet,一个用 tkinter canvas 手动绘制的表格

github 地址:https://github.com/ragardner/tksheet

支持多达数亿个单元格的大数据渲染,只重绘表格的可见部分,所以能运行得相当流畅。

还支持单元格颜色和背景。

使用

确保 Python 3.6+版本,安装依赖

pip install tksheet

使用

from tksheet import Sheet
import tkinter as tk


class demo(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.grid_columnconfigure(0, weight = 1)
        self.grid_rowconfigure(0, weight = 1)
        self.frame = tk.Frame(self)
        self.frame.grid_columnconfigure(0, weight = 1)
        self.frame.grid_rowconfigure(0, weight = 1)
        self.sheet = Sheet(self.frame,
                           data = [[f"Row {r}, Column {c}\nnewline1\nnewline2" for c in range(50)] for r in range(500)])
        self.sheet.enable_bindings()
        self.frame.grid(row = 0, column = 0, sticky = "nswe")
        self.sheet.grid(row = 0, column = 0, sticky = "nswe")


app = demo()
app.mainloop()

tksheet

参考

评论