Reputation: 15
So, I'm using TKinter with Python to try and take an input from the user and write that into a seperate file for use later, but I can't seem to get it to work. Having looked over other questions and adapting some parts of my code in accordance to their answers, I still can't get it to work.
Here's the full code:
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()
The Error I'm given in the console, after pressing the button, says:
File "[file directory]", line 9, in write_File
file.write(user_Input).get()
AttributeError: 'int' object has no attribute 'get'
Anyone able to offer any assistance?
Upvotes: 0
Views: 4163
Reputation: 126
Your function should look something like this:
def write_file (user_input): # naming convention for functions in python is__like_this
file = open("users.txt", "a") # 'a' stands for 'append'
file.write(user_input)
file.close()
or even better using context manager
def write_File (user_input):
with open('users.txt', 'a') as file:
file.write(user_input)
Upvotes: 1
Reputation: 1101
So I'm not entirely certain what resources you were using to create write_File, but there were a few errors. I've fixed them in the below code, with comments to explain what I've changed and why.
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()
Another thing is that depending on the version of Python you're using, instead of using file = open(...)
and then file.close()
at the end of the method, you could instead use the with open(...) as file:
construct which will automatically close the file at the end of the scope.
Upvotes: 2