Kelley
Kelley

Reputation: 1

Passing a string to file type in tkinter.filedialog.askopenfile fails

I have edited and tried using () instead of [] in the string. I have used single quotes and double quotes. I can print the string, copy it and paste it in the filetypes=[('HTML', '*.html')] and it works but I can not get it to except a string.

strFileTypes = '[(' + "'" + 'HTML'"'" + ', ' + "'" + '*.html' + "')]"
strFolder = 'C:\\Users\\Kelley\\Documents'
strFileName = ''
strFile = ''
parent = filedialog.Tk()
parent.eval('tk::PlaceWindow . center')
parent.withdraw()
strFile = filedialog.askopenfile(initialdir=strFolder, title='Open', filetypes=strFileTypes)
if strFile is None:
    # no file selected
    exit()
Exception has occurred: TclError
bad file type "[", should be "typeName {extension ?extensions ...?} ?{macType ?macTypes ...?}?"
  File "C:\Users\Kelley\Documents\Python\Environments\Capture\capture.py", line 11, in <module>
    strFile = filedialog.askopenfile(initialdir=strFolder, title='Open', filetypes=strFileTypes)

Upvotes: 0

Views: 189

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386332

filetypes needs to be a list, not a string that looks like a list.

filetypes = [('HTML', '*.html')]
strFile = filedialog.askopenfile(initialdir=strFolder, title='Open', filetypes=filetypes)

Also, askopenfile doesn't return a string as your variable name implies. It returns an open file handle. If you are expecting to get the filename as a string you should call askopenfilename.

Upvotes: 2

Related Questions