import tkinter as tk
from tkinter import ttk
import pandas as pd
import tkinter.messagebox as MessageBox
def on_double_click(event):
item = tree.selection()[0]
value = tree.item(item, 'values')[2] # 获取原表格中的第二列(现在是第一列)的值
MessageBox.showinfo('提醒', f"单元格内容:{value}")
def sort_column(treeview, col, reverse):
items = [treeview.item(item)['values'] for item in treeview.get_children()]
items.sort(key=lambda x: x[col], reverse=reverse)
for index, item in enumerate(items):
treeview.item(treeview.get_children()[index], values=item)
treeview.set(treeview.get_children()[index], column=0, value=index+1)
if not reverse:
treeview.heading(col, command=lambda _col=col: sort_column(treeview, _col, True))
else:
treeview.heading(col, command=lambda _col=col: sort_column(treeview, _col, False))
def show_table():
file_path = 'results-1-day_sorted.xlsx' # 请替换为实际文件路径
df = pd.read_excel(file_path)
code Copy code
# 添加数据行
for index, row in df.iterrows():
tree.insert('', 'end', values=(index+1, *row)) # 添加序号和数据行
root = tk.Tk()
root.title('Excel内容')
创建滚动条
scrollbar = tk.Scrollbar(root, orient='vertical')
创建TreeView并绑定滚动条
tree = ttk.Treeview(root, columns=['#0'], show='headings', yscrollcommand=scrollbar.set)
scrollbar.config(command=tree.yview)
file_path = 'results-1-day_sorted.xlsx' # 请替换为实际文件路径
df = pd.read_excel(file_path)
添加列
tree.column('#0', width=10) # 设置序号列宽度
tree.heading('#0', text='序号')
设置列宽度的列表
column_widths = [20, 100, 200, 100, 150, 80, 120, 90]
for index, column in enumerate(df.columns):
tree.column(index, width=column_widths[index]) # 设置每一列的宽度
tree.heading(index+1, text=column, command=lambda _col=index+1: sort_column(tree, _col, False))
tree.bind('', on_double_click) # 双击事件绑定
使用place定位Treeview
tree.place(x=20, y=200)
使用place定位滚动条
scrollbar.place(x=20 + tree.winfo_reqwidth(), y=20, height=tree.winfo_reqheight())
创建显示按钮并绑定 show_table 函数
show_button = tk.Button(root, text='显示表格', command=show_table)
show_button.place(x=20, y=20)
root.mainloop()