You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Tkinter中将用户输入作为保存按钮的文件名

让Tkinter保存按钮使用输入框内容作为文件名

要实现点击保存按钮时,用输入框里的内容作为默认文件名,只需要修改savef函数的initialfile参数,同时处理输入为空的边界情况即可:

修改要点

  • 用script_name_input_area.get()获取输入框中的用户输入,作为保存对话框的初始文件名
  • 若用户未输入文件名,设置一个默认值(比如"untitled.jef")避免对话框初始文件名空白

修改后的完整代码

from tkinter import *
from tkinter import filedialog, StringVar
from tkinter.ttk import *
import os


win = Tk()
#main window parameters
win.title(" JEAME ")
win.geometry("900x500")
p1 = PhotoImage(file = 'deltalogo_en.png')
win.iconphoto(False, p1)

def openf():
    file = filedialog.askopenfilename(initialdir='/', title="select file",
                                      filetypes=(('JEL files',".jef"), ('All Files','*.*')))
def savef():
    # 获取输入框的文件名,为空则用默认值
    default_filename = script_name_input_area.get() or "untitled.jef"
    file = filedialog.asksaveasfile(initialdir='/', title="select file", initialfile=default_filename,
                                      filetypes=(('JEL files', ".jef"), ('All Files', "*.*")))

#open existing script
btn1 = Button(win, text = ' Open ', command= openf)
btn1.place(x=5, y=5)
#start new script button
btn2 = Button(win, text = ' New ')
btn2.place(x=80, y=5)
#save created script button
btn3 = Button(win, text = ' Save ', command= savef)
btn3.place(x=155, y=5)
#script naming
script_name = Label (
    text = "Script name ").place(x = 10, y = 60)
script_name_input_area: StringVar = StringVar()
Fname = Entry(textvariable=script_name_input_area,
    width = 30).place(x = 100, y = 60)

# Run main loop
win.mainloop()

关键说明

  • script_name_input_area.get()会读取输入框中的文本内容,直接传给initialfile参数,保存对话框就会自动填充这个文件名
  • 用or处理空输入的情况:如果用户没输入任何内容,就用"untitled.jef"作为默认文件名,避免对话框初始文件名空白
  • 保存对话框会根据你选择的文件类型自动添加后缀,比如选了JEL文件类型,即使输入的文件名没带.jef,也会自动补上

内容的提问来源于stack exchange,提问作者Jakub Hodulak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 07:16:08