以下是一个简单的 Python 代码示例,用于导入 CSV 文件并在 Python 界面中以 CSV 格式查看其内容,无需打开新的窗口:

import tkinter as tk
import csv

class CSVViewer(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.import_button = tk.Button(self, text='导入文件', command=self.import_file)
        self.import_button.grid(row=0, column=0)

        self.csv_text = tk.Text(self, height=20, width=50)
        self.csv_text.grid(row=1, column=0)

    def import_file(self):
        file_path = tk.filedialog.askopenfilename(filetypes=[('CSV文件', '*.csv')])
        if file_path:
            with open(file_path, newline='') as csvfile:
                reader = csv.reader(csvfile)
                for row in reader:
                    self.csv_text.insert(tk.END, ','.join(row) + '\n')

root = tk.Tk()
app = CSVViewer(master=root)
app.mainloop()

在这个代码中,我们创建了一个名为 CSVViewer 的类,它继承了 tkinterFrame 类。在初始化方法中,我们创建了一个按钮和一个文本框,用于显示 CSV 文件的内容。当用户点击按钮时,我们会调用 import_file 方法来打开一个文件对话框,让用户选择要导入的 CSV 文件。然后,我们使用 Python 的 csv 库读取该文件,并将其内容显示在文本框中。

需要注意的是,我们使用了 tkinter 的文件对话框来让用户选择 CSV 文件。这需要我们在代码中导入 tkinterfiledialog 模块。如果您在使用该代码时遇到任何问题,请确保已经正确导入了该模块。

Python tkinter 导入 CSV 文件并查看内容 (无需新窗口)

原文地址: https://www.cveoy.top/t/topic/n2tF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录