how to open text file through Tkinter Text widget - Python MagicStick Text Editor - Part 11

Posted by Suraj Singh on May 15, 2017 · 22 mins read
hii readers,




                    Python Text Editor is really very powerful widget of Tkinter Module.With This Text Widget, we can do several things. For Example,  To Edit any text file using tkinter text widget, first we need to import text content in text widget as text character and then, after doing editing, we also need to save that edited content in text file. very simple!. So, Today In this Tutorials, I am going to show you how to create a complete function set that can work like a file handler for your tkinter text widget or in other other word, how to open text file through Tkinter Text Widget.

readers, This Is our 11th Tutorial Of Python MagicStick Project But,  if you are a new visitor, Then I will suggest you to read our tutorials number wise. because in these tutorial series i am showing how to use python tkinter module to create a real life application.

Links For Tutorials

MagicStick Text Editor Introduction
MagicStick Text Editor Part 1
MagicStick Text Editor Part 2
MagicStick Text Editor Part 3
MagicStick Text Editor Part 4
MagicStick Text Editor Part 5
MagicStick Text Editor Part 6
MagicStick Text Editor Part 7
MagicStick Text Editor Part 8
MagicStick Text Editor Part 9
MagicStick Text Editor Part 10
MagicStick Text Editor Part 11
MagicStick Text Editor Part 12
MagicStick Text Editor Last Part

Or You Can Also Download Our Updated Example Codes Of Python MagicStick Text Editor Project For Understanding This Project More Clearly.

Check Here Our Github Repo





Now, let's focus to our main topic.

In this Functions, We will use Simple methods for performing our tasks.

For Reading Content From File:


fileobject = open("filename.txt","r")

content = fileobject.read()

fileobject.close()


Here, As You Can see in above example, for reading content from text file. Create file Object with read-only mode flag, store content in another variable and close file object.

As Same In Writing Function:


fileobject = open("filename.txt","w")

fileobject.write(content)

fileobject.close()


After Creating These Function we will use Tkinter Bind Functions For binding our functions with specified keyboard shortcut keys.


To make this script easy to understand we will create a separate empty script "
FileHandler.py" in "magicsticklibs/" folder and write our codes  in it.

So, let's do some practical coding's.

1. FileHandler.py



  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
##
##
## ################################################
## ###### Please Don't Remove Author Name #########
## ############# Thanks ###########################
## ################################################
##
##
__author__='''

######################################################
By
######################################################

Suraj Singh


surajsinghbisht054@gmail.com
http://www.bitforestinfo.com/


######################################################
'''
from Graphics import Tkinter, tkFileDialog

class FileHandler:
def __init__(self, text):
self.text = text
self.text.storeobj['OpenFile']=None
self.functions_key_bindings()
self.binding_key_configuration()

def binding_key_configuration(self):
for key in ['<Control-N>',"<Control-n>"]:
self.text.bind(key, self.new_file)
for key in ['<Control-S>',"<Control-s>"]:
self.text.bind(key, self.save_file)
for key in ['<Control-Shift-S>',"<Control-Shift-s>"]:
self.text.bind(key, self.save_as)
for key in ['<Control-O>',"<Control-o>"]:
self.text.bind(key, self.open_file)
for key in ['<Control-q>',"<Control-Q>"]:
self.text.bind(key, self.quit)
return

def functions_key_bindings(self):
self.text.storeobj['Open']=self.open_file
self.text.storeobj['Save']=self.save_file
self.text.storeobj['SaveAs']=self.save_as
self.text.storeobj['OpenNew']=self.new_file
return

def open_file(self, event=None):
path = tkFileDialog.askopenfilename()
if path:
data=open(path,"rb").read()
self.text.delete('1.0','end')
self.text.insert("1.0", data)
self.text.storeobj['OpenFile']=path
return

def save_file(self, event=None):
if not self.text.storeobj['OpenFile']:
path = tkFileDialog.asksaveasfilename()
else:
path = self.text.storeobj['OpenFile']
if path:
data = self.text.get("1.0",'end')
f_=open(path,"wb")
f_.write(data)
f_.close()
self.text.storeobj['OpenFile']=path
return

def save_as(self, event=None):
path = tkFileDialog.asksaveasfilename()
if path:
data = self.text.get("1.0",'end')
f_=open(path,"wb")
f_.write(data)
f_.close()
return

def new_file(self, event=None):
print "New"
return

def quit(self, event=None):
import sys
sys.exit(0)
return



if __name__ == '__main__':
root = Tkinter.Tk()
pad = Tkinter.Text(root)
pad.pack()
pad.storeobj={}
FileHandler(pad)
root.mainloop()





To Run These Script Codes alone, Just Change line 24 from

"from Graphics import Tkinter"

To  "import Tkinter"

Or

To Run This Codes as MagicStick Script. Don't Do Any Changes in this codes.


 Now, let's join this script in MagicStick Text Editor Project ( Follow Below Steps only, when you have not Connected this script with MagicScript Main Stream).

To Connect This Script With MagicStick project, we need to do only two steps.


1. first, Place This Script In Our "MagicStick/magicsticklibs" Project Directory.


2. Add Function Of This Script in Our "ConfigSettings.py".




Let me explain you these steps in more details.


Step 1.
 Place "FileHandler.py" In Our "MagicStick/magicsticklibs" Project Directory.



Then Our MagicStick Project Directory Structure will look like this.




MagicStick_Editor_Part_10
|
|---> About.txt
|
|---> magicsticklibs
| |
| |---> __init__.py
| |
| |---> Main.py
| |
| |---> TextPad.py
| |
| |---> Graphics.py
| |
| |---> ConfigSettings.py
| |
| |---> ScrollBar.py
| |
| |---> LineNumber.py
| |
| |---> StationeryFunctions.py
| |
| |---> PopupMenu.py
| |
| |---> FindAndReplace.py
| |
| |---> FileHandler.py
|
|---> main.py

Step 2.
          Add "FileHandler.py" Function in Our "ConfigSettings.py" because in this project, "ConfigSettings.py" is responsible for joining libs in main stream.

ConfigSettings.py Modified Codes


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
##
##
## ################################################
## ###### Please Don't Remove Author Name #########
## ############# Thanks ###########################
## ################################################
##
##
__author__='''

######################################################
By
######################################################

Suraj Singh


surajsinghbisht054@gmail.com
http://www.bitforestinfo.com/


######################################################
'''

from LineNumber import LineMain
from ScrollBar import Scrollbar
from StationeryFunctions import StationeryFunctions
from PopupMenu import Popup
from FIndAndReplace import FindReplaceFunctions
from FileHandler import FileHandler

class Connect:
def __init__(self, pad):
self.pad = pad
self.modules_connections()


def modules_connections(self):
LineMain(self.pad)
Scrollbar(self.pad)
StationeryFunctions(self.pad)
Popup(self.pad)
FindReplaceFunctions(self.pad)
FileHandler(self.pad)
return



Boom! Our FileHandler.py script is now ready to use and also, this script is now connected with MagicStick Project Main stream. To run this script in main stream of project. just run "main.py" script or you can also run this script alone and parallel without touching project main stream just run "FileHandler.py".



This Tutorial Ends Here,


In My Next Tutorial, We will Continue This project.


Written By