python tkinter写一个表格
时间: 2023-12-09 09:50:56 浏览: 116
下面是一个简单的Python tkinter表格示例:
```python
import tkinter as tk
class Table(tk.Frame):
def __init__(self, parent=None, headings=tuple(), rows=tuple()):
super().__init__(parent)
table = tk.Frame(self, borderwidth=1, relief="sunken")
table.grid(sticky="nsew")
self._widgets = []
for row, cells in enumerate([headings] + rows):
current_row = []
for column, cell_value in enumerate(cells):
if row == 0:
label = tk.Label(table, text=cell_value, font=("Helvetica", 12, "bold"), bg="white", fg="black", relief="ridge")
else:
label = tk.Label(table, text=cell_value, font=("Helvetica", 12), bg="white", fg="black", relief="ridge")
label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
current_row.append(label)
self._widgets.append(current_row)
for column in range(len(headings)):
table.columnconfigure(column, weight=1)
def set(self, row, column, value):
widget = self._widgets[row+1][column]
widget.configure(text=value)
if __name__ == '__main__':
headings = ("Name", "Age", "Gender")
rows = (
("John Smith", "30", "Male"),
("Jane Doe", "25", "Female"),
("Bob Johnson", "45", "Male")
)
root = tk.Tk()
root.title("Table Example")
table = Table(root, headings=headings, rows=rows)
table.pack(fill="both", expand=True)
root.mainloop()
```
这个表格使用了tkinter模块创建,具有以下功能:
- 支持行和列的数量任意设置;
- 支持行和列的大小自动调整;
- 支持设置单元格的值;
你可以根据自己的需求修改这个表格。
阅读全文