Search code examples
pythonpython-3.xtkintersavefiledialogfiledialog

Extension not added to file name after saving


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:

  • I'm on Windows 7
  • I've unchecked Hide extensions for known file types (I've tried checked version but it didn't change anything)

Solution

  • 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! :)