【问题标题】:How to create a .txt file in python by the user prefered nsme?如何通过用户首选名称在 python 中创建 .txt 文件?
【发布时间】:2016-01-27 23:19:18
【问题描述】:

我制作了一个程序来读取存储的文件详细信息。 我想使用 python tkinter 创建一个 .txt 文件。创建文件的名称将由用户在输入框中给出。

你能提供正确的代码吗?请

【问题讨论】:

  • f = open("filename.txt", 'w")f.write("Hello World!\n")。就是这样。
  • 这将创建一个名为“filename.txt”的文件
  • 但我希望用户提供名称而不是 progtammer
  • 我在想你知道如何从输入框中获取文本并使用它来代替“filename.txt”
  • name = your_entry.get()f = open(name, "w") ,仅此而已。

标签: python-2.7 tkinter python-3.4 python-import python-3.3


【解决方案1】:
from tkinter import *
root = Tk()

def clicked():
    Input = entry1.get()
    FileName = str("filepath" + Input + ".txt")
    TextFile = open(FileName,"w")

entry1 = Entry(root)
button1 = Button(root,text="Press to create text file", command = clicked)
entry1.pack()
button1.pack()

root.mainloop()

这将创建一个在单击按钮时运行的函数,它将获取输入框中的文本,然后创建一个文件路径,最后它会尝试打开这个文件,因为文件不存在它会改为以该名称创建一个新文件。

【讨论】:

    【解决方案2】:

    简单示例

    import tkinter as tk
    
    def write_file():
        name = e.get() # get text from entry
        with open(name + ".txt", "w") as f: # open file 
            f.write("Hello World\n") # write doesn't add '\n'
        # `with` will close file automatically
    
    root = tk.Tk()
    
    e = tk.Entry(root)
    e.pack() # can't be `e = Widget(...).pack()`
    
    tk.Button(root, text="Save", command=write_file).pack()
    
    root.mainloop()
    

    【讨论】:

    • 运行此代码后,它会产生不希望的输出...没有输入框...在我单击后只有一个显示“hello”的按钮...它有一个消息框“hellow world ""
    • 这是不可能的。你用什么 ?它适用于我在 Linux 上使用 Python 3.4 和 Python 2.7。
    • 我使用 Windows.. 使用 python 2.7
    猜你喜欢
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2021-01-18
    • 1970-01-01
    • 2016-06-22
    • 2016-06-27
    相关资源
    最近更新 更多