Reputation: 623
So, I have this snippet of code:
def savefileas(self):
filename = "hello.json" #Do interface
f = tk.filedialog.asksaveasfilename(filetypes=("All files", "*."))
if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
return
f.close()
but, every time I try to run it, whatever i put on "filetype" (I've tried "json", ".json", "All files", "." and some others I've seen in examples around the web), it keeps returning with the same error on those lines:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Tibers\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "d:\Users\Tibers\Documents\GitHub\improved-broccoli\main.py", line 84, in savefileas
f = tk.filedialog.asksaveasfilename(filetypes=("All files", "*."))
File "C:\Users\Tibers\AppData\Local\Programs\Python\Python37-32\lib\tkinter\filedialog.py", line 380, in asksaveasfilename
return SaveAs(**options).show()
File "C:\Users\Tibers\AppData\Local\Programs\Python\Python37-32\lib\tkinter\commondialog.py", line 43, in show
s = w.tk.call(self.command, *w._options(self.options))
_tkinter.TclError: bad file type "*.", should be "typeName {extension ?extensions ...?} ?{macType ?macTypes ...?}?"
Why is that? and what do I need to do to fix it? (Preferably, I'd save the files as .json)
Upvotes: 0
Views: 3394
Reputation: 10592
From effbot:
filetypes
list
Sequence of (label, pattern) tuples. The same label may occur with several patterns. Use “*” as the pattern to indicate all files.
So filetypes
should be a list of tuples of the form (label, pattern)
. Right now you give it just one tuple, not a list of tuples. You can make it a list of one tuple or a list of multiple tuples, with the first being the default option.
So change the one tuple
f = tk.filedialog.asksaveasfilename(filetypes=("All files", "*."))
to a list of tuples like
f = tk.filedialog.asksaveasfilename(filetypes=[("All files", "*.*")])
or to have Json instead of all files like
f = filedialog.asksaveasfilename(filetypes=[("Json", '*.json')])
or add all files as a second option with Json being the default like
f = filedialog.asksaveasfilename(filetypes=[("Json", '*.json'), ("All files", "*.*")])
Upvotes: 3
Reputation: 487
As indicated in my comment, I'm pretty sure your issue is simply with formatting.
f = tk.filedialog.asksaveasfilename(filetypes=("All files", "*."))
Should be
f = tk.filedialog.asksaveasfilename(filetypes=("json", "*.json"))
Or
f = tk.filedialog.asksaveasfilename(filetypes=("All files", "*.*"))
# I'm not sure you can do this one with asksaveasfilename though
Where "All files" and "json" are just labels
Upvotes: 0