Tkinter filedialog to save user entered data

User can enter data using one Text box and filedialog.asksaveasfile() function is used to show Save As file dialog box to save the data in a file.

We will use the basic code used for filedialog.asksaveasfile() and add features to this.
Saving user entered data
Displaying data in Treeview by using Tkinter filedialog to show file browser to upload & read file

Using Text entry box

Tkinter Text widget is used to enter multi-line data.
t1 = tk.Text(my_w,  width=40, height=3)
t1.grid(row=2,column=1)
Once the user clicks the button to save, the data entered inside the Text widget is collected and stored in a variable .
my_str1=t1.get("1.0",END)
After writing the data into a file, the user entered text is removed from the Text widget.
t1.delete('1.0',END) # Delete from position 0 till end
t1.update()

Button

Once the button is clicked to save the data, the text on the button is changed saying the data is saved. Original text is restored after a time gap of three seconds.
	b1.config(text="Saved")
        b1.after(3000, lambda: b1.config(text='Save'))
Full code is here ( all changes to basic code at asksaveasfile() is highlighted. )
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import asksaveasfile
from tkinter import END
my_w = tk.Tk()
my_w.geometry("400x300")  # Size of the window 
my_w.title('www.plus2net.com')
my_font1=('times', 18, 'bold')
l1 = tk.Label(my_w,text='My Note Book',width=30,font=my_font1)  
l1.grid(row=1,column=1)

t1 = tk.Text(my_w,  width=40, height=3)
t1.grid(row=2,column=1)

b1 = tk.Button(my_w, text='Save',command=lambda:save_file(), width=20)
b1.grid(row=4,column=1) 
def save_file():
    my_str1=t1.get("1.0",END)  # read from one text box t1
    fob=filedialog.asksaveasfile(filetypes=[('text file','*.txt')],
        defaultextension='.txt',initialdir='D:\\my_data\\my_html',
        mode='w')
    try:
        fob.write(my_str1)
        fob.close()
        t1.delete('1.0',END) # Delete from position 0 till end 
        t1.update()  
        b1.config(text="Saved")
        b1.after(3000, lambda: b1.config(text='Save'))
    except :
        print (" There is an error...")
my_w.mainloop()  # Keep the window open
filedialog.asksaveasfile
Tkinter Filedialog Treeview askopenasfile() Upload and display image file
Save data entered by user in Tkinter window to PDF file
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer