保存后扩展名未添加到文件名

Par*_*mli 1 python filedialog tkinter savefiledialog python-3.x

保存后我得到了没有扩展名的文件,尽管我在我的程序中通过filetypes 选项为它们提供了扩展名。我只能使用defaultextension option来做到这一点,但我想让用户决定选择一个扩展而不会弄乱代码。另外,当我使用defaultextension option 时,例如: defaultextension=".txt",它会.txt在我的文件名中添加 2 ,例如filename.txt.txt. 这是我的片段:

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()
Run Code Online (Sandbox Code Playgroud)

我写文件没有任何问题,我的问题只是它们的扩展名

额外信息:

  • 我在 Windows 7 上
  • 我已经取消选中Hide extensions for known file types(我已经尝试过选中版本,但它没有改变任何东西)

Par*_*mli 10

伟大的!我自己只是通过添加defaultextension="*.*" option找到了答案。感谢大家尝试回答我的问题,虽然他们都没有解决我的问题,但实际上,他们中的大多数人只是在没有解释原因的情况下对我的问题投了反对票。好吧,如果您不知道解决方案,那不是我的错,哈哈!感谢其他试图帮助我的人!赞赏!:)