def read_file():
filename = radio_var.get()
data = pd.read_excel(f"results-{filename}.xlsx")
code
# Clear the existing table
for row in tree.get_children():
tree.delete(row)
# Update the table with the new data
for index, row in data.iterrows():
tree.insert('', 'end', values=(index + 1, *row))
def sort_table(col, order):
data = [tree.item(child)['values'] for child in tree.get_children()]
data.sort(key=lambda x: x[col], reverse=not order)
code
# Update the table with the sorted data
for i, item in enumerate(data):
tree.item(item[0], values=(i + 1, *item[1:]))
tree.heading(col, command=lambda: sort_table(col, not order))
radio_var = tk.StringVar(value='1-day')
for text in ['day', '1-hour', '4-hour', '30-minute']:
tk.Radiobutton(root, text=text, variable=radio_var, value=text).pack(side='left')
tree = ttk.Treeview(root, columns=columns, show='headings')
tree.bind('', on_double_click)
Add headings and set their sort function
for i, (col, width) in enumerate(zip(columns, column_widths)):
tree.column(col, width=width)
tree.heading(col, text=col, command=lambda col=i: sort_table(col, True))
tree.pack()
root.mainloop()这个代码无法排序,请修正一下
import tkinter as tk
from tkinter import ttk, messagebox
import pandas as pd
def read_file():
filename = radio_var.get()
data = pd.read_excel(f"results-{filename}.xlsx")
# Clear the existing table
for row in tree.get_children():
tree.delete(row)
# Update the table with the new data
for index, row in data.iterrows():
tree.insert('', 'end', values=(index + 1, *row))
def sort_table(col, order):
data = [tree.item(child)['values'] for child in tree.get_children()]
data.sort(key=lambda x: x[col], reverse=not order)
# Update the table with the sorted data
for i, item in enumerate(data):
tree.item(item[0], values=(i + 1, *item[1:]))
tree.heading(col, command=lambda: sort_table(col, not order))
# Re-bind the sort function for each column
for i, col in enumerate(columns):
tree.heading(col, command=lambda col=col: sort_table(columns.index(col), True))
def on_double_click(event):
item_id = tree.focus()
cell_value = tree.item(item_id)['values'][1]
messagebox.showinfo('Cell value', cell_value)
root = tk.Tk()
# Radio buttons
radio_var = tk.StringVar(value='1-day')
for text in ['day', '1-hour', '4-hour', '30-minute']:
tk.Radiobutton(root, text=text, variable=radio_var, value=text).pack(side='left')
# Read button
tk.Button(root, text='Read', command=read_file).pack(side='left')
# Table
columns = ('index', 'a', 'b', 'c', 'd', 'e', 'f', 'g')
column_widths = [50, 100, 100, 100, 100, 100, 100, 100]
tree = ttk.Treeview(root, columns=columns, show='headings')
tree.bind('<Double-1>', on_double_click)
# Add headings and set their sort function
for i, (col, width) in enumerate(zip(columns, column_widths)):
tree.column(col, width=width)
tree.heading(col, text=col, command=lambda col=col: sort_table(columns.index(col), True))
tree.pack()
root.mainloop()