Python Forum
[Tkinter] [split] I want to add a code to the "Save" button to save the data entered
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] [split] I want to add a code to the "Save" button to save the data entered
#1
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()
buran write Jan-23-2023, 10:01 AM:
Please, use proper tags when post code, traceback, output, etc.
See BBcode help for more info.
Please, don't hijack other member's threads
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Trying to add data into a shelf from a submit button TWB 8 1,845 Jan-06-2023, 11:30 PM
Last Post: TWB
Question [Tkinter] How to make split button? teknixstuff 2 1,059 Jan-03-2023, 06:21 PM
Last Post: Yoriz
  Can't get tkinter button to change color based on changes in data dford 4 3,418 Feb-13-2022, 01:57 PM
Last Post: dford
  Button to add data to database and listbox SalsaBeanDip 1 2,873 Dec-06-2020, 10:13 PM
Last Post: Larz60+
  Tkinter Python: How to make sure tkSimpleDialog takes in No value entered rcmanu95 3 2,340 Aug-05-2020, 05:32 AM
Last Post: Yoriz
  [PyQt] Pyqt5: How do you make a button that adds new row with data to a Qtablewidget YoshikageKira 6 6,988 Jan-02-2020, 04:32 PM
Last Post: Denni
  [Tkinter] Unable to save filepath to config.ini file using filedialog.askopenfilename JackMack118 10 4,957 Dec-29-2019, 08:12 PM
Last Post: JackMack118
  [PyGUI] Pressing button by code after gui is loaded KaiBehncke 1 1,405 Nov-18-2019, 10:04 PM
Last Post: Denni
  [PySimpleGui] How to alter mouse click button of a standard submit button? skyerosebud 3 5,008 Jul-21-2019, 06:02 PM
Last Post: FullOfHelp
  How to save record Rehan11 2 2,731 Dec-28-2018, 09:07 PM
Last Post: joe_momma

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020