This is really simple, and I had it working last night with everything exactly how it was (though clearly not, or it would be working now!).
I simply need the data entered on the form to save itself in to a text document.
I've tried googling and watching a couple of YouTube videos, and it appears to me that I'm doing exactly what some of them show.
from tkinter import *
window=Tk()
window.title("City Gym Membership Form")
frame = Frame(window)
frame.pack()
def button():
first_name = firstNameEntry.get()
last_name = lastNameEntry.get()
address = addressEntry.get()
mobile = phoneNumberEntry.get()
file = open("test.txt", "w")
file.write(f"First Name: {first_name}")
file.write(f"Last Name: {last_name}")
file.write(f"Address: {address}")
file.write(f"Phone Number: {mobile}")
file.write("\n")
file.close()
personal_details = LabelFrame(frame, text="User Information")
personal_details.grid(row=0, column=0, padx=20, pady=10)
firstNameLabel = Label(personal_details, text="First Name:")
firstNameLabel.grid(row=0, column=0)
lastNameLabel = Label(personal_details, text="Last Name:")
lastNameLabel.grid(row=0, column=1)
firstNameEntry = Entry(personal_details)
firstNameEntry.grid(row=1, column=0)
lastNameEntry = Entry(personal_details)
lastNameEntry.grid(row=1, column=1)
phoneNumberLabel = Label(personal_details, text="Phone Number:")
phoneNumberLabel.grid(row=2, column=0)
phoneNumberEntry = Entry(personal_details, width=45)
phoneNumberEntry.grid(row=3, column=0, columnspan=2)
addressLabel = Label(personal_details, text="Address:")
addressLabel.grid(row=4, column=0)
addressEntry = Entry(personal_details, width=45)
addressEntry.grid(row=5, column=0, columnspan=2)
submit_button = Button(frame, text="Submit", command=button)
submit_button.grid(row=6, column=0, columnspan=2, sticky="news", padx=20, pady=10)
window.mainloop()
The issue that I'm having is that it's not putting anything into the text file.
Any help would be much appreciated, as I'm very new to Python/Tkinter. Thank you!
CodePudding user response:
Simple example of how to write text from entry
to file:
import tkinter as tk
root = tk.Tk()
entry_var = tk.StringVar()
def save_to_file():
text = entry_var.get()
with open('file.txt', 'w') as f:
f.write(text)
entry = tk.Entry(root, textvariable=entry_var)
sub_btn = tk.Button(root, text='Save to file', command=save_to_file)
entry.grid(row=0, column=0)
sub_btn.grid(row=1, column=0)
root.mainloop()
CodePudding user response:
Turns out the file was simply in a different directory to the one that my .py file was in.