ValueError: Invalid file path or buffer object type: class tkinter.StringVar

2024/10/13 7:22:57

Here is a simplified version of some code that I have. In the first frame, the user selects a csv file using 'tk.filedialog' and it is meant to be plotted on the same frame on the canvas.

There is also a second frame that is capable of plotting the graph in case it is easier to do it across a different frame.

Running this version of the code results in the error: "ValueError: Invalid file path or buffer object type: ". I am not sure how to get this code to work without this problem occurring, so that the user selected file plots on the empty graph with columns 'a' and 'b'.

import csv
import pandas as pd
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
from tkinter import messagebox
import matplotlibmatplotlib.use("TkAgg")from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAggfrom matplotlib.figure import Figurefig = Figure(figsize=(5,4), dpi=100)
ax= fig.add_subplot(111)LARGE_FONT= ("Verdana", 12)class GUI(tk.Tk):def __init__(self, *args, **kwargs):tk.Tk.__init__(self, *args, **kwargs)tk.Tk.wm_title(self, "GUI")container = tk.Frame(self)container.pack(side="top", fill="both", expand = True)container.grid_rowconfigure(0, weight=1)container.grid_columnconfigure(0, weight=1)self.frames = {}for F in (Home, Graph):frame = F(container, self)self.frames[F] = frameframe.grid(row=0, column=0, sticky="nsew")self.show_frame(Home)def show_frame(self, cont):frame = self.frames[cont]frame.tkraise()class Home(tk.Frame):def __init__(self, parent, controller):self.controller = controllertk.Frame.__init__(self,parent)label = tk.Label(self, text="Start Page", font=LARGE_FONT)label.pack(pady=10, padx=10)ftypes = [('CSV files','*.csv')]def browsefunc2():filename = tk.filedialog.askopenfilename(filetypes=ftypes)pathlabel2.config(text=filename)filename = filename.get()return filename#this line is just used to check that hard-coding in a filename works, which it does providing 'filename = tk.StringVar()' is removed#filename = '...'filename = tk.StringVar()df = pd.read_csv(filename, encoding='latin-1')browsebutton = tk.Button(self, borderwidth=0, text="Browse", command=browsefunc2, height=1, width=10)browsebutton.pack()pathlabel2 = tk.Label(self, borderwidth=0)pathlabel2.pack()canvas = FigureCanvasTkAgg(fig, self)df.plot.scatter('a', 'b', ax=ax)canvas.draw()canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)button2 = ttk.Button(self, text="Graph",command=lambda: controller.show_frame(Graph))button2.pack()class Graph(tk.Frame):def __init__(self, parent, controller):self.controller = controllertk.Frame.__init__(self,parent)label = tk.Label(self, text="Graph", font=LARGE_FONT)label.pack(pady=10,padx=10)canvas = FigureCanvasTkAgg(fig, self)#this line causes a problem as the dataframe is not recognised across framesdf.plot.scatter('a', 'b', ax=ax)canvas.draw()canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)button3 = ttk.Button(self, text="Back",command=lambda: controller.show_frame(Home))button3.pack()app = GUI()
app.mainloop()

As far as I'm aware it's not possible to upload a .csv file onto StackOverflow so I have recreated an example one, but the file type needs to be .csv.

a,b
1,10
2,32
3,23
4,5
5,4
6,66
7,7
8,19
9,31
10,44
Answer

I haven't run your 'simplified' version of the code because it's by no means a Minimal, Complete, and Verifiable example.

The error tells you that you're assuming something is a path or buffer when it is StringVar. I believe the error is on the line:

df = pd.read_csv(filename, encoding='latin-1')

this requires filename to be a path or buffer object where as on the very line above filename is indeed a StringVar object:

filename = tk.StringVar()df = pd.read_csv(filename, encoding='latin-1')

In order to reach the value of StringVar or any of the Variable subclass types, one needs to use get method.

filename.get()

However, that would result an empty string, '' which would raise another error.

https://en.xdnf.cn/q/69556.html

Related Q&A

Is there a way to reopen a socket?

I create many "short-term" sockets in some code that look like that :nb=1000 for i in range(nb):sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sck.connect((adr, prt)sck.send(question …

How django handles simultaneous requests with concurrency over global variables?

I have a django instance hosted via apache/mod_wsgi. I use pre_save and post_save signals to store the values before and after save for later comparisons. For that I use global variables to store the p…

Why cant I string.print()?

My understanding of the print() in both Python and Ruby (and other languages) is that it is a method on a string (or other types). Because it is so commonly used the syntax:print "hi"works.S…

Difference between R.scale() and sklearn.preprocessing.scale()

I am currently moving my data analysis from R to Python. When scaling a dataset in R i would use R.scale(), which in my understanding would do the following: (x-mean(x))/sd(x)To replace that function I…

Generate random timeseries data with dates

I am trying to generate random data(integers) with dates so that I can practice pandas data analytics commands on it and plot time series graphs. temp depth acceleration 2019-01-1 -0.218062 -1.21…

Spark select top values in RDD

The original dataset is:# (numbersofrating,title,avg_rating) newRDD =[(3,monster,4),(4,minions 3D,5),....] I want to select top N avg_ratings in newRDD.I use the following code,it has an error.selectne…

Python module BeautifulSoup extracting anchors href

i am using BeautifulSoup module to select all href from html by this way:def extract_links(html):soup = BeautifulSoup(html)anchors = soup.findAll(a)print anchorslinks = []for a in anchors:links.append(…

Pandas: how to get a particular group after groupby? [duplicate]

This question already has answers here:How to access subdataframes of pandas groupby by key(6 answers)Closed 9 years ago.I want to group a dataframe by a column, called A, and inspect a particular grou…

aws cli in cygwin - how to clean up differences in windows and cygwin style paths

I suspect this is my ineptitude in getting path variables set right, but Im at a loss.Ive installed the aws cli using pip in cygwin.pip install awscliI have two python environments... a windows anacon…

Print all variables and their values [duplicate]

This question already has answers here:too many values to unpack, iterating over a dict. key=>string, value=>list(8 answers)Closed 6 years ago.This question has been asked quite a bit, and Ive tr…