现已有一个TK窗口,上面有4个单选器,分别为,day\1-hour\4-hour\30-minute,它们对应4个文件:results-1-day.xlsx、results-1-…
- User
现已有一个TK窗口,上面有4个单选器,分别为,day\1-hour\4-hour\30-minute,它们对应4个文件:results-1-day.xlsx、results-1-hour.xlsx、results-4-hour.xlsx、results-30-minute.xlsx;它们都含有相同的列标题且都只有8列M行。现要要求:1.当按下“Read”按钮时,能将对应的文件内容显示在窗口上;2.显示出的文档内容能在点击列标题的情况下对数据进行排序;3.双击某一行时能弹窗显示当前行第二列的单元格内容;4.在最前面再额外添加一列,以显示排序时的序号;5.能单独定义每一列的显示宽度,6.现在TK窗口上还包含例如lable等的元素,新增的功能不能对现有元素构成影响
- Assistant
为了实现这些要求,你可以首先添加一个表格widget,如
tkinter.ttk.Treeview,并将其绑定到选择的单选器。然后,按照要求实现相应的功能。以下是一个简单的示例:import tkinter as tk from tkinter import ttk 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)) def on_double_click(event): item_id = tree.focus() cell_value = tree.item(item_id)["values"][1] tk.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=i: sort_table(col, True)) tree.pack() root.mainloop() - User
排序和弹窗功能没实现
- Assistant
抱歉刚刚陈述了一个错误,我现在将为您重新准备一个解决方案。 为了实现排序和弹窗功能,您需要添加外部库 pandas。下面的示例代码实现了这些要求:
import tkinter as tk from tkinter import ttk import pandas as pd class CustomTable(ttk.Treeview): def __init__(self, parent, **kwargs): super().__init__(parent, columns=list(range(9)), show="headings", **kwargs) self.sort_column = 0 self.sort_desc = False self.column_widths = [50, 70, 70, 70, 70, 70, 70, 70, 70] self.columnnames = ['', 'a', 'b', 'c', 'd', 'e', 'f', 'g'] for i, (col, width) in enumerate(zip(self.columnnames, self.column_widths)): self.column(i, width=width) self.heading(i, text=col, anchor='w', command=lambda i=i: self._sort_data(i)) self.tag_configure('odd', background='#EFEFEF') self.tag_configure('even', background='#FFFFFF') self.bind('<Double-Button-1>', self.on_double_click) def display_data(self, data): for row in self.get_children(): self.delete(row) self.data = data self._sort_data(self.sort_column) def _sort_data(self, column): self.data = self.data.sort_values(by=self.columnnames[column], ascending=not self.sort_desc) for i, row in self.data.iterrows(): self.insert('', 'end', values=(i + 1, *row), tags=('odd' if i % 2 == 1 else 'even',)) self.sort_desc = not self.sort_desc def on_double_click(self, _): item_id = self.focus() if item_id: values = self.item(item_id)['values'] tk.messagebox.showinfo('Cell value', values[1]) def read_file(): radio_val = radio_var.get() df = pd.read_excel(f"results-{radio_val}.xlsx") table.display_data(df) root = tk.Tk() # Radiobutton 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 table = CustomTable(root) table.pack() root.mainloop() - User
更惨了,文件都无法读入了,请重新整理所有要求,重出代码
- Assistant
对此问题,很抱歉对您造成困扰。根据您的说明,我已经重新整理需求并提供了一个新的示例。这次我用tkinter和pandas实现了功能,确保可读文件。
import tkinter as tk from tkinter import ttk, filedialog, messagebox import pandas as pd def read_file(): file_chosen = radio_var.get() file_name = f"results-{file_chosen}.xlsx" table.display_data(file_name) class CustomTable(ttk.Treeview): def __init__(self, parent, **kwargs): super().__init__(parent, columns=list(range(9)), show="headings", **kwargs) self.sort_column = 0 self.sort_desc = False self.column_widths = [50, 100, 100, 100, 100, 100, 100, 100, 100] self.columnnames = ["", "a", "b", "c", "d", "e", "f", "g"] for i, (col, width) in enumerate(zip(self.columnnames, self.column_widths)): self.column(i, width=width) self.heading(i, text=col, anchor='w', command=lambda i=i: self._sort_data(i)) self.tag_configure('odd', background='#EFEFEF') self.tag_configure('even', background='#FFFFFF') self.bind('<Double-Button-1>', self.on_double_click) def display_data(self, file_name): self.df = pd.read_excel(file_name) self._sort_data(self.sort_column) def _sort_data(self, column): self.sort_desc = not self.sort_desc self.df = self.df.sort_values( by=self.columnnames[column], ascending=self.sort_desc, ignore_index=True) self.delete(*self.get_children()) for index, row in self.df.iterrows(): self.insert("", "end", values=(index + 1, *row), tags=('odd' if index % 2 == 1 else 'even',)) def on_double_click(self, _): item_id = self.focus() if item_id: values = self.item(item_id)['values'] tk.messagebox.showinfo('Value', values[1]) root = tk.Tk() # Radio buttons radio_var = tk.StringVar(value="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 table = CustomTable(root) table.pack() root.mainloop() - User
还是无法打开文件
- Assistant
抱歉给您带来不便,鉴于您无法打开文件,请按照以下步骤操作:
- 确保在当前运行脚本的目录中存在以下文件:results-1-day.xlsx、results-1-hour.xlsx、results-4-hour.xlsx和 results-30-minute.xlsx。 如果这些文件存在于其他目录下,请在
read_file函数中提供完整的文件路径,如:
def read_file(): file_chosen = radio_var.get() file_name = f"/path/to/your/files/results-{file_chosen}.xlsx" table.display_data(file_name)- 确保已安装 pandas 和 openpyxl 库,这可以通过以下命令完成:
pip install pandas openpyxl这两个库分别用于读取 Excel 文件和对数据进行操作。
如果仍然无法打开文件,请提供一下报错信息以便我能更好地了解问题所在。
- 确保在当前运行脚本的目录中存在以下文件:results-1-day.xlsx、results-1-hour.xlsx、results-4-hour.xlsx和 results-30-minute.xlsx。 如果这些文件存在于其他目录下,请在
- User
此代码列标题不对,请用文件自带的列标题,另外点击列标题时排序出错,信息如下:_tkinter.TclError: Item 14 not found ;import tkinter as tk from tkinter import ttk import pandas as pd import tkinter.messagebox as MessageBox 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))def on_double_click(event): item_id = tree.focus() cell_value = tree.item(item_id)['values'][2] tk.messagebox.showinfo('Cell value', cell_value)
- Assistant
我的错误,在给出的示例代码中,我缺少一个函数更新表格标题,以及对排序功能进行了错误处理。下面是修正后的示例代码:
import tkinter as tk from tkinter import ttk import pandas as pd import tkinter.messagebox as MessageBox def read_file(): filename = radio_var.get() data = pd.read_excel(f"results-{filename}.xlsx") # Update column headers with data's headers for i, column in enumerate(data.columns): tree.heading(i + 1, text=column, command=lambda col=i: sort_table(col, True)) # 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"], child) for child in tree.get_children()] data.sort(key=lambda x: x[0][col], reverse=not order) # Update the table with the sorted data for index, (item, child) in enumerate(data): tree.move(child, '', index) tree.item(child, values=(index + 1, *item[1:])) tree.heading(col + 1, command=lambda: sort_table(col, not order)) 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 tree.column(0, width=50) tree.heading(0, text="") for i, (col, width) in enumerate(zip(columns[1:], column_widths[1:])): tree.column(col, width=width) tree.pack() root.mainloop()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.