Building a Notepad Application with TkModule: A Pythonic Approach

Kartavya Shukla

March 24, 2022

TkModule: A Pythonic Gateway to Tkinter

In the realm of graphical user interface (GUI) development within the Python ecosystem, Tkinter has long stood as the standard library for creating simple and effective GUI applications. However, despite its widespread use, newcomers and even seasoned developers often find themselves entangled in the verbosity and complexity of Tkinter’s traditional approach. Enter TkModule, a Python package that emerges as a beacon of simplicity, transforming the way we interact with Tkinter.

TkModule is not just another wrapper; it is a thoughtful utility that draws inspiration from the likes of KivyMD, extending the capabilities of Kivy by providing a set of Material Design components. Similarly, TkModule equips developers with a suite of tools and functions that elevate the Tkinter experience to new heights, making GUI creation more intuitive, faster, and more enjoyable.

pip install tkmodule

Source Code and ASMR Video

Github Source Code

Youtube Video ASMR


The Genesis of a GUI Application

Our journey begins with the creation of the parent window using TkModule’s createTk() function. This sets the stage for our Notepad, providing a full-screen window titled “Untitled - Notepad”. The simplicity of TkModule shines here, as we can set up our main window with minimal code:

Crafting the Core Functions

A Notepad application is defined by its ability to create new files, open existing ones, save edits, and quit the application. These functions form the backbone of our program. With TkModule, implementing these functions is straightforward, thanks to its intuitive command binding and file dialog utilities:

The Beginning: Setting Up the Main Window

from tkmodule.tkmodule import *
from tkinter import font
from tkinter.filedialog import askopenfilename,asksaveasfilename
from tkinter.messagebox import showinfo
import os

# Parent Window
root=createTk()
root.Window(title="Untitled - Notepad",fullscreen=True)

Here, we import the necessary modules from TkModule and Tkinter. We then create the main window of our application, setting it to full screen and giving it a default title of “Untitled - Notepad”. The createTk() function is a TkModule utility that initializes the main window, while root.Window() sets its properties.

Core Functionality: New, Save, Open, and Quit

Deep Dive into the Notepad’s Functionalities

The Notepad application we’re building with TkModule is more than just a text editor; it’s a fully functional tool that handles various file operations. Let’s explore the key functions that make this possible.

The New Function: Starting Afresh

file=None
def New():
    global file
    root.tk.title("Untitled - Notepad")
    file = None
    root.Textvar.delete(1.0, END)

When the user selects ‘New’ from the menu, this function is triggered. It sets the stage for a new document by clearing the text area and resetting the file variable, which tracks the current file path.

The Save Function: Preserving Your Work

def Save():
    global file
    if file == None:
        file = asksaveasfilename(initialfile = 'Untitled - Notepad.txt', defaultextension=".txt",
                        filetypes=[("All Files", "*.*"),
                                    ("Text Documents", "*.txt")])
        if file=="":
            file=None
        
        else:
            f=open(file,'w')
            context=root.Textvar.get(1.0, END)
            f.write(context)
            f.close()

            root.tk.title(os.path.basename(file) + " - Notepad")
    else:
        # Save the file
        f = open(file, "w")
        f.write(root.Textvar.get(1.0, END))
        f.close()

The Save function is crucial—it ensures that users don’t lose their work. If the current document hasn’t been saved before (i.e., file is None), it prompts the user to choose a location and file name. If the document has been saved previously, it simply writes the current text to the existing file.

The Open Function: Bringing in Existing Documents

def Open():
    global file
    file = askopenfilename(defaultextension=".txt",
                           filetypes=[("Text Documents", "*.txt")])
    
    if file=="":
        file=None
    
    else:
        root.tk.title(os.path.basename(file) + " - Notepad")
        root.Textvar.delete(1.0,END)
        f=open(file,'r')
        context=f.read()
        root.Textvar.insert(1.0,context)
        f.close()

Opening a file is a breeze with the Open function. It uses a file dialog to let the user select a text document to edit. Once a file is chosen, its contents are loaded into the text area for editing.

The Quit Function: Exiting Gracefully

def Quit():
    root.Quit()

When it’s time to close the application, the Quit function is called. It ensures that the application exits cleanly, without leaving any processes hanging.

The About Function: Providing Information

def About():
    showinfo(title="Notepad",message="Notepad by Novfensec Inc.")

The About function offers a simple dialog box with information about the Notepad application, such as the developer’s name or the version of the app.

Bringing It All Together

These functions are tied together through the menu bar, providing a user-friendly interface for interacting with the Notepad application. Each menu item is connected to its respective function, creating a seamless experience for the user.

Menu Bar: Adding Interactivity

# Menubar
menubar=Menubars(root)

# filemenu starts
menubar.createMenu()
menubar.addCmd(label="New",command=New)
menubar.addCmd(label="Open",command=Open)
menubar.addCmd(label="Save",command=Save)
menubar.nav.add_separator()
menubar.addCmd(label="Exit",command=Quit)
menubar.addHead(label="File")

# helpmenu starts
menubar.createMenu()
menubar.addCmd(label="About Notepad",command=About)
menubar.addHead(label="Help")

menubar.view()

The menu bar is an essential part of any application. Here, we use TkModule’s Menubars class to create a menu bar and add commands like New, Open, Save, and Exit. The addCmd() method binds these commands to the functions we defined earlier, providing the user with the ability to interact with the application through the menu.

Text Area: The Heart of Notepad

Textfont=font.Font(family="Trebuchet-MS",size=18)
root.textarea(scroll=True,fill=BOTH,expand=True,border=5,relief=FLAT,font=Textfont)

The text area is where users will spend most of their time typing and editing text. We define a font and create a text area with scrolling enabled, filling the entire window. The textarea() method from TkModule makes this process simple, allowing us to specify various attributes like the font, border, and relief.

Runnig the application

root.Run()

Finally, root.Run() starts the main loop of the application, bringing our Notepad to life.


Conclusion

Through this line-by-line exploration, we’ve seen how TkModule facilitates the creation of a Notepad application. Each function and method provided by TkModule serves a specific purpose, from managing the main window to handling user interactions. The result is a clean, readable, and maintainable codebase that any developer would be proud of.

This blog post provides a comprehensive explanation of the Notepad application’s code, offering insights into the functionality of each part. By understanding the role of each line, developers can better appreciate the simplicity and power of TkModule in GUI programming.

Comments (0)


Please Login to Post a Comment.