我正在用pythontkinter制作一个简单的日志程序,它允许用户在Text小部件内编写文本,并将其作为“journal”文件保存到一个文件中。{I}不能用文件扩展名保存它。我知道您可以使用.defaultextension,但我希望用户用他们选择的扩展名保存文件。这是我的代码:from datetime import datetime
now = datetime.now()
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import font
journal_name = ""
def save_journal():
journal_name = filedialog.asksaveasfilename(filetypes = [("Text file", ".txt"), ("Python file", ".py"), ("All Types", ".*")])
file = open(journal_name, "a")
file.write("%s/%s/%s" % (now.month, now.day, now.year))
file.write(" ")
file.write(text_box.get("1.0", "end-1c"))
file.write("\n\n")
file.close()
#make a gui window
app = Tk()
app.title("Journal Program")
app.iconbitmap(app, "C:\\Program Files (x86)\\Notepad++\\Files\\journalicon.ico")
app.resizable(0,0)
text_font = font.Font(family="Segoe UI", size=11)
#main frame
main_frame = ttk.Frame(app, padding = "5 5 5 5")
main_frame.grid(column=0, row=0, sticky="nsew")
text_box = Text(main_frame, wrap = WORD, height = 15, width = 70, font = text_font)
scrollbar = ttk.Scrollbar(main_frame)
scrollbar.config(command = text_box.yview)
text_box.config(yscrollcommand = scrollbar.set)
text_box.grid(column = 1, columnspan = 3, row = 2, sticky = "es")
scrollbar.grid(column = 4, row = 2, sticky = "ns")
save_button = ttk.Button(main_frame, text = "Save", command = save_journal)
save_button.grid(column = 3, row = 3, sticky = S + E, pady = '5')
app.mainloop()
我想要的是,用户能够从“另存为”窗口中选择一种文件类型(例如python),并将其作为所保存文件的文件扩展名。我不知道是否有可能,但如果是的话,我真的很感激你的帮助,我还没有找到任何关于这类事情的信息。在
对于堆栈溢出问题,我希望这不是太多的代码。我试着把它精简成一个最小的程序。我也意识到代码是可以优化的,但我仍在学习python,并试图解决问题。任何关于如何优化此代码的评论或帮助也将不胜感激。提前谢谢大家。在