将输入输入写入文本文件

时间:2020-01-24 20:07:09

标签: python tkinter text-files tkinter-entry

from tkinter import *

root = Tk()
writeList = []
myFile = open("details.txt","w")

nameLabel = Label(root,text = "Input your name: ")
nameLabel.grid(column = 1,row = 0)

nameEntry = Entry(root)
nameEntry.grid(column = 2,row = 0)

name = nameEntry.get()
writeList.extend(("Name:",name))

ageLabel = Label(root,text = "Enter your age:")
ageLabel.grid(column = 1,row = 1)

ageEntry = Entry(root)
ageEntry.grid(column = 2,row = 1)

age = ageEntry.get()
writeList.extend(("Age:",age))

def writeFile(writeList):
    for x in range(len(writeList)):
        write = writeList[x]
        myFile.write(write)
        myFile.write("\n")

    myFile.close()

writeButton = Button(root,text = "Write to a file",command = writeFile(writeList),bg = "turquoise")
writeButton.grid(column = 1,row = 3)

root.mainloop()

所以基本上它不会将我输入的内容写到我出错的文本文件中...... 我不得不尝试使用一个按钮,以便它可以在输入后写入 我应该在函数中而不是在for循环中写入条目

1 个答案:

答案 0 :(得分:2)

首先需要在这里解决一些问题。

  1. 您在全局命名空间而不是函数中拥有Assignment Branch Condition sizeget()。这将导致在extend()处调用这2个方法,基本上,您将始终拥有空字符串。您想使用一个函数来调用这些东西,以便在需要时获取数据。

  2. 您的按钮命令还在__init__上调用您的函数,因为您实际上并未保存对该函数的引用。要解决此问题,您需要去除括号或使用__init__

  3. 我会在lambda上使用import tkinter as tk。这样可以防止意外覆盖方法。

  4. 我将使用from tkinter import *代替with openopen()。函数完成后,close()语句将自动关闭文件。

下面,我对您的代码进行了一些整理,并添加了所需的更改。如果您有任何问题,请告诉我。

示例:

with

结果:

enter image description here

文件包含以下文本:

import tkinter as tk

root = tk.Tk()
write_list = []

tk.Label(root, text="Input your name: ").grid(column=1, row=0)
tk.Label(root, text="Enter your age:").grid(column=1, row=1)
name_entry = tk.Entry(root)
age_entry = tk.Entry(root)
name_entry.grid(column=2, row=0)
age_entry.grid(column=2, row=1)


def write_file():
    name = name_entry.get()
    age = age_entry.get()
    write_list.extend(("Name:", name))
    write_list.extend(("Age:", age))
    with open("details.txt", "w") as my_file:
        for x in range(len(write_list)):
            write = write_list[x]
            my_file.write(write)
            my_file.write("\n")


tk.Button(root, text="Write to a file", command=write_file, bg="turquoise").grid(column=1, row=3)
root.mainloop()