🐕

Tkinter csvフォルダ選択GUI

2023/09/13に公開
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from pathlib import Path


class DataModel:
    def __init__(self):
        self.selected_folder = None
        self.selected_files = []

    def set_selected_folder(self, folder_path):
        self.selected_folder = folder_path
        self.selected_files = []

    def add_selected_file(self, file_path):
        self.selected_files.append(file_path)

    def clear_selected_file(self):
        self.selected_files = []


class FolderSelectionView(tk.Frame):
    def __init__(self, master, data_model, file_selection_view):
        super().__init__(master)
        self.data_model = data_model
        self.file_selection_view = file_selection_view
        self.create_widgets()

    def create_widgets(self):
        folder_label = tk.Label(self, text="Selected Folder:")
        folder_label.grid(row=0, column=1, padx=5, pady=5, sticky="w")

        self.folder_text = tk.Label(self, text="")
        self.folder_text.grid(row=0, column=2, padx=5, pady=5, sticky="w")

        select_button = tk.Button(
            self, text="Select Folder", command=self.select_folder
        )
        select_button.grid(row=0, column=0, padx=5, pady=5)

        clear_selection_folder_button = tk.Button(
            self, text="Clear Folder", command=self.clear_selection_folder
        )
        clear_selection_folder_button.grid(row=1, column=0, padx=5, pady=5)

    def select_folder(self):
        folder_path = filedialog.askdirectory()
        if folder_path:
            self.data_model.set_selected_folder(folder_path)
            self.update_folder_text(folder_path)
            self.file_selection_view.update_treeview()

    def update_folder_text(self, folder_path):
        if self.folder_text:
            self.folder_text.config(text=folder_path)

    def clear_selection_folder(self):
        self.data_model.set_selected_folder(None)
        self.update_folder_text("")


class FileSelectionView(tk.Frame):
    def __init__(self, master, data_model):
        super().__init__(master)
        self.data_model = data_model
        self.treeview = None
        self.create_widgets()

    def create_widgets(self):
        self.treeview = ttk.Treeview(self, columns=("File Name", "File Size"))
        self.treeview.bind("<<TreeviewSelect>>", self.handle_treeview_select)
        self.treeview.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
        self.treeview.heading("#1", text="File Name")
        self.treeview.heading("#2", text="File Size")

        preview_button = tk.Button(self, text="Load CSV", command=self.loadCSV)
        preview_button.grid(row=1, column=3, padx=5, pady=5)

        clear_selection_tree_button = tk.Button(
            self, text="Clear Selection", command=self.clear_selection_tree
        )
        clear_selection_tree_button.grid(row=1, column=0, padx=5, pady=5)

    def update_treeview(self):
        self.treeview.delete(*self.treeview.get_children())
        folder = self.data_model.selected_folder
        if folder:
            for file in Path(folder).iterdir():
                if file.is_file() and file.suffix == ".csv":
                    file_size = file.stat().st_size
                    self.treeview.insert(
                        "", "end", values=(file.name, file_size)
                    )

    def clear_selection_tree(self):
        self.treeview.selection_remove(self.treeview.selection())

    def loadCSV(self):
        print(f"{list(self.data_model.selected_files)}")

    def handle_treeview_select(self, event):
        selected_items = self.treeview.selection()
        self.data_model.clear_selected_file()
        for item in selected_items:
            file_name = self.treeview.item(item, "values")[0]
            file_path = Path(self.data_model.selected_folder) / file_name
            self.data_model.add_selected_file(file_path)
        print(f"TreeViewで選択されているのは{len(self.data_model.selected_files)}個のファイル")


class ContentView(tk.Frame):
    def __init__(self, master, data_model):
        super().__init__(master)
        self.data_model = data_model
        self.file_selection_view = FileSelectionView(self, self.data_model)
        self.folder_selection_view = FolderSelectionView(
            self, self.data_model, self.file_selection_view
        )
        self.folder_selection_view.grid(
            row=0, column=0, padx=5, pady=5, sticky="w"
        )
        self.file_selection_view.grid(
            row=1, column=0, padx=5, pady=5, sticky="w"
        )
        self.create_widgets()

    def create_widgets(self):
        pass


class Application(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("CSV Viewer")
        # self.geometry("800x600")
        self.data_model = DataModel()
        self.content_view = ContentView(self, self.data_model)
        self.content_view.pack(fill=tk.BOTH, expand=True)


if __name__ == "__main__":
    app = Application()
    app.mainloop()

Discussion