How to distribute the python software for windows 10?

This article will show you how to distribute your python software for windows 10 after you have finished creating it. In order to distribute the software written in python to the windows 10 platform’s users all you need to do is to use a python module known as PyInstaller which will help you to turn the python script into an executable application which can then be used on the windows 10 platform.

Before you can use the pyinstaller module you will need to download and install the PyInstaller module first, open up the windows command prompt and type in this command : pip install pyinstaller to install the PyInstaller module into the site-packages folder.

After you have installed the pyinstaller module then all you need to do is to browse to the folder where you have saved your python program and then run the below command in the windows command prompt.

pyinstaller firstpythonproject.py

where firstpythonproject.py is the python program which you wish to turn into an application.

Once pyinstaller has finished it’s job you should find a few folders together with your original python script and a spec file under that same folder.

open up the dist folder
open up the dist folder

Under the dist folder you will find another folder with the same name as your python script and in this folder you will find an application file which you can then double click and open it up just like any other ordinary software which runs on windows 10.

After you have started your application you will see a console window at it’s background, in order to get rid of that console you will need to do one simple change within the firstpythonproject.spec file. Open up the firstpythonproject.spec file and then change the console value from True to False within the EXE module.

exe = EXE(pyz,
          a.scripts,
          exclude_binaries=True,
          name='firstpythonproject',
          debug=False,
          strip=False,
          upx=True,
          console=False )

After that run this command in the windows command prompt : pyinstaller firstpythonproject.spec to regenerate all the contents within the dist directory. Now go into the dist directory again and double click on the application file to start the program without the console at it’s background.

This time no more console
This time no more console

If you want to distribute your application now then all you need to do is to upload the entire firstpythonproject folder (or zip it up) to your website so people can download it and open up the application file by double clicking on it! Although there are other tools that you can use to pack up your software but PyInstaller is the best according to my humble opinion because it is so easy to use as compared to the others.

Your very first wxPython project in Python 3.5.2

Today I will introduce you to wxPython which is another GUI toolkit besides tkinter which you can use to create GUI for your python application. Phoenix is wxpython for python version 3.x.x which you can download through this link : https://wxpython.org/Phoenix/snapshot-builds/, remember to download the latest version of Phoenix which matches your python version (3.x.x) and your OS. I have Python 3.5.2 installs in my pc that runs on the 64bit windows 10 os so I have downloaded the wxPython_Phoenix-3.0.3.dev2421+1efd6fb-cp35-cp35m-win_amd64.whl file to my pc.

Once you have downloaded the whl file you will need to install it in the python site package folder with this command : pip3 install wxPython_Phoenix-3.0.3.dev2421+1efd6fb-cp35-cp35m-win_amd64.whl.

After you have installed the module, start a new project in NetBeans 8.1 IDE and then create a new python module under the Sources folder just like before. In this new module enter below script.

# Import wxPython module and system module
import wx
import sys

# Subclass wxPython frame
class WXFRAME(wx.Frame):
    
    def __init__(self, parent, title, size=(200,100)):
        
        # Initialize super class
        wx.Frame.__init__(self, parent, title=title, size=size)
    
        # Set frame background color
        self.SetBackgroundColour('grey')

        # Create Status Bar
        self.CreateStatusBar()

        # Create the Menu
        menu= wx.Menu()
    
        # Add menu items to the menu and bind those items with event listener
        about = menu.Append(wx.ID_ABOUT, "About", "wxPython Demo")
        self.Bind(wx.EVT_MENU, self.about_, about)
        menu.AppendSeparator()
        exit = menu.Append(wx.ID_EXIT,"Exit"," Exit")
        self.Bind(wx.EVT_MENU, self.exit_, exit)
    
        # Create the menubar
        menuBar = wx.MenuBar()

        # Connect menu to menubar and set the MenuBar title
        menuBar.Append(menu,"File")

        # Connect the menubar to the frame
        self.SetMenuBar(menuBar)
    
        # Display the frame
        self.Show()
    
    # Exit function to close the program
    def exit_(self, e):
        sys.exit(0)
        
    # About function to show the about message
    def about_(self, e):
        wx.MessageBox("This is a wxPython demo...", "wxPython Demo" ,wx.OK | wx.ICON_INFORMATION)


# Create instance of wxPython application
app = wx.App()

# Ceeate the wx.Frame's instance
WXFRAME(None, "wxPython demo", (300,300))

# Run the main GUI event loop
app.MainLoop()

Run the module, click on File->About and see the below outcome…

Select the About item
Select the About item

Next click on the Exit item to close the program.

As you can see, wxpython has almost all those features provided by tkinter and many more, you can find out how to use all the Phoenix features through this link : https://wxpython.org/Phoenix/docs/html/classic_vs_phoenix.html

How to create a sqlite table then populate data within python 3.5.2

In this python 3.5.2 tutorial we will first create a sqlite table and then populate that table with few rows of data. In order to create a sqlite table we need to import the sqlite3 module into our python 3.5.2 program. The good thing about this module is that it has already been included in python 3.5.2 so we do not need to download it separately into our python package.

Alright, without wasting any time let get started. I am using Eclipse to create my python project, let us create a new PyDev project in Eclipse. If you have read my previous tutorial before then you should know that we need to install the PyDev plugin in order for us to create and run our python project in Eclipse, so if you have not yet installed the plugin just go ahead and do so.

After you have installed the PyDev plugin then go ahead and follow the following instruction to create and populate the sqlite table with data.

1) Before you create this new project you will need to create the MyClassDemo project first because we will need to use it’s PersonalData class in this tutorial. Go ahead and create the MyClassDemo project through this tutorial link :
http://gamingdirectional.com/blog/2016/07/31/how-to-create-a-python-class/

2) After you have created the MyClassDemo project you can now create a new SqliteDemo project in PyDev through File->New->PyDev Project.

Fill in the project detail
Fill in the project detail
check the MyClassDemo project
Check the MyClassDemo project, you will need it to import the personaldata.py module into the SqliteDemo project

3) Next create a new package under the SqliteDemo project’s src folder through right click on the project folder->New->PyDev package.

Fill in the package name then click Finish
Fill in the package name then click Finish

3) Then create the insertEmployeeData.py module under the SqliteDemo package through right click on the package->New->PyDev Module

Fill in module name then click Finish
Fill in the module name then click Finish
Select Module Main
Select Module Main

4) Now your project should have the following file structure.

Project File Structure
Project File Structure

5) Next double click on the insertEmployeeData.py module to open it up on the code editor window.

6) In the editor window, enter the below script to import the PersonalData class from the MyClassDemo project into the insertEmployeeData.py module.

from os import path
import sys
sys.path.append(path.abspath('../MyClassDemo')) #let Eclipse knows where to find the MyClassDemo project path

from MyClass.personaldata import PersonalData 

7) Continue entering the below script under if __name__ == ‘__main__’: to gather the data of that particular employee and then create a new employee object from the PersonalData class and populate it with name, job and salary of that particular employee.

if __name__ == '__main__':
    
    name = input("Enter Employee Name")
    job = input("Enter Employee Job")
    salary = input("Enter Employee Salary")
    
    employeeObject = PersonalData(name, job, salary)

8) Next at the top of the insertEmployeeData.py module import the sqlite3 module into our program as well as provide a new name for our new sqlite3 database.

import sqlite3
db_name = 'employeedata.sqlite'

9) Now create our employee table in the employeedata.sqlite database

# connect to the employeedata.sqlite database, if the database is not there yet then create it
connection = sqlite3.connect('employeedata.sqlite')
cursor = connection.cursor()

# retrieve the employee table name which we have created
cursor.execute("""SELECT name FROM sqlite_sequence WHERE name='employee'""")
name_is_there = cursor.fetchone()[0]


# if the employee table has not been created yet then we shall create it
if name_is_there != 'employee':
    cursor.execute("""CREATE TABLE employee (
                    id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,
                    name TEXT NOT NULL,
                    job  TEXT NOT NULL,
                    salary TEXT NOT NULL) """)

10) Insert the data we have gathered at the beginning of the program into the employee table.

cursor.execute("INSERT INTO employee (name, job, salary) VALUES (?, ?, ?)", (employeeObject.name, employeeObject.work, employeeObject.earning)) # insert data into the employee table
connection.commit()
connection.close() #close the connection

11) Now run the above program (on the Eclipse’s console) and entering those information when the program asks you to do so, press the enter key on your keyboard after each answer!

Eclipse Console
Eclipse Console

12) There should be a employeedata.sqlite database file in your src folder at this moment.

employeedata.sqlite
employeedata.sqlite

13) Open it up, do you see this?

sqlite3
sqlite3

14) As you can see the file above is not meant for human to read it. We need a software which can read those information we have inserted into the employee table. Go ahead and download this powerful db browser from http://sqlitebrowser.org and then open it up once you have downloaded and installed it on your pc.

15) Now open up the sqlitebrowser then load the sqlite database you have just created through File->Open DataBase. Under the Database Structure tab there are two tables, 1) the sqlite_sequence table is use to keep all the tables of the employeedata.sqlite database, 2) the employee table is the one which we have just created.

Open the database
Open the database

16) Switch to the Browse Data tab and select the employee table under the drop down list, you should now see the data that we have inserted into this table.

The are two John here...
The are two John here…

Do you realize that there are two persons with the same name “John” in the employee table? As you can see the only data which is unique in our table is the id and the rest of the field can consist of the same repeated value because we have programmed the table in such a way.

17) There are lots of thing you can do with sqlitebrowser besides the above mentioned feature, for example you can learn sql by directly entering the sql command into the console as shown below.

Enter SQL command here
Enter SQL command here

One thing you might feel puzzling about is why do we need to use the PersonalData class to create the employeeObject instead of directly insert the data returns by the input function into the table? Actually we do not need the employeeObject at all but this step will prepare you for my next python lesson which will involve both the employeeObject and the sqlite3 module.

Here is the complete script for the insertEmployeeData.py module

import sqlite3
db_name = 'employeedata.sqlite'

from os import path
import sys
sys.path.append(path.abspath('../MyClassDemo')) #let Eclipse knows where to find MyClassDemo project path

from MyClass.personaldata import PersonalData 

if __name__ == '__main__':
    
    name = input("Enter Employee Name")
    job = input("Enter Employee Job")
    salary = input("Enter Employee Salary")
    
    employeeObject = PersonalData(name, job, salary)
    
    # connect to the employeedata.sqlite database, if the database is not there yet then create it
    connection = sqlite3.connect('employeedata.sqlite')
    cursor = connection.cursor()
    
    # retrieve the employee table name which we have created
    cursor.execute("""SELECT name FROM sqlite_sequence WHERE name='employee'""")
    name_is_there = cursor.fetchone()[0]
    
    # if the employee table has not been created yet then we shall create it
    if name_is_there != 'employee':
        cursor.execute("""CREATE TABLE employee (
                        id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,
                        name TEXT NOT NULL,
                        job  TEXT NOT NULL,
                        salary TEXT NOT NULL) """)
        
    cursor.execute("INSERT INTO employee (name, job, salary) VALUES (?, ?, ?)", (employeeObject.name, employeeObject.work, employeeObject.earning)) # insert data into the employee table
    connection.commit()
    connection.close()

Do you enjoy this tutorial? If so don’t forget to subscribe to my blog for more future tutorial on Python, Javascript, Blender and many more…

Create many classes within a same python module

Besides creating a class within another class we can also create many classes within the same python module. Let us take a look at how to create a python module with many classes in it.

Start a new Eclipse’s project as before then create this module :- doubleclassdemo.py and input below python script into it.

class FirstClass(object):
    
    def __init__(self, welcome = "welcome to first class server!"):
        print(welcome)
        
class SecondClass(object):

    def __init__(self, welcome = "welcome to the second class server!"):
        print(welcome)

As you can see we have created two classes in one module. Next create another python module and name it mainserver.py then enter below script into it.

import doubleclassdemo 

if __name__ == '__main__':
    print(doubleclassdemo.FirstClass())
    print(doubleclassdemo.SecondClass())

Run the mainserver.py module.

As you can see we have imported the doubleclassdemo module into this module and then create a new instance for both classes within the doubleclassdemo module inside that print method which will first call the __init__ method of each class to print out the welcome message and then will call the __str__ method to return the memory address of each class and print it out!

welcome to first class server!
<doubleclassdemo.FirstClass object at 0x00FE5C10>
welcome to the second class server!
<doubleclassdemo.SecondClass object at 0x00FE5C10>

Do you realize that both classes do share the same memory address? Hmmm…interesting.

Create an inner class in python language

Python allows us to create an inner class within a python class just like how we create any ordinary class.

In following example I have created a new class within the PersonalData class which I have created before so that new class will behave like a list which allows us to insert the previous job history of an employee into it so we can retrieve them later on.

class JobHistory(list):
        
        def __init__(self):
            list.__init__([])

As you can see we make that inner class extends the list class so it behaves just like a list. Now we can use it just like any other class by initiating that inner class and then inserted job history of an employee into it in the runmyclass.py module.

personalData = PersonalData("John", "computer programmer","1000") #create an instance of the PersonalData class
job_history = personalData.JobHistory() #create an instance of the JobHistory inner class
job_history.append('python programmer') #append history to the list
job_history.append('web developer')
job_history.append('android developer')

Print out the job history is also very simple.

print ("Before this " + personalData.name + " is a : ")
    print("")
    for job in job_history:
        print(job)

The outcome for the entire program is as follow:

John works as a computer programmer and he has a monthly income of 1000
John now works as a project manager and he has a monthly income of 3000
Before this John is a :

python programmer
web developer
android developer

*Refer to my previous tutorial on the PersonalData class.

How to create a python class

In this tutorial I am going to show you how to create a class in python and then create an instance object from that class. What we want here is to create a python class which will receive the name, job, salary and a boolean parameter which indicates whether that person has changed his or her job recently or not so the default __str__ method from that class will return different string based on that boolean value. OK let get started.

This time I will use eclipse to write the python script but you can use other IDE such as NetBeans 8.1 as well if you want to, both Eclipse and NetBeans are the top IDE I use to write the python script. Before you can create a python project in Eclipse make sure you have installed the PyDev plugin through Help->Install New Software.

Install PyDev
Install PyDev

If you have not yet installed the PyDev plugin before then click on the Add button and provide a name together with this link http://pydev.org/updates to download and install the PyDev plugin.

Once you have installed the plugin in Eclipse you can now go to File->New->PyDev project and create a new python project just like how you create other project in Eclipse.

I will leave you to create the new project with Eclipse and concentrate on the main topic which is how to create a python class.

After creating a package within that project you can now create a new module calls personaldata.py and enter the below script into it.

class PersonalData(object):

        def __init__(self, name, work, earning = 0, change = False):
            self.name = name
            self.work = work
            self.earning = earning
            self.change = change
        
        def __str__(self):
            if(self.change == False):
                return "%s works as a %s and he has a monthly income of %s" % (self.name, self.work, self.earning)
            else:
                return "%s now works as a %s and he has a monthly income of %s" % (self.name, self.work, self.earning)
        
        def changeJob(self, work, income, change = False):
            self.work = work
            self.earning = income
            self.change = change

Every python class needs to have an __init__ method where self is the first parameter which will be automatically passed into the method, self is very important because the instance of that class will use this parameter to call a method or to access a variable of that object.

The rest of the parameters will be passed in at the time you create a new instance of that class. You can also set the default value for each parameter so that instance can use any of those values if any of those values has not been passed into the class at the time you create an instance of that class. The same goes to the class’s method as well.

Now let us create the main python module which will include the PersonalData’s class instance in it. Let create a new python module and name it runmyclass.py. Now you should see those two python modules under the same package.

Folder Tree
Folder Tree

Next enter below script into the runmyclass.py module…

from personaldata import PersonalData

if __name__ == '__main__':
    
    personalData = PersonalData("John", "computer programmer","1000")
    print (personalData)
    personalData.changeJob("project manager", "3000", True)
    print (personalData)

As you can see you will need to import the PersonalData class into this module before you can use it.

If you want to run any python module then you will need this line of statement,

if __name__ == ‘__main__’

make sure you do that.

Next let create an instance of the PersonalData class and enter the second, third and fourth parameter into it, you do not need to enter the fifth parameter if you don’t want to because it already has a default boolean value which is False.

Now you can call the print method and pass in that new instance, what will happen here is this instance will call it’s own __str__ method and return a string based on the boolean value you have passed in, in this example when we first create the new instance Mr. John has not changed his job yet so change = False.  We can overwrite the __str__ method and return any string that we wish to in this program.

We then call the changeJob method and pass three parameters into that method, the last one will be used as the boolean value to decide which string should we return this time.

The program above will produce the below output.

Python Class Demo
Python Class Demo

That is it for this tutorial, as you can see creating class in python is not that hard after all, right? If you are interested in learning more about class in python then continue to read this tutorial Create an inner class in python language.

Tuning up the previous text editor with tkinter

In this article I will continue with the text editor development tutorial. In the previous post I have created a text box and a save button for my text editor so we can save our work later on, however the previous interface does not look professional so I have decided to change and redo the entire GUI to make it looks better as well as prepared the text editor for the future expansion.

All right, without further talking let get started. I have broken down the python script into small parts to make it easy for you to follow my code.

1) Import a few modules into our new program.

import tkinter as tk 
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import ttk

2) Create the window object.

win = tk.Tk() #create an instance
win.title("Write Word") #add a title

3) Create the label frame to host the checkboxes

labelFrame = ttk.LabelFrame(win, text="Text Property")
labelFrame.grid(column=0, row=2, padx=30, pady=10, sticky=tk.W)

4) Create the checkboxes and hosted them in labelFrame.

#create a few checkboxes
ckValueObj1 = tk.IntVar()
ckValueObj2 = tk.IntVar()
ckValueObj3 = tk.IntVar()

chk1 = tk.Checkbutton(labelFrame, text="Highlight Text", variable=ckValueObj1, command=changeState)
chk1.deselect()
chk1.grid(column=0, row=2, sticky=tk.W)

chk2 = tk.Checkbutton(labelFrame, text="Bold Text", variable=ckValueObj2, command=changeState)
chk2.deselect()
chk2.grid(column=1, row=2, sticky=tk.W)

chk3 = tk.Checkbutton(labelFrame, text="Green Text", variable=ckValueObj3, command=changeState)
chk3.deselect()
chk3.grid(column=2, row=2, sticky=tk.W)

5) Create the function which will be called every time we checked or unchecked any checkbox.

def changeState(): # receive chackbox updates
    
    state1 = ckValueObj1.get() #use this value to highlight the background of the text with yellow color
    state2 = ckValueObj2.get() #use this value to change the text to bold
    state3 = ckValueObj3.get() #use this value to turn the text to green
    
    if state1 == 1: 
        scrollText.tag_add('highlightline', '1.0', 'end-1c')
        scrollText.tag_configure('highlightline', background='yellow', relief='raised')
    else:
        scrollText.tag_remove('highlightline', '1.0', 'end-1c')
        
    if state2 == 1:
        scrollText.tag_add('makebold', '1.0', 'end-1c')
        scrollText.tag_configure('makebold', font='helvetica 12 bold', relief='raised')
    else:
        scrollText.tag_remove('makebold', '1.0', 'end-1c')
    
    if state3 == 1:
        scrollText.tag_add('green', '1.0', 'end-1c')
        scrollText.tag_configure('green', foreground='green', relief='raised')
    else:
        scrollText.tag_remove('green', '1.0', 'end-1c')

6) Create the scroll text editor.

scrolW = 50
scrolH = 10 
scrollText = scrolledtext.ScrolledText(win, width=scrolW, height=scrolH, wrap=tk.WORD)
scrollText.grid(column=0, row= 0, columnspan=3)

7) Create the main menu items.

menuBar = Menu(win) # create menu bar
win.config(menu=menuBar) # attach menubar to window

fileMenu = Menu(menuBar, tearoff=0) # create a menu in the menu bar and remove the default dash line
fileMenu.add_command(label="Save", command=_saveFile) # create the save file sub menu
fileMenu.add_command(label="Exit", command=_closeFile) # create the close file sub menu
menuBar.add_cascade(label="File", menu=fileMenu) # create main menu

8) Create the save file function for the Save item.

def _saveFile(): #save file command
    try:
        with open('note.txt', 'w') as note:
            text = scrollText.get("1.0", 'end-1c') #get text entry
            note.write(text) #write text to file
    except IOError as err:
        print("File error " + str(err))

9) Create exit command for the Exit item.

def _closeFile(): #close file command
    win.quit()
    win.destroy()
    exit()

10) Most of the script above is self-explaining so you should understand them if you know the basic python language. The full code is as follow.

import tkinter as tk 
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import ttk

win = tk.Tk() #create instance
win.title("Write Word") #add a title

def _saveFile(): #save file command
    try:
        with open('note.txt', 'w') as note:
            text = scrollText.get("1.0", 'end-1c') #get text entry
            note.write(text) #write text to file
    except IOError as err:
        print("File error " + str(err))
        
def _closeFile(): #close file command
    win.quit()
    win.destroy()
    exit()
    
def changeState(): # receive chackbox updates
    
    state1 = ckValueObj1.get() #use this value to highlight the background of the text with yellow color
    state2 = ckValueObj2.get() #use this value to change the text to bold
    state3 = ckValueObj3.get() #use this value to turn the text to green
    
    if state1 == 1: 
        scrollText.tag_add('highlightline', '1.0', 'end-1c')
        scrollText.tag_configure('highlightline', background='yellow', relief='raised')
    else:
        scrollText.tag_remove('highlightline', '1.0', 'end-1c')
        
    if state2 == 1:
        scrollText.tag_add('makebold', '1.0', 'end-1c')
        scrollText.tag_configure('makebold', font='helvetica 12 bold', relief='raised')
    else:
        scrollText.tag_remove('makebold', '1.0', 'end-1c')
    
    if state3 == 1:
        scrollText.tag_add('green', '1.0', 'end-1c')
        scrollText.tag_configure('green', foreground='green', relief='raised')
    else:
        scrollText.tag_remove('green', '1.0', 'end-1c')
 
#create label frame to host the checkboxes    
labelFrame = ttk.LabelFrame(win, text="Text Property")
labelFrame.grid(column=0, row=2, padx=30, pady=10, sticky=tk.W)

#create a few checkboxes
ckValueObj1 = tk.IntVar()
ckValueObj2 = tk.IntVar()
ckValueObj3 = tk.IntVar()

chk1 = tk.Checkbutton(labelFrame, text="Highlight Text", variable=ckValueObj1, command=changeState)
chk1.deselect()
chk1.grid(column=0, row=2, sticky=tk.W)

chk2 = tk.Checkbutton(labelFrame, text="Bold Text", variable=ckValueObj2, command=changeState)
chk2.deselect()
chk2.grid(column=1, row=2, sticky=tk.W)

chk3 = tk.Checkbutton(labelFrame, text="Green Text", variable=ckValueObj3, command=changeState)
chk3.deselect()
chk3.grid(column=2, row=2, sticky=tk.W)

# create a scroll text editor
scrolW = 50
scrolH = 10 
scrollText = scrolledtext.ScrolledText(win, width=scrolW, height=scrolH, wrap=tk.WORD)
scrollText.grid(column=0, row= 0, columnspan=3)

# create menu items
menuBar = Menu(win) # create menu bar
win.config(menu=menuBar) # attach menubar to window

fileMenu = Menu(menuBar, tearoff=0) # create a menu in the menu bar and remove the default dash line
fileMenu.add_command(label="Save", command=_saveFile) # create the save file sub menu
fileMenu.add_command(label="Exit", command=_closeFile) # create the close file sub menu
menuBar.add_cascade(label="File", menu=fileMenu) # create main menu

scrollText.focus() #focus on the scroll text editor

win.mainloop() #start GUI

If you run the program now in NetBeans 8.1 IDE then you can check on the checkboxes below the scroll text editor to see various effects that we have included in our python script above.

Text Editor
Text Editor

You can select the save command to save your file in plain text or the exit command to terminate the program under the File’s drop down menu. I will continue to develop this text editor so make sure you return and read more about it, you can find this text editor under the python text editor tag on this blog.

How to create a simple text editor with tkinter

If we want to create a GUI program in Python 3 then Tkinter seems like the best choice because 1) tkinter module has already been included in Python 3 and thus we do not need to download and install an extra module 2) wxPython does not support Python 3 development and also it is already out of date.

Below is the python program I have created which allows user to input text into the textbox then saves it in the text file later on.

import tkinter as tk 
from tkinter import ttk 
from tkinter import Text

win = tk.Tk() #create instance
win.title("Write Note") #add a title

def saveFile():
    try:
        with open('note.txt', 'w') as note: #open file
            text = text_entry.get("1.0", 'end-1c') #get text entry
            note.write(text) #write text to file
    except IOError as err:
        print("File error " + str(err))
        
text_entry = Text(win,width=50,height=30) #create text editor
text_entry.grid(column=0, row=0) 

action = ttk.Button(win, text="Save", command=saveFile) #create button
action.grid(column=0, row=1)
action.config(width=66)

text_entry.focus()
win.mainloop() #start GUI

The program above will create a textbox and a button which once you have clicked on it it will call the saveFile() function to save the text into a text file (or creates the text file first if it has not been created yet).

Enter some words then press Save
Enter some words then press Save

tkinter module actually can match wxPython in every field and therefore there is no need for us to use another new module for our Python 3 GUI development!

Latest update :

I have decided to make a few changes to the script and come out with a new script to create our text editor. Kindly read the text editor latest development in this article http://gamingdirectional.com/blog/2016/07/30/tuning-up-the-previous-text-editor-with-tkinter/

How to write python program in windows command prompt

After you have installed python in your computer, you can either use NetBeans 8.1 or Eclipse or any other IDE to write the python script then run it. However, for some of you who do not have any IDE installed on your computer then you might want to consider using the windows command prompt which is also good for writing simple python program if you know how to use it.

With Python installed on your pc lets open up the command prompt, then type in python to start the python shell, then from there you can start to type in the python script then run the program.

Lets write a simple python script to sort a list as follow, you will need to press the enter key each time you have completed a line.

windows command prompt
windows command prompt

The script above will sort the data in ascending order.

As you see we can use windows command prompt to write and run the python script easily, but for the complicated program which requires us to debug and change the script rapidly then we will need to use the real IDE such as NetBeans or Eclipse.

How to create windows graphic user interface with tkinter

This article will show you how to create windows GUI with python’s tkinter module. It is very easy to create a pop up window with tk module. First start up your NetBeans IDE, then create a new project as I have shown you before in my previous article. Next enter below script into the NetBeans code editor and run it!

import tkinter as tk 

win = tk.Tk() # create tk instance
win.title("tkinter GUI") # add a title

win.mainloop() # start the GUI

Basically the above python script will create an empty window with the tkinter module then start the window’s event loop by calling the mainloop method from the tk’s class instance as shown in the following graphic.

tk GUI
tk GUI