Python Tkinter To-do List














































Python Tkinter To-do List



To do list (Tkinter)

In this article, I'm going to discuss how a To-do list can be built from scratch using Tkinter a GUI library.

To use Tkinter, we need to import the library.


import tkinter as tk
from tkinter import ttk

Window Design

The app will need few Buttons, an Entry to enter the task and a Listbox widget.

Buttons

Add Task - On clicking this button a new task will be added to the Listbox widget

Delete - On clicking this button a selected task will be deleted.

Delete All - On clicking this button all the tasks will be deleted.

Exit - On clicking exits the applications

Listbox


The listbox is used here to display the tasks in the order they've been inserted.


lb = tk.Listbox(root, height= < num >, selectmode='SINGLE')

Here the 'selectmode' describes how many elements in the Listbox can be selected at once.


Entries


An entry in Tkinter is a text field which takes text as input.


entry1 = ttk.Entry(root)

Labels

Two labels are used here one denoting the title and other denoting the task entry.

label1 = ttk.Label(root, text = '< Name of the label >')

Geometry

All the widgets are arranged in the window using place geometry. For each widget a set of co-ordinates (x,y) must be given for where they must be placed.

This is achieved using the place() method.


widgetname.place(x = < num > , y = < num >)

This is the code of the design part:




After the design part is done, this is how the window is going to look like.


Functional part

Each button must be assigned with a callback function so that everytime a button is clicked, the corresponding function will be invoked.



Using database


To make the tasks available even after the application is closed, they must be stored in a database.

So, I've imported sqlite3 library and create a database and named it as todo.db. I created a table in the database with the name 'tasks'

The code for creating a database is here:

import sqlite3


Task list

The task list is a list used to keep track of all the tasks that are being added or deleted. It is initialized with no elements in it.

addTask()

On clicking the Add Task Button, this function will be invoked. It first reads the text in the Entry field and adds it to the list box and also the task list.

The definition of the addTask() function goes here:


The method e1.get() retrieves the text in the Entry field. If the length of the text is zero i.e., if no input is given the app would display a message box to enter task name.


 


 

If some task is entered then, it is appended to the task list and also inserted into the table using cur.execute() statement. Then another method listUpdate is called. After executing it, the text in the entry is removed.

listUpdate()

The listUpdate function is used to update the Listbox every time an entry is added to or deleted from the task list. It first invokes the clearList() function and it inserts all the elements present in the task list freshly into the Listbox.




clearList()

This function deletes all the entries present in the Listbox but not from the task list. All the entries which are not deleted are still present in the task list.


delOne()

This function deletes one task that is selected from the Listbox. If no entry is selected before clickingon the delete button, the application displays a message box informing to select an entry.


 

If an item is selected from the Listbox, then the function first removes the item from task list, then it deletes the task from database.





Here is the definition of the function:


 

deleteAll()

This method deletes all the items in the Listbox as well as in task list.



This function also prompts with a confirmation message.


 
Here is the definition of the function:



retrieveDB()

This method retrieves all the data present in the database at the time of starting the application. If any tasks are present in the database, they will be added to the Listbox.



The DB Browser can show all the entries present in the tasks table.


Here is the definition of the function:

 

Before closing the program the data in the database must be committed so that the data wont be lost and also the cursor must be closed.




 

The full code goes here:

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import sqlite3 as sq

root = tk.Tk()
root.title(
'To-Do List')
root.geometry(
"400x250+500+300")

conn = sq.connect(
'todo.db')
cur = conn.cursor()
cur.execute(
'create table if not exists tasks (title text)')

task = []
#------------------------------- Functions--------------------------------
def addTask():
word = e1.get()
if len(word)==0:
messagebox.showinfo(
'Empty Entry', 'Enter task name')
else:
task.append(word)
cur.execute(
'insert into tasks values (?)', (word,))
listUpdate()
e1.delete(
0,'end')

def listUpdate():
clearList()
for i in task:
t.insert(
'end', i)

def delOne():
try:
val = t.get(t.curselection())
if val in task:
task.remove(val)
listUpdate()
cur.execute(
'delete from tasks where title = ?', (val,))
except:
messagebox.showinfo(
'Cannot Delete', 'No Task Item Selected')

def deleteAll():
mb = messagebox.askyesno(
'Delete All','Are you sure?')
if mb==True:
while(len(task)!=0):
task.pop()
cur.execute(
'delete from tasks')
listUpdate()

def clearList():
t.delete(
0,'end')

def bye():
print(task)
root.destroy()

def retrieveDB():
while(len(task)!=0):
task.pop()
for row in cur.execute('select title from tasks'):
task.append(row[
0])

#------------------------------- Functions--------------------------------

l1 = ttk.Label(root, text =
'To-Do List')
l2 = ttk.Label(root, text=
'Enter task title: ')
e1 = ttk.Entry(root, width=
21)
t = tk.Listbox(root, height=
11, selectmode='SINGLE')
b1 = ttk.Button(root, text=
'Add task', width=20, command=addTask)
b2 = ttk.Button(root, text=
'Delete', width=20, command=delOne)
b3 = ttk.Button(root, text=
'Delete all', width=20, command=deleteAll)
b4 = ttk.Button(root, text=
'Exit', width=20, command=bye)

retrieveDB()
listUpdate()

#Place geometry
l2.place(x=
50, y=50)
e1.place(x=
50, y=80)
b1.place(x=
50, y=110)
b2.place(x=
50, y=140)
b3.place(x=
50, y=170)
b4.place(x=
50, y =200)
l1.place(x=
50, y=10)
t.place(x=
220, y = 50)
root.mainloop()

conn.commit()
cur.close()


I hope you liked my work. Please like, share to support me.


More Articles of Raaga Sree Charitha Pilaka:

Name Views Likes
Python datetime tzinfo 1014 1
Python Tkinter To-do List 5123 4
Python math Hyperbolic functions 605 0
Python math trigonometric functions 610 1
Python math Introduction 578 0
Edit your images using PIL 847 2
Python GUI Digital Clock 963 2
Python re Extract adverbs and their positions using finditer() 563 4
Python math pow(), exp(), log() 1262 1
Python re findall() 579 0
Python re Greedy vs Non-Greedy Matching 966 1
Python math perm() and comb() 1214 1
Python re sub() 596 2
QR Code Reader using Python 896 1
Python re finditer() 614 1
Python itertools accumulate() 703 0
Python Tetris game 2213 3
Python math floor() and ceil() 779 1
Python itertools cycle(), repeat() 586 1
Python math constants 649 0
Python itertools filterfalse() 628 1
Python itertools Introduction 582 1
Python re How to extract an e-mail address 606 3
GUI Dictionary App using JSON 62 6
Python datetime strftime(), now() 634 2
Python re match() 527 1
Python re split() 688 2
Python math prod() 607 0
Convert a batch of JPG files into PNGs 1834 1
Python re search() 557 1
Python math Inverse Hyperbolic functions 619 1
Python re Introduction 549 2
Python program to find the union of two sets 409 0
Python itertools chain() 1003 0
Python math factorial() 573 2
Python Track location with IP address 813 4
Python datetime date.today(), ctime() 625 0
Python re Extract a specific part of a string 608 1
Python program to print Pascal Triangle 473 0
GUI Dictionary App using JSON 1418 1
python itertools permutations(), combinations() 1140 0
Python program to find the interesection of two sets 398 0
Python re compile() 583 0
Python itertools product() 976 0
Python math Inverse Trigonometric functions 5406 0
Python args and kwargs 523 0
Python program to find difference of two sets 393 0
Python itertools compress() 728 1
Create a batch of files or folders easily 625 1
Python program to find symmetric difference of two sets 623 0
Generate QR Codes using qrcode 820 0
Convert Speech to text using Python 703 4
Python itertools count() 552 1
Python datetime timedelta() 747 0
Python datetime Introduction 561 0
Python math radians() and degrees() 547 0
Python math isnan(), isinf(), isqrt() 555 1

Comments