Make Notepad using Tkinter

| | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

Python 3 and Tkinter must already be installed on your system to create this notebook. You can download the appropriate Python package according to your system requirements. After you have successfully installed Python, you need to install Tkinter (a GUI package for Python).

Use this command to install Tkinter:

 pip install python-tk 

Tkinter imports:

import tkinter

import os

from tkinter import *


# To get a place above for a post

from tkinter.messagebox import *


# To open the dialog used as needed

from tkinter.filedialog import *

Note. Message Box is used to write a message in a white box named Notepad, and Dialog File is used to display / em> dialog box when you open a file from anywhere on your system or save a file to a specific position or location.

Add a menu:

# Add controls (widget)

self .__ thisTextArea.grid (sticky = N + E + S + W)


# Open new file

self .__ thisFileMenu.add_command (label = "New" ,

command = self .__ newFile)


# To open an existing file

self .__ thisFileMenu.add_command (label = " Open " ,

command = self .__ openFile)


# Save current file

self .__ thisFileMenu.add_command (label = "Save" ,

command = self .__ saveFile)


# Create a line in the dialog

self .__ thisFileMenu.add_separator ()


# To stop

self .__ thisFileMenu.add_command (label = "Exit" ,

command = self .__ quitApplication)

self .__ thisMenuBar.add_cascade ( label = "File" ,

menu = self .__ thisFileMenu)


# To add a stroke

self .__ thisEditMenu.add_command (label = "Cut" ,

command = self .__ cut)


# To give a copy function

self .__ thisEditMenu.add_command (label = "Copy" ,

command = self .__ copy )


# To add an insert function

self .__ thisEditMenu.add_command (label = "Paste" ,

command = self .__ paste)


# To enable editing

self .__ thisMenuBar.add_cascade (label = " Edit " ,

menu = self .__ thisEditMenu)


# To create a notepad description function

self .__ thisHelpMenu.add_command (label = " About Notepad " ,

command = self .__ showAbout )

self .__ thisMenuBar.add_cascade (label = "Help" ,

menu = self .__ thisHelpMenu)

self .__ root.config (menu = self .__ thisMenuBar)

self .__ thisScrollBar.pack (side = RIGHT, fill = Y)


# The scroll bar will be adjusted automatically
# according to the content

self .__ thisScrollBar.config (command = self .__ thisTextArea .yview)

self .__ thisTextArea.config (yscrollcommand = self .__ thisScrollBar. set )

With this code we will add menus to our notepad windows and add things like copy, paste, save, etc.

Add functionality:

def __ quitApplication ( self ):

self .__ root.destroy ()

# exit ()

def __ showAbout ( self ):

showinfo ( "Notepad" , "Mrinal Verma" )

def __ openFile ( self ):

self .__ file = askopenfilename (defaultextension = ". txt" ,

filetypes = [( "All Files " , " *. * " ),

( "Text Documents" , "*. txt" )])

if self .__ f ile = = "":

# no file to open

self .__ file = None

else :

# try opening the file

# set the window title

self .__ root.title (os.path.basename ( self .__ file) + " - No tepad " )

self .__ thisTextArea.delete ( 1.0 , END)

file = open ( self .__ file, "r" )

self .__ thisTextArea.insert ( 1.0 , file . read ())

file . close ()

def __ newFile ( self ):

self .__ root.title ( " Untitled - Notepad " )

self .__ file = None

self .__ thisTextArea.delete ( 1.0 , END)

def __ saveFile ( self ):

if self .__ file = = None :

# save as new file

self .__ file = asksaveasfilename (initialfile = ’ Untitled.txt’ ,

defaultextension = ". txt" ,

f iletypes = [( "All Files" , "*. *" ),

( "Text Documents" , "*. txt" )])

if self .__ file = = "":

self .__ file = None

else :

# try to save the file

file = open ( self .__ file, "w" )

file . write ( self .__ thisTextArea.get ( 1.0 , END))

file . close ()

# change the title of the window

self .__ root.title (os.path.basename ( self .__ file) + "- Notepad" )

else :

file = open ( self .__file, "w" )

file . write ( self .__ thisTextArea.get ( 1.0 , END))

file . close ()

def __ cut ( self ):

self .__ thisTextArea.event_generate ( "& lt; & lt; Cut & gt; & gt;" )

def __ copy ( self ):

self .__ thisTextArea.event_generate ( "& lt; & lt; Copy & gt; & gt;" )

def __ paste ( self ):

self .__ thisTextArea.event_generate ( "& lt; & lt; Paste & gt; & gt;" )

This we have added all the features that are required in notepad, you can also add other features like font size, font color, bold, underline, etc.

Main code after combining all:

import tkinter

import os

from tkinter import *

from tkinter.messagebox import *

from tkinter.filedialog import *

class Notepad:

__ root = Tk ()

# default window width and height

__ thisWidth = 300

__ thisHeight = 300

__ thisTextArea = Text (__root)

__ thisMenuBar = Menu (__ root)

__ thisFileMenu = Menu (__ thisMenuBar, tearoff = 0 )

__ thisEditMenu = Menu (__ thisMenuBar, tearoff = 0 )

__ thisHelpMenu = Menu (__ thisMenuBar, tearoff = 0 )

# Add scrollbar

__ thisScrollBar = Scrollbar (__ thisTextArea)

__ file = None

def __ init __ ( self , * * kwargs ):

# Set icon

try :

self .__ root .wm_iconbitmap ( "Notepad.ico" )

except :

pass

# Set window size (default 300x300)

try :

self .__ thisWidth = kwargs [ ’ width’ ]

except KeyError:

pass

try :

self .__ thisHeight = kwargs [ ’height’ ]

except KeyError:

pass

# Set window text

self .__ root.title ( "Untitled - Notepad" )

# Center the window

screenWidth = self .__ root.winfo_screenwidth ()

screenHeight = self .__ root .winfo_screenheight ()

# For the left

left = (screenWidth / 2 ) - ( self .__ thisWidth / 2 )

# Right-ally

top = (screenHeight / 2 ) - ( self . __thisHeight / 2 )

# For top and bottom

self .__ root.geometry ( ’% dx% d +% d +% d’ % ( self .__ thisWidth,

self .__ thisHeight,

left, top))

# To make the text area automatically resize

/ code> pass

# Set window text

self .__ root.title ( "Untitled - Notepad" )

# Center window

screenWidth = self .__ root.winfo_screenwidth ()

screenHeight = self .__ root.winfo_screenheight ()

# For the left

left = (screenWidth / 2 ) 👻 Read also: what is the best laptop for engineering students?

Make Notepad using Tkinter __del__: Questions

How can I make a time delay in Python?

5 answers

I would like to know how to put a time delay in a Python script.

2973

Answer #1

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

2973

Answer #2

You can use the sleep() function in the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1) # Time in seconds

Make Notepad using Tkinter __del__: Questions

How to delete a file or folder in Python?

5 answers

How do I delete a file or folder in Python?

2639

Answer #1


Path objects from the Python 3.4+ pathlib module also expose these instance methods:

2639

Answer #2


Path objects from the Python 3.4+ pathlib module also expose these instance methods:

2639

Answer #3

Python syntax to delete a file

import os
os.remove("/tmp/<file_name>.txt")

Or

import os
os.unlink("/tmp/<file_name>.txt")

Or

pathlib Library for Python version >= 3.4

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()

Path.unlink(missing_ok=False)

Unlink method used to remove the file or the symbolik link.

If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.

Best practice

  1. First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :
    a. os.path.isfile("/path/to/file")
    b. Use exception handling.

EXAMPLE for os.path.isfile

#!/usr/bin/python
import os
myfile="/tmp/foo.txt"

## If file exists, delete it ##
if os.path.isfile(myfile):
    os.remove(myfile)
else:    ## Show an error ##
    print("Error: %s file not found" % myfile)

Exception Handling

#!/usr/bin/python
import os

## Get input ##
myfile= raw_input("Enter file name to delete: ")

## Try to delete the file ##
try:
    os.remove(myfile)
except OSError as e:  ## if failed, report it back to the user ##
    print ("Error: %s - %s." % (e.filename, e.strerror))

RESPECTIVE OUTPUT

Enter file name to delete : demo.txt
Error: demo.txt - No such file or directory.

Enter file name to delete : rrr.txt
Error: rrr.txt - Operation not permitted.

Enter file name to delete : foo.txt

Python syntax to delete a folder

shutil.rmtree()

Example for shutil.rmtree()

#!/usr/bin/python
import os
import sys
import shutil

# Get directory name
mydir= raw_input("Enter directory name: ")

## Try to remove tree; if failed show an error using try...except on screen
try:
    shutil.rmtree(mydir)
except OSError as e:
    print ("Error: %s - %s." % (e.filename, e.strerror))

Is there a simple way to delete a list element by value?

5 answers

I want to remove a value from a list if it exists in the list (which it may not).

a = [1, 2, 3, 4]
b = a.index(6)

del a[b]
print(a)

The above case (in which it does not exist) shows the following error:

Traceback (most recent call last):
  File "D:zjm_codea.py", line 6, in <module>
    b = a.index(6)
ValueError: list.index(x): x not in list

So I have to do this:

a = [1, 2, 3, 4]

try:
    b = a.index(6)
    del a[b]
except:
    pass

print(a)

But is there not a simpler way to do this?

1055

Answer #1

To remove an element"s first occurrence in a list, simply use list.remove:

>>> a = ["a", "b", "c", "d"]
>>> a.remove("b")
>>> print(a)
["a", "c", "d"]

Mind that it does not remove all occurrences of your element. Use a list comprehension for that.

>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
>>> a = [x for x in a if x != 20]
>>> print(a)
[10, 30, 40, 30, 40, 70]

We hope this article has helped you to resolve the problem. Apart from Make Notepad using Tkinter, check other __del__-related topics.

Want to excel in Python? See our review of the best Python online courses 2022. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Julia Krasiko

Berlin | 2022-12-08

log is always a bit confusing 😭 Make Notepad using Tkinter is not the only problem I encountered. I just hope that will not emerge anymore

Anna Wu

Prague | 2022-12-08

Thanks for explaining! I was stuck with Make Notepad using Tkinter for some hours, finally got it done 🤗. I just hope that will not emerge anymore

Jan OConnell

Munchen | 2022-12-08

__del__ is always a bit confusing 😭 Make Notepad using Tkinter is not the only problem I encountered. I just hope that will not emerge anymore

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically