Python 使用 tkinter 和 pandas 导入 CSV 数据集
这段代码使用 Python 的 tkinter 和 pandas 库实现从 CSV 文件导入数据集的功能,并使用滚动文本框展示数据内容。代码中使用了 filedialog 和 scrolledtext 模块,需要确保已安装这些库。
def load_data(self):
file_path = filedialog.askopenfilename(filetypes=[('CSV Files', '*.csv')])
print(file_path)
if file_path:
self.nroot_data = pd.read_csv(file_path, encoding='gbk')
self.nroot = tk.Tk()
self.nroot.geometry('600x400+400+50')
self.nroot.resizable(True, True)
self.nroot.title('导入数据集')
self.nroot_model_val = tk.StringVar(self.nroot)
self.nscr = scrolledtext.ScrolledText(self.nroot, width=65, height=20,font=('隶书', 12)) # 滚动文本框(宽,高(这里的高应该是以行数为单位),字体样式)
self.nscr.place(x=20, y=10)
self.nroot_button = tk.Button(self.nroot, text='确定', command=self.nroot_getdata, width=20)
self.nroot_button.place(x=20, y=360)
self.nroot_button = tk.Button(self.nroot, text='取消', command=self.nroot_close, width=20)
self.nroot_button.place(x=180, y=360)
f = open(file_path, 'r', encoding='gbk')
for item in f.readlines():
self.nscr.insert(END, item)
self.nroot.mainloop()
代码中使用了 filedialog 模块来打开文件选择对话框,并使用 pandas 库读取 CSV 文件。代码还创建了一个 tkinter 窗口,并使用 scrolledtext 模块展示数据内容。
注意:
- 代码需要在 Python 环境中运行,并确保已安装
tkinter、pandas、filedialog和scrolledtext库。 - 代码中的
gbk编码用于读取中文数据,如果你的 CSV 文件使用其他编码,需要修改代码中的编码参数。 self.nroot_getdata和self.nroot_close函数需要根据实际情况进行定义。
原文地址: https://www.cveoy.top/t/topic/oPQQ 著作权归作者所有。请勿转载和采集!