In this tutorial, we will learn How to save text to file in Python Tkinter and we will also cover different examples related to saving a text file. And also cover these topics
- Python Tkinter save text to file
- Python Tkinter save text dialog box
- Python Tkinter save file path
- Python Tkinter save entry
- Python Tkinter save button
- Python Tkinter save input to variable
- Python Tkinter save canvas image
Python Tkinter save text to file
In this section, we will learn how to save the text to a file in Python Tkinter.
Firstly, we write the text on a text writer Like Notepad, Microsoft word. After writing the text, we want to save this. For saving the text, go to the menubar where the file tab is located under the file, tab there are save options for saving the file.
Code:
In the following code Firstly we clear the text area and then insert the text and save by clicking on the save option.
- text_zone.delete()is used for clearing the text area.
- text_zone.insert()is used for inserting the text inside the text area.
- text_zone.edit_modified()= After inserting the text if we want to modify the text then we use this function.
- filedialog.askopenfile() function shows the dialog box that allows the user to select the file and return the file that the user selected.
- filemenu.add_command() is used for adding the command under the File tab.
- menubar.add_cascade() used for giving the access to the function as opening the file.
- Scrollbar()is used if we have written a big paragraph. Since the screen is not sufficient to display the entire paragraph then we have used the scrollbar.
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
def file1():
if not text_zone.edit_modified():
text_zone.delete('1.0', tk.END)
else:
savefileas()
text_zone.delete('1.0', tk.END)
text_zone.edit_modified(0)
ws.title('PYTHON GUIDES')
def openfile():
if not text_zone.edit_modified():
try:
path = filedialog.askopenfile(filetypes = (("Text files", "*.txt"), ("All files", "*.*"))).name
ws.title('Notepad - ' + path)
with open(path, 'r') as f:
content = f.read()
text_zone.delete('1.0', tk.END)
text_zone.insert('1.0', content)
text_zone.edit_modified(0)
except:
pass
else:
savefileas()
text_zone.edit_modified(0)
openfile()
def savefile():
try:
path = ws.title().split('-')[1][1:]
except:
path = ''
if path != '':
with open(path, 'w') as f:
content = text_zone.get('1.0', tk.END)
f.write(content)
else:
savefileas()
text_zone.edit_modified(0)
def savefileas():
try:
path = filedialog.asksaveasfile(filetypes = (("Text files", "*.txt"), ("All files", "*.*"))).name
ws.title('Notepad - ' + path)
except:
return
with open(path, 'w') as f:
f.write(text_zone.get('1.0', tk.END))
ws = tk.Tk()
ws.title('Notepad')
ws.geometry('800x600')
menubar = tk.Menu(ws)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=file1)
filemenu.add_command(label="Open", command=openfile)
filemenu.add_command(label="Save", command=savefile)
filemenu.add_command(label="Save as...", command=savefileas)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=ws.quit)
menubar.add_cascade(label="File", menu=filemenu)
text_zone = tk.Text(ws)
text_zone.pack(expand = tk.YES, fill = tk.BOTH, side = tk.LEFT)
scrollbar = ttk.Scrollbar(ws, orient=tk.VERTICAL, command=text_zone.yview)
scrollbar.pack(fill=tk.Y, side=tk.RIGHT)
text_zone['yscrollcommand'] = scrollbar.set
ws.config(menu=menubar)
ws.mainloop()
Output:
In the following output, we see the Notepad where the text is written. To save this text we create a menubar inside the menubar we see the file option.
On clicking on the File we see the save option and click on them for saving the text to file.
Read: Python Tkinter Spinbox
Python Tkinter save text dialog box
In this section, we will learn how to save text dialog boxes in Python Tkinter.
A dialog box is a drive or directory where we can save our text files. We can create a text file for saving this text file to the dialog box. Click on the button dialog box to appear. Choose the file you want to save after chosen the file click on the save. The file will save in the dialog box.
Code:
In the following code, we create a window ws=TK() inside this window we add a button on clicking this button dialog box appears where we save out the text file.
- asksaveasfile() function which is used to save the user file.
- lambda function only has a single expression.
- Button() is used to save the file.
from tkinter import *
from tkinter.filedialog import asksaveasfile
ws = Tk()
ws.geometry('200x200')
ws.title("Python Guides")
def save():
Files = [('All Files', '*.*'),
('Python Files', '*.py'),
('Text Document', '*.txt')]
file = asksaveasfile(filetypes = Files, defaultextension = Files)
button = Button(ws, text = 'Save', command = lambda : save())
button.pack(side = TOP, pady = 20)
ws.mainloop()
Output:
In the following output, we see a save button is placed on the widget. Press the save button.
After pressing the save button, a dialog box appears where we can save our file.
Read: Python Tkinter search box
Python Tkinter save file path
In this section, we will learn how to save the file path in the Python Tkinter.
After creating the file, we can save our file. The file where we can save a path is created or we can say that on which location our file is saved like In C/ drive, E/ drive, desktop.
Code:
In the following code, we create a widget inside the widget a button is placed on clicking the button file path is saved where the file is located.
- filedialog.askopenfilename() function allow to open and return the file path.
- Button()is used to search the file by clicking on them.
from tkinter import *
from tkinter import filedialog
def get_file_path():
global file_path1
file_path1= filedialog.askopenfilename(title = "Select A File", filetypes = (("Python files", "*.png"), ("mp4", "*.mp4"), ("wmv", "*.wmv"), ("avi", "*.avi")))
l1 = Label(ws, text = "File path: " + file_path1).pack()
ws = Tk()
ws.title("Python Guides")
ws.geometry("200x200")
button = Button(ws, text = "openfile", command = get_file_path).pack(pady=10)
ws.mainloop()
print(file_path1)
Output:
After running the above code, we get the following output we see a widget inside the widget an “openfile” button is placed.
After clicking on openfile button we get the dialog box where we select our file and find the path of the file.
After selecting the file and click on open the file path will show on the widget.
Read: Python Tkinter Validation
Python Tkinter save entry
In this section, we will learn how to save the entry in Python Tkinter.
Entry is an object written in a list, diary, or we can say that updates some content of data. As there is an entry box of usernames and passwords we can enter the data in this column. After entering the data we can save the data we enter update automatically after saving.
Code:
In the following code, we create a login screen inside a login screen there is an entry widget of username and password where users can enter their name and password and then save by clicking on submit button.
- Label() is used to display a field of text or images.
- Entry() is used for getting the user input.
- Button() that will call the submit function.
- .grid() it manages the geometry of Label,Entry,Button.
from tkinter import *
ws=Tk()
ws.title("Python Guides")
ws.geometry("200x200")
name_variable=StringVar()
password_var=StringVar()
def submit():
name=name_variable.get()
password=password_var.get()
print("The name is : " + name)
print("The password is : " + password)
name_variable.set("")
password_var.set("")
name_label = Label(ws, text = 'Username', font=('calibre',10, 'bold'))
name_entry = Entry(ws,textvariable = name_variable, font=('calibre',10,'normal'))
password_label = Label(ws, text = 'Password', font = ('calibre',10,'bold'))
password_entry=Entry(ws, textvariable = password_var, font = ('calibre',10,'normal'), show = '*')
submit_button=Button(ws,text = 'Submit', command = submit)
name_label.grid(row=0,column=0)
name_entry.grid(row=0,column=1)
password_label.grid(row=1,column=0)
password_entry.grid(row=1,column=1)
submit_button.grid(row=2,column=1)
ws.mainloop()
Output:
In the following output, we create a login screen. There is a username and password block where users can enter their name and password.
In this output, we see that the user can enter their name and password. After completing the process click on submit.
After clicking on submit button, the entry is saved and show on the command prompt.
Read: Python Tkinter On-Off Switch
Python Tkinter save button
In this section, we will learn about the save button in Python Tkinter.
The save button is used for saving the file which is created by the user. By simply clicking on the save button we can save any file.
Code:
In the following code, we create a widget inside the widget a button is placed. By clicking on the button a dialogue box is open inside the dialog box we can save the file by simply click on the Save button.
asksaveasfile()function which is used to save the user file.
Button()that will call the submit function.
from tkinter import *
from tkinter.filedialog import asksaveasfile
ws = Tk()
ws.title("Python Guides")
ws.geometry('200x150')
def save_button():
files = [('All Files', '*.*'),
('Python Files', '*.py'),
('Text Document', '*.txt')]
file = asksaveasfile(filetypes = files, defaultextension = files)
btn = Button(ws, text = 'Save', command = lambda : save_button())
btn.pack(side = TOP, pady = 20)
ws.mainloop()
Output:
In the following output, we see the widget inside the widget a save button is placed. we clicking on the save button.
After clicking on the button, a dialog box chooses the file which we want to save. After choosing the file, click on the Save button.
Read: Python Tkinter notebook Widget
Python Tkinter save input to variable
In this section, we will learn how to save the input to variable in Python Tkinter.
In the below code, we create a canvas inside the canvas we create a lab1, lab2, and entry widget where the user enters the input and gets the output to save in the form of variable.
Code:
- Canvas()where we can place graphics, text, or frames.
- Label()function is used for displaying the field of text.
- Entry()is used to accept the text from a user.
- canvas.create_window() is used for creating a new canvas window object on a canvas.
- Button() is used for calling the submit function.
from tkinter import *
ws = Tk()
ws.title("Python Guides")
canvas =Canvas(ws, width = 400, height = 300, relief = 'raised')
canvas.pack()
lab1 =Label(ws, text='Calculate The Square Root')
lab1.config(font=('helvetica', 14))
canvas.create_window(200, 25, window=lab1)
lab2 =Label(ws, text='Enter the Number:')
lab2.config(font=('helvetica', 10))
canvas.create_window(200, 100, window=lab2)
entry1 =Entry (ws)
canvas.create_window(200, 140, window=entry1)
def get_SquareRoot ():
a1 = entry1.get()
lab3 =Label(ws, text= 'The Square Root of ' + a1 + ' is:',font=('helvetica', 10))
canvas.create_window(200, 210, window=lab3)
lab4 =Label(ws, text= float(a1)**0.5,font=('helvetica', 10, 'bold'))
canvas.create_window(200, 230, window=lab4)
button = Button(text='Get the Square Root', command=get_SquareRoot, bg='brown', fg='white', font=('helvetica', 9, 'bold'))
canvas.create_window(200, 180, window=button)
ws.mainloop()
Output:
In the following output, we see the canvas inside the canvas there’s an entry widget where the user can enter the number. After entering the number, click on the Get the Square Root button.
After clicking on the button, the user input saves as a variable in the form of a square root.
Read: Python Tkinter Events
Python Tkinter save canvas image
In this section, we will learn how to save the canvas image in Python Tkinter.
In the below code, we are creating a canvas shape by using the PyQt5 library.
- It is a cross-platform GUI toolkit through which we can develop interactive applications with ease of the tools and simplicity provided by the library.
- PyQt5 has provided a tool QtDesigner that helps to design our frontend by drag and drop method that helps to make our development faster.
Code:
- PyQt5.QtWidgets library help to create widgets.
- PyQt5.QtGui help to make our application a GUI structure.
- PyQt5.QtCore is used to set of python binding.
from tkinter import *
import tkinter as tk
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
title = "Python Guides"
top = 300
left = 300
width = 700
height = 500
self.setWindowTitle(title)
self.setGeometry(top, left, width, height)
self.Image = QImage(self.size(), QImage.Format_RGB32)
self.Image.fill(Qt.white)
MainMenu = self.menuBar()
fileMenu = MainMenu.addMenu("File")
SaveAction = QAction("Save", self)
SaveAction.setShortcut("Ctrl + S")
fileMenu.addAction(SaveAction)
SaveAction.triggered.connect(self.save)
self.draw_something()
def paintEvent(self, event):
canvaspainter = QPainter(self)
canvaspainter.drawImage(self.rect(), self.Image,
self.Image.rect())
def draw_something(self):
painter = QPainter(self.Image)
painter.setPen(QPen(Qt.black, 5, Qt.SolidLine,
Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(100, 100, 300, 300)
self.update()
def save(self):
# selecting file path
filePath, _ = QFileDialog.getSaveFileName(self, "Save Image", "",
"PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) ")
if filePath == "":
return
self.Image.save(filePath)
if __name__ == "__main__":
application = QApplication(sys.argv)
ws = Window()
ws.show()
sys.exit(application.exec())
Output:
After running the following code, we created a simple canvas which we can see as an output to make this we use PyQt5 Library under which we imported QtWidgets, QtGui, and Gtcore library. In-display, we can see a menu bar with a File tab that is performing an action to save our draw image to .PNG format.
Here, after clicking on the save button a dialog box will appear which will ask with which name we want to save our image and at what location inside our system we want to store/save.
You may also like to read the following Tkinter tutorials.
- Python Tkinter Animation
- Python Tkinter Multiple WindowsÂ
- Python Tkinter Editor
- Python Tkinter panel
- Python Tkinter after method
- Python Tkinter Table
- Python Tkinter Quiz
So, in this tutorial, we have discussed Python Tkinter save text to file and we also covered different examples. Here is the list of examples that we have covered.
- Python Tkinter save text to file
- Python Tkinter save text dialog box
- Python Tkinter save file path
- Python Tkinter save entry
- Python Tkinter save button
- Python Tkinter save input to variable
- Python Tkinter save canvas image
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.