Python 将输入框中的输入保存到.txt文件中

Python 将输入框中的输入保存到.txt文件中,python,tkinter,file-handling,Python,Tkinter,File Handling,我想将输入框中的输入保存到.txt文件中,它对第一个代码有效,而不是第二个代码,但我需要使用的是第二个代码 代码1: import tkinter as tk def f(): def save(): a = t.get() f = open((a + '.txt'), 'w') f.write(a) f.close() return top = tk.Tk() t = tk.StringVa

我想将输入框中的输入保存到.txt文件中,它对第一个代码有效,而不是第二个代码,但我需要使用的是第二个代码

代码1:

import tkinter as tk

def f():
    def save():
        a = t.get()
        f = open((a + '.txt'), 'w')
        f.write(a)
        f.close()
        return

   top = tk.Tk()
   t = tk.StringVar()
   e = tk.Entry(top, textvariable = t).pack()
   b = tk.Button(top, text = 'Save as a file', command = save).pack()
   top.mainloop()
f()
代码2:

import tkinter as tk

root = tk.Tk()

def f():
    def save():
        a = t.get()
        f = open((a + '.txt'), 'w')
        f.write(a)
        f.close()
        return

    top = tk.Tk()
    t = tk.StringVar()
    e = tk.Entry(top, textvariable = t).pack()
    b = tk.Button(top, text = 'Save as a file', command = save).pack()
    top.mainloop()

button = tk.Button(root, text="Button",command=f).pack()
root.mainloop()

您没有在第二个代码中调用save函数。在定义后添加save call可以解决您的问题

您的代码:

def f():
    def save():
        a = t.get()
        f = open((a + '.txt'), 'w')
        f.write(a)
        f.close()
        return
固定的:

def f():
    def save():
        a = t.get()
        f = open((a + '.txt'), 'w')
        f.write(a)
        f.close()
        return
    save()

您将变量与输入框混淆:使用更好的变量名会有所帮助。您还正在用此名称创建的文件中写入文件名。。。不清楚这是否真的是你想要的。 您也在同一行上打包,因为分配给变量e-pack返回None 出于某种原因,您还启动了两个主循环;不要这样做,这是个坏主意

import tkinter as tk

def save():
    file_name = entry.get()
    with open(file_name + '.txt', 'w') as file_object:
        file_object.write(file_name)   # it is unclear if writing the file_name in the newly created file is really what you want.

if __name__ == '__main__':
    top = tk.Tk()
    entry_field_variable = tk.StringVar()
    entry = tk.Entry(top, textvariable=entry_field_variable)
    entry.pack()
    tk.Button(top, text="save", command=save).pack()

    top.mainloop()
我删除了嵌套函数;如果您觉得必须这样做,也许您应该使用类来代替。 我还将文件的打开/关闭更改为上下文管理器,以便为您处理它

import tkinter as tk

def f():
    def save():
        a = t.get()
        with open((a + '.txt'), 'w') as f: 
            f.write(a)

    top = tk.Tk()
    t = tk.StringVar(top)
    tk.Entry(top, textvariable=t).pack()
    tk.Button(top, text = 'Save as a file', command=save).pack()

root = tk.Tk()
tk.Button(root, text="Button", command=f).pack()
root.mainloop()

最重要的更改是t=tk.StringVar->t=tk.StringVartop,指定主小部件。还有一些其他更改,例如,pack返回None,因此不要基于它设置值,使用上下文管理器关闭文件

可能重复将top=tk.tk更改为top=tk.Toplevel,这基本上是Lafexlos链接的摘要。请参阅:tk.buttonop,text='另存为文件',command=save.packYou不能有两个Tk实例。@Lafexlos当然可以,但可能不应该,因为可能有更好的方法,但代码显然是有效的。尝试it@Lafexlos您是否阅读了链接的建议副本?从技术角度来看,没有理由不能同时拥有两个Tk实例。嗯,是的,不能是一个强有力的词,我的不好。@jkle,如果你接受我的答案,因为它比其他人更接近你的答案,那主要是因为我对它的思考比其他人少。你应该考虑从ReBoLogMaskIK中正确地回答答案。即使您决定使用这种方法,其他读者也可能对更通用的解决方案感兴趣。