打开至少两个 csv 文件并使用 tkinter 按钮合并它们

Opening at least two csv files and merging them using tkinter button

我想打开多个文件(至少两个)并将它们存储到单独的变量中,这样我就可以使用 pandas 合并它们,但所有操作都通过单击 tkinter 按钮完成。我已经坚持了两天了。我知道我应该使用 类(OOP) python,但这不是我的强项,因为我仍然是初学者...任何在正确方向上的帮助将不胜感激。我的代码片段:

importing all libraries
import tkinter
from sys import path
from tkinter import *

from tkinter import ttk, messagebox
from tkinter import filedialog as fd
from tkinter.messagebox import showinfo
from tkinter.messagebox import showerror
from tkinter.filedialog import asksaveasfile
from PIL import ImageTk, Image

import pandas as pd

browse_button = Button(btn_frame, text='Browse File', command=lambda: file_dialog(),
                       font=('helvetica', 10, 'bold'), bg='#ebdec5')
browse_button.grid(row=0, column=1, padx=10, pady=30)

load_button = Button(btn_frame, text='Load Data', command=lambda: merge_files(),
                     font=('helvetica', 10, 'bold'), bg='#ebdec5')
load_button.grid(row=0, column=2, padx=10, pady=40)

label_file = Label(btn_frame, text=browse_filetxt, font=('helvetica', 9, 'bold'), bg='#ebdec5')
label_file.place(rely=0, relx=0)


## file dialog to load files,how to load more than one, and and assign variables that can be used...

def file_dialog():
    try:

        file_name = fd.askopenfilename(initialdir='/',
                                       title='Select a file',
                                       filetypes=(('csv files', '*.csv'), ('All files', '*.*')))

    except FileNotFoundError:

        tkinter.messagebox.showerror('Information', "File not found")
        return None

    label_file['text'] = file_name


def merge_files():
    global df
    file_path = label_file['text']
    try:
        csv_filename = r'{}'.format(file_path)
        df = pd.read_csv(csv_filename, delimiter=',')

        # How to place files into variables.....
        # what goes here..Please help

    except ValueError:
        tkinter.messagebox.showerror('Information', 'File is invalid')
        return None
    except FileNotFoundError:
        tkinter.messagebox.showerror('Information', "File not found")

## I want to load two ore more files, put them into different variables, then use the variables,
# to merge both csv files using pandas......

您应该使用列表来保存所有 selected 文件。这样你可以有任意数量的文件,你可以使用 for-loop 来处理所有文件名

all_files = [] 

当你select文件

def file_dialog():
    global all_files

    try:
        file_name = fd.askopenfilename(initialdir='/home/furas/test',
                                       title='Select a file',
                                       filetypes=(('csv files', '*.csv'), ('All files', '*.*')))

    except FileNotFoundError:
        tkinter.messagebox.showerror('Information', "File not found")
        return

    # check if not pressed `Cancel`
    if file_name:
        all_files.append( file_name )

稍后您可以合并它们

    df = pd.DataFrame() # create new empty dataframe
    
    for filename in all_files:
        print('filename:', filename)
        
        try:
            new_df = pd.read_csv(filename, delimiter=',')
            df = df.append(new_df)    # <--- inside `try/except`
        except ValueError:
            tkinter.messagebox.showerror('Information', 'File is invalid')
        except FileNotFoundError:
            tkinter.messagebox.showerror('Information', "File not found")
        
    print(df.to_string())

最小工作示例:

import tkinter as tk
from tkinter import filedialog as fd
import pandas as pd

# --- functions ---

def file_dialog():
    global all_files

    print('[file_dialog]')
    
    try:
        file_name = fd.askopenfilename(initialdir='/home/furas/test',
                                       title='Select a file',
                                       filetypes=(('csv files', '*.csv'), ('All files', '*.*')))

    except FileNotFoundError:
        tkinter.messagebox.showerror('Information', "File not found")
        return

    # check if not pressed `Cancel`
    if file_name:
        all_files.append( file_name )


def merge_files():
    global df
    global all_files
    
    print('[merge_files]')
    
    df = pd.DataFrame() # create new empty dataframe
    
    for filename in all_files:
        print('filename:', filename)
        
        try:
            new_df = pd.read_csv(filename, delimiter=',')
            df = df.append(new_df)
        except ValueError:
            tkinter.messagebox.showerror('Information', 'File is invalid')
        except FileNotFoundError:
            tkinter.messagebox.showerror('Information', "File not found")
    
        
        
    print(df.to_string())
    
    # remove all filenames
    all_files = []
    
# --- main ---

df = pd.DataFrame() # create empty dataframe at start (as default value)
all_files = []      # create empty list at start (as default value)

root = tk.Tk()

browse_button = tk.Button(root, text='Browse File', command=file_dialog)
browse_button.pack(fill='x')

load_button = tk.Button(root, text='Load Data', command=merge_files)
load_button.pack(fill='x')

root.mainloop()

编辑:

还有 askopenfilenames 以 char s 结尾,一次 select 许多文件名。

它为 list/tuple 提供所有 selected 文件名,您可以将其分配给全局变量(并替换所有以前的文件名)或使用 extend()+= 添加现有列表的文件名

    file_names = fd.askopenfilenames(...)

    # check if not pressed `Cancel`
    if file_names:
        #all_files.extend( file_names )  # add to existing list 
        #all_files += file_names         # add to existing list  
        all_files = file_names           # replace previous list