LMP2016 LMP2016 - 3 months ago 21
Python Question

Python 3.5 - Tkinter Using variables for filenames + paths

I have a combo box which always sets two variables

1) is a filename (.csv)

2) is a file path location

Depending on what is selected in the combo box, a particular .csv file is allocated to variable

csvfilename
and a path is allocated to
path


I'm trying to feed these variables into the below code to load certain files from a fixed file location.

with open(csvfilename) as csvfile:


and

self.DwgOutputBox.tag_bind("dwg", "<ButtonRelease-1>", lambda event, filename=path + '/' + linkname: subprocess.run(filename, shell=True))


however I'm getting a

"TypeError: unsupported operand type(s) for +: 'StringVar' and 'str'"
message when testing using the PATH variable

and a

with open(csvfilename) as csvfile: TypeError: invalid file: tkinter.StringVar object at 0x024F4F50
when trying to use the csv variable.

When I test the code by setting the path and csv filename myself it works correctly, so it appears to be an issue with either not being able to use variables for file names or my syntax is incorrect.

Answer

path is a StringVar object, and you are trying to add / to it.

Instead of trying to define a keyword argument, pass in the StringVar objects (path and linkname) and get their values in the lambda:

self.DwgOutputBox.tag_bind(
    "dwg", "<ButtonRelease-1>",
    lambda event, path=path, linkname=linkname: subprocess.run(
        os.path.join(path.get(), linkname.get()), shell=True))

The path.get() call retrieves the current value of the StringVar object. I used os.path.join() instead of manual concatenation so that your code also works on an OS where the path separator is not /.

You'll have to do something similar for the with open(...) call; retrieve the string values contained in the StringVar objects.