Python Forum

Full Version: [split] I want to add a code to the "Save" button to save the data entered
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to add a code to the "Save" button to save the data entered . Also, I want when you click on "Back" button, it go to main menu. At the same time, I want to present check the data entry on "Student Name" text box. Below is the code:
from tkinter import *  
top = Tk()   
top.geometry("450x500")


def open_text():
   text_file = open("test.txt", "r")
   content = text_file.read()
   my_text_box.insert(END, content)
   text_file.close()

def save_text():
   text_file = open("test.txt", "w")
   text_file.write(my_text_box.get(1.0, END))
   text_file.close()
   
def main():
   Messageforyou = Label(top, 
                       text = "Park Wood School - Students Details").place(x = 100,
                                              y = 20)
# the label for user_name 
user_name = Label(top, 
                  text = "Pupil ID").place(x = 40,
                                           y = 60)     
# the label for user_password  
user_password = Label(top, 
                      text = "First Name").place(x = 40,
                                               y = 100)
user_Surname = Label(top, 
                      text = "Surname").place(x = 40,
                                               y = 140)
user_Form_Class = Label(top, 
                      text = "Form Class").place(x = 40,
                                               y = 180)

user_password = Label(top, 
                      text = "DOB").place(x = 40,
                                               y = 220)
submit_button = Button(top, 
                       text = "Add Pupil").place(x = 100,
                                              y = 250)
my_text_box = Button(top, 
                       text = "Save").place(x = 100,
                                              y = 300)

submit_button = Button(top, 
                       text = "Back").place(x = 100,
                                              y = 350)
Messageforyou = Label(top, 
                       text = "Please Enter Pupils Details").place(x = 100,
                                              y = 400)
user_name_input_area = Entry(top,
                             width = 30).place(x = 110,
                                               y = 60)      
user_password_entry_area = Entry(top,
                                 width = 30).place(x = 110,
                                                   y = 100)
user_password_entry_area = Entry(top,
                                 width = 30).place(x = 110,
                                                   y = 140)
user_name_input_area = Entry(top,
                             width = 30).place(x = 110,
                                               y = 180)
user_name_input_area = Entry(top,
                             width = 30).place(x = 110,
                                               y = 220)



# Creating a text box widget
my_text_box = Text(win, height=10, width=20)
my_text_box.pack()

open_btn = Button(win, text="Open Text File", command=open_text)
open_btn.pack()

# Create a button to save the text
save = Button(win, text="Save File", command=save_text)
save.pack()

win.mainloop()

top.mainloop()
This does not do what you think it does:
Messageforyou = Label(top, text = "Park Wood School - Students Details")
    .place(x = 100, y = 20)
Label() returns a lablel widget. place() returns None. Label().place() returns None. Messageforyou == None. If you want to change the label, you can't. There is no handle to the label widget. If you need to talk to a widget later in your program, assign the widget first, then, in a separate command, pack the widget.

You also have a problem with scope. If you fixed all the code where you wanted a variable to reference a widget, but ended up referencing None, you would still have problems. A variable assignment inside a function creates a variable that is local to the function. Messageforyour is not visible outside main(). open_text() will not work because my_text_box is not defined (it was only defined inside the main() function). To make these variables visible to other functions, or the main body of code, you need to declare them as "global".
def main():
    global my_text_box, and, other, variables, you, want, to, be, global 
A better way to write tkinter applications if you use classes. Instance variables provide an easy way to get around the global/local scope problems that plague programs that only use functions. The example below only has one variable that is used in multiple places, but even here it is easy to see how the class makes it obvious that "message" is associated with "TextEditor", something much less obvious when using a global variable.
import tkinter as tk  # Do not do * imports
from tkinter import filedialog


class TextEditor(tk.Tk):
    """A super bare bones text editor"""
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self["bg"] = "blue"
        self.message = tk.Text(self, width=60, height=20)
        frame = tk.Frame(self, bg="red")
        load_btn = tk.Button(frame, text="Load", command=self.load_message)
        save_btn = tk.Button(frame, text="Save", command=self.save_message)
        clear_btn = tk.Button(frame, text="Clear", command=self.clear_message)
        self.message.pack(side=tk.TOP, padx=10, pady=10, expand=1, fill=tk.BOTH)
        frame.pack(side=tk.TOP, padx=10, pady=(0, 10), fill=tk.X)
        load_btn.pack(side=tk.LEFT, expand=True, fill=tk.X)
        save_btn.pack(side=tk.LEFT, padx=10, expand=True, fill=tk.X)
        clear_btn.pack(side=tk.LEFT, expand=True, fill=tk.X)

    def load_message(self):
        """Load message from a file"""
        self.clear_message()
        if filename := filedialog.askopenfilename():
            with open(filename, "r") as file:
                text = file.read()
                self.message.insert(tk.END, text)

    def save_message(self):
        """Save message to a file"""
        if filename := filedialog.asksaveasfilename():
            with open(filename, "w") as file:
                file.write(self.message.get(1.0, tk.END))

    def clear_message(self):
        """Clear the message"""
        self.message.delete(1.0, tk.END)


TextEditor().mainloop()
Your form is like a dialog. Typical buttons on a dialog are "Accept" and "Cancel". Accept closes the dialog and saves changes. Cancel closes the dialog without saving changes. Add pupil would not belong on the dialog. The dialog would pop open when the Add Pupil button (or menu selection) was chosen in a different window.