abishek kumaresan abishek kumaresan - 1 month ago 34
Python Question

Opening and Reading a csv file using read_csv from Tkinter GUI

from tkinter import filedialog, Label, Button, Entry, StringVar
from tkinter.filedialog import askopenfile
import pandas as pd

root = tk.Tk()
Label(root, text='File Path').grid(row=0, column=0)
v = StringVar()
entry = Entry(root, textvariable=v).grid(row=0, column=1)
Button(root, text='Browse Data Set',command=lambda: v.set(askopenfile())).grid(row=1, column=0)
Button(root, text='Close',command=root.quit()).grid(row=1, column=1)
root.file = v.get()
df = pd.read_csv(root.file)

I want to open a dataset (CSV file) on the click of a button and read it using
function i am getting some errors

Traceback (most recent call last):
File "/home/abishek/PycharmProjects/untitled1/temp.py", line 21, in <module>
df = pd.read_csv(root.file)
File "/usr/lib/python3/dist-packages/pandas/io/parsers.py", line 498, in parser_f
return _read(filepath_or_buffer, kwds)
File "/usr/lib/python3/dist-packages/pandas/io/parsers.py", line 275, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "/usr/lib/python3/dist-packages/pandas/io/parsers.py", line 590, in __init__
File "/usr/lib/python3/dist-packages/pandas/io/parsers.py", line 731, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "/usr/lib/python3/dist-packages/pandas/io/parsers.py", line 1103, in __init__
self._reader = _parser.TextReader(src, **kwds)
File "pandas/parser.pyx", line 353, in pandas.parser.TextReader.__cinit__ (pandas/parser.c:3246)
File "pandas/parser.pyx", line 591, in pandas.parser.TextReader._setup_parser_source (pandas/parser.c:6111)
OSError: File b'' does not exist

Process finished with exit code 1

Please Help me with this one i am new to Tkinter


As suggested by @Kevin, you need to put some of the functionality in to a function that is called when the button is pressed. I've provided an example (I don't have pandas installed, so the pandas part is commented out). You also should be using askopenfilename not askopenfile. I've also fixed your close button, note I've changed it to root.destroy and I haven't put () at the end.

import tkinter as tk
from tkinter.filedialog import askopenfilename
#import pandas as pd

def import_csv_data():
    global v
    csv_file_path = askopenfilename()
    #df = pd.read_csv(csv_file_path)

root = tk.Tk()
tk.Label(root, text='File Path').grid(row=0, column=0)
v = tk.StringVar()
entry = tk.Entry(root, textvariable=v).grid(row=0, column=1)
tk.Button(root, text='Browse Data Set',command=import_csv_data).grid(row=1, column=0)
tk.Button(root, text='Close',command=root.destroy).grid(row=1, column=1)