Reputation: 1287
I get files with no extension after saving them, although I give them extensions by filetypes
option in my program. I can only do it using defaultextension
option, but I want to let user decide to choose an extension without messing with code. Plus, when I use defaultextension
option, for example: defaultextension=".txt"
, it adds 2 .txt
to my file name, like filename.txt.txt
. Here's my snippet:
from tkinter import *
import tkinter.filedialog
root = Tk()
root.title("Saving a File")
root.geometry("500x500-500+50")
def save():
filename = filedialog.asksaveasfilename(
initialdir="D:",
title="Choose your file",
filetypes=(
("Text Files", "*.txt"),
("Python Files", "*.py"),
("All Files", "*.*")
)
)
try:
fileobj = open(filename, 'w')
fileobj.write(text.get(0.0, "end-1c"))
fileobj.close()
except:
pass
button = Button(root, text="Save", command=save,
cursor='hand2', width=30, height=5,
bg='black', fg='yellow', font='Helvetica')
button.pack()
text = Text(root)
text.pack()
I do not have any problem with writing a file, my problem is only with their extensions.
Extra info:
Hide extensions for known file types
(I've tried checked version but it didn't change anything) Upvotes: 6
Views: 3580
Reputation: 1287
Great! I myself found the answer just by adding defaultextension="*.*"
option. Thanks for everyone for trying to answer my question, although none of them solved my problem, in fact, most of them only downvoted my question without explaining their reasons. Well, it was not my fault if you don't know a solution LOL! Thanks for others who tried to help me! Appreciated! :)
Upvotes: 14
Reputation: 19144
idlelib.IOBinding (.iomenu in 3.6) has this code that works to add .py or .txt when not explicitly entered. I don't know/remember what "TEXT" is for, but since the code works, I leave it alone.
filetypes = [
("Python files", "*.py *.pyw", "TEXT"),
("Text files", "*.txt", "TEXT"),
("All files", "*"),
]
[...]
def asksavefile(self):
dir, base = self.defaultfilename("save")
if not self.savedialog:
self.savedialog = tkFileDialog.SaveAs(
parent=self.text,
filetypes=self.filetypes,
defaultextension=self.defaultextension)
filename = self.savedialog.show(initialdir=dir, initialfile=base)
return filename
Upvotes: 0