如何在新创建的文件中编写用户输入(取自Tkinter的Entry)

时间:2017-08-08 17:00:27

标签: python-2.7 user-interface tkinter

我希望用户使用Tkinter的条目获得用户输入

from Tkinter import *
top = Tk()
label = Label(top, text="Enter your bio")
entry = Entry(top, bd = 2)

def create_new():
   new_file = open('file.txt', 'w+')
   user_input = str(entry) # I ALSO TRIED WITHOUT str()
   new_file.write(user_input) #still doesn't work

button = Button(top, text = "SAVE", fg ="red", command=create_new) 

label.pack()
entry.pack()
button.pack()
top.mainloop()

当我在字段中添加我的信息并点击SAVE时,它会创建一个新的file.txt但是 它不会在file.txt中写下我的信息..

file.txt只有一些这样的数字

  

0.22775808   和   0.22710272   和   0.22382592

... ETC 那我怎么能解决这个????

  

P.S。 :绝对没有这些数字意味着什么,我知道为什么这些在这里:)

2 个答案:

答案 0 :(得分:1)

from tkinter import *
top = Tk()
label = Label(top, text="Enter your bio")

entry = Entry(top, bd = 2)

def create_new():
   new_file = open('file.txt', 'w+')
   user_input = (entry).get() # I ALSO TRIED WITHOUT str()
   new_file.write(user_input) #still doesn't work

button = Button(top, text = "SAVE", fg ="red", command=create_new) 

label.pack()
entry.pack()
button.pack()`enter code here`
top.mainloop()

答案 1 :(得分:0)

您没有撰写条目的内容,您正在编写条目本身 - 这是从Python的角度来看的只是生成在嵌入式Tcl / Tk解释器中的实际窗口小部件的随机生成的名称。使用var RegisteredUsers = new List<Person>(); RegisteredUsers.Add(new Person() { PersonID = 1, Name = "Bryon Hetrick", Registered = true }); RegisteredUsers.Add(new Person() { PersonID = 2, Name = "Nicole Wilcox", Registered = true }); RegisteredUsers.Add(new Person() { PersonID = 3, Name = "Adrian Martinson", Registered = false }); RegisteredUsers.Add(new Person() { PersonID = 4, Name = "Nora Osborn", Registered = false }); var serializer = new JavaScriptSerializer(); var serializedResult = serializer.Serialize(RegisteredUsers); 作为实际内容。

您在写入文件后也忘记关闭文件,因此您设法写入的内容可能不会立即显示。