I have created a Entry box:
I have created a text file:
save_file.close()
However the data being entered is not saving to the text file. This is being saved:
Accounts
<bound method Entry.get of <tkinter.Entry object .!entry>><bound method Entry.get of <tkinter.Entry object .!entry2>>
Any idea on how to fix this?
You need to call the get method.
Change
save_file.write(str(username_input_box.get))
to
save_file.write(str(username_input_box.get()))
As you are having trouble, I have written out a very basic version of your program which I have tested and it works. It writes the "Accounts" text to the file and when the button is pressed, it writes the content of the entry field to the file too. If you code still isn't working, perhaps you'll need to post a more complete and executable example of your code
from tkinter import *
def creating_text_file():
save_file = open("Accounts.txt", "a")
title = "Accounts"
line = "\n"
save_file.write(title)
save_file.write(line)
save_file.close()
def apending_to_text_file():
save_file = open("Accounts.txt", "a")
save_file.write(str(username_input_box.get()))
save_file.write("\n")
save_file.close()
root = Tk()
username_input_box = Entry(root, width=30)
username_input_box.grid()
btn = Button(root,text="Press Me",command=apending_to_text_file)
btn.grid()
creating_text_file()
root.mainloop()
As an improvement, I'd use the context managers to open/close your file. They look like this
with open("Accounts.txt", "a") as save_file:
save_file.write("Some random text")
#No need to close the file as the context manager does this for you
Related
FormScreenShot
I am very new to python, and I have created a form that requests information from a user, and Im currently stuck (and clueless on where to start) on creating a functional submit button for the form.
Basically, what I am trying to achieve is when the user enters his output directory and hit submits, it prints to a text file. So for example if he browses through and hits C:/Users/Folder
and hits submit, it will output to a text file saying Output_Dir = "C:/Users/Folder"
I am guessing after I create my submit button, I will have to create a function that it calls that writes to the text file.
UI CODE
self.browse_1 = QPushButton(self.input_files1)
self.browse_1.setObjectName(u"browse_1")
self.browse_1.setGeometry(QRect(100, 100, 75, 23))
main code
##Output Directory Button:
self.ui.browse_1.clicked.connect(self.browsebutton_Function)
## SUBMIT FIELDS INPUT FILES
self.ui.pushButton_4.clicked.connect(self.textFileOutput)
##Output Directory Function:
def browsebutton_Function(self):
file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
if file:
self.ui.lineEdit.setText(str(file))
def textFileOutput(self):
output_DIR = self.ui.lineEdit.text()
with open("Output.txt", "w") as text_file:
print(f" Output Directory = {output_DIR}", file=text_file)
I currently have a python file that I have to run for different excel files on a daily basis.
The steps are :
Open .py file
change directory of excel file
run python file
write to .xlsx
This takes in a excel file as a pandas dataframe does some manipulation and other things and spits out an excel file.
The problem is that I have to change the directory each time manually in the code.
I would rather build a nice GUI for me to pick the source file that I want to manipulate, pick the output directory and then click begin to start the .py script.
My current .py file is not written as a function but it is just a series of steps on some data so I could easy write it as a function like so:
def data_automation(my_excel_file):
#do some stuff
pd.to_excel(output directory)
I currently have this:
import tkinter.filedialog as filedialog
import tkinter as tk
master = tk.Tk()
def input():
input_path = tk.filedialog.askopenfilename()
input_entry.delete(1, tk.END) # Remove current text in entry
input_entry.insert(0, input_path) # Insert the 'path'
def output():
path = tk.filedialog.askopenfilename()
input_entry.delete(1, tk.END) # Remove current text in entry
input_entry.insert(0, path) # Insert the 'path'
top_frame = tk.Frame(master)
bottom_frame = tk.Frame(master)
line = tk.Frame(master, height=1, width=400, bg="grey80", relief='groove')
input_path = tk.Label(top_frame, text="Input File Path:")
input_entry = tk.Entry(top_frame, text="", width=40)
browse1 = tk.Button(top_frame, text="Browse", command=input)
output_path = tk.Label(bottom_frame, text="Output File Path:")
output_entry = tk.Entry(bottom_frame, text="", width=40)
browse2 = tk.Button(bottom_frame, text="Browse", command=output)
begin_button = tk.Button(bottom_frame, text='Begin!')
top_frame.pack(side=tk.TOP)
line.pack(pady=10)
bottom_frame.pack(side=tk.BOTTOM)
input_path.pack(pady=5)
input_entry.pack(pady=5)
browse1.pack(pady=5)
output_path.pack(pady=5)
output_entry.pack(pady=5)
browse2.pack(pady=5)
begin_button.pack(pady=20, fill=tk.X)
master.mainloop()
Which generates this:
So what I want to do is assign a function to the begin button which I can do with command=function easily.
What I am struggling to do is:
Given an input from the user, take that input and use the the file path as a function argument.
Be able to select an output destintion (currently I can only select a file not a destination) and then use that destination path to write my new excel file at the end of my function.
Appreciate any input!
Connect a function to your 'Begin' button that gets the content of both your entries and runs data_automation(). Something like
def begin():
my_excel_file = input_entry.get()
output_directory = output_entry.get()
data_automation(my_excel_file, output_directory)
I have added the output_directory argument to your data_automation function.
If you use filedialog.askdirectory() instead of filedialog.askopenfilename(), you will be able to pick a directory instead of a file. By the way there is a typo in output(), I think you want to insert the result in output_entry, not input_entry.
def output():
path = tk.filedialog.askdirectory()
output_entry.delete(1, tk.END) # Remove current text in entry
output_entry.insert(0, path) # Insert the 'path'
I'm currently having some trouble with checking if things are written down in my textfile.
In my code, I check if "1" is in my storefile.txt file. If "1" isn't in the textfile, signalling that the user has opened the code for the first time, Tkinter asks for the user's name and puts in "1" (signalling that the user has opened the code before). If not, Tkinter says "Welcome back," and the user's inputted name.
However, even after I open the code after the first time, the code acts like "1" isn't even in the storefile, even though it is. The code asks for my name and prints "1" again, so I end up having more than 1 "1"s in my storefile and never reach to the "Welcome back," [name] stage.
import tkinter as tk
from time import time
from tkinter import *
root = Tk()
#FUNCTION FOR LABELS (not necessary but it condenses the code)
def label(a):
Label(root,text=a,font=("System",15,"bold"),fg="steelblue").pack()
#THIS IS FOR EXTRACTING SPECIFIC DATA FROM THE TEXTFILE
lines = [] #Declare an empty list named "lines"
def specify(x):
with open ('storefile.txt', 'rt+') as in_file: #Open file lorem.txt for reading of text data.
for line in in_file: #For each line of text store in a string variable named "line", and
lines.append(line) #add that line to our list of lines.
label(lines[x]) #print the list object.
#[x] allows us to print whatever line we want.
#############################
#THIS IS FOR THE 'ENTER NAME' BUTTON TO STORE NAMES
def store():
user_entry = distance_text_box.get()
f=open("storefile.txt", "a")
f.write (str(user_entry))
f.close()
#TITLE
label("[INSERT TITLE]")
#CHECKS IF THIS IS THEIR FIRST TIME ON THE APP. IF IT IS, PRINT DESCRIPTION AND ASKS FOR USERNAME
searchfile = open("storefile.txt", "r")
with open ('storefile.txt', 'rt+') as in_file: #Open file lorem.txt for reading of text data.
for line in searchfile: #For each line of text store in a string variable named "line", and
if "1" not in line:#IT STORES '1' IN THE TEXTFILE WHEN THE USER FIRST OPENS THE CODE, SO IF '1' ISN'T THERE, THE USER HAS NOT OPENED THE CODE YET
print("yes")
Label(root,text="ENTER NAME",font=("System",15,"bold"),fg="steelblue").pack(side=LEFT)#enter name label
distance_text_box = Entry(root, bd=1)
distance_text_box.pack()
searchfile = open("storefile.txt", "a")
searchfile.write("1\n")
searchfile.close()
Button(root, text ="Done!", command=lambda:store()).pack(side=RIGHT)
elif "1" in line:
print("no")
Label(root,text="Welcome back,").pack()
searchfile.close()
#PUT NAME IN TEXTFILE
root.mainloop()
First of all, you are trying to open an already opened file.
Second, if you want to access a file line by line try this:
with open('file.txt','r') as f:
lines = f.readlines() #lines is now a list of lines in the file.
If you want to add new text to the file you can simply create a list of lines to add and append to it, once the check loop is done, append it to the lines list and write back to the file.
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?
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.
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)
I am currently making a desktop widget and what I want to do is create a file in which a user can edit and then save. However, if you guys are familiar with Microsoft word or any other text editors, I want it so that after you hit File -> save, a save dialog appears in which you can choose where to save the file and the file's name. However, after the first time, if the file name stays the same, the save dialog will not come up--rather it will just automatically save over what was previously written. This is what I want to implement but I am having trouble trying to do this. Following is my method for saving files using the save dialog but I am unsure on how to save without having the save dialog pop up.
def saveFile(self):
filename = QtGui.QFileDialog.getSaveFileName(None, 'Save File', os.path.expanduser("~/Desktop/Calendar Data/"+self.dateString), ".txt")
f = open(filename, 'w')
filedata = self.text.toPlainText()
f.write(filedata)
f.close()
Anyone have any idea how to do this? If so that would be great! Thanks for helping.
You should make filename an instance attribute, so you can just check if it was already set:
class Spam:
...
def __init__(self):
self.filename = None
def saveFile(self):
if not self.filename:
self.filename = QtGui.QFileDialog.getSaveFileName(...)
# here you should check if the dialog wasn't cancelled
with open(filename, 'w') as f:
f.write(self.text.toPlainText())
...