所以,我使用 TKinter 和 Python 来尝试从用户那里获取输入并将其写入一个单独的文件以供以后使用,但我似乎无法让它工作。查看了其他问题并根据他们的答案调整了我的代码的某些部分后,我仍然无法让它工作。
这是完整的代码:
import tkinter
def write_File (text_File):
file = open("users.txt", "a")
user_Input = str(file)
file.write(user_Input).get()
text_File.insert(INSERT, file.read())
file.close()
screen = tkinter.Tk()
the_input = tkinter.Entry(screen)
the_input.grid(row=1, column=1)
button_Write = tkinter.Button(screen, text = "Send to file:", command = lambda: write_File(the_input)).grid(row=10, column=1)
screen.mainloop()
按下按钮后,我在控制台中给出的错误说:
File "[file directory]", line 9, in write_File
file.write(user_Input).get()
AttributeError: 'int' object has no attribute 'get'
任何人都可以提供任何帮助?
所以我不完全确定您使用什么资源来创建 write_File,但有一些错误。我已经在下面的代码中修复了它们,并附有注释来解释我所做的更改以及原因。
import tkinter
def write_File (text_File):
file = open("users.txt", "a")
#The object text_File is a tkinter.Entry object, so we will get
# the user input by calling the get method on that object.
user_Input = text_File.get()
#Here we now directly write the user input to the file that has been
# opened, I'm not sure you were previously doing with writing the
# string version of the file, but this appears to achieve what you
# desire.
file.write(user_Input)
file.close()
screen = tkinter.Tk()
the_input = tkinter.Entry(screen)
the_input.grid(row=1, column=1)
button_Write = tkinter.Button(screen, text = "Send to file:", command = lambda: write_File(the_input)).grid(row=10, column=1)
screen.mainloop()
另一件事是,根据您使用的 Python 版本,而不是使用file = open(...)
然后file.close()
在方法结束时,您可以改为使用with open(...) as file:
将在范围结束时自动关闭文件的构造。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句