Here is a little app to make a todo list. It’s a new version of this one. I decided to use a class to make the window and an external module for the functions that can make the app work. You can add items and delete them. When you close the app and you open it back you will have the item retrieved from a txt file saved by the app.
The code consist of a main file and another in a folder called todo_scripts.
The main file is this, where there is the window with its widgets
import tkinter as tk import os from todo_script.todo_functions import* class Window: def __init__(self): self.root = tk.Tk() # self.root.geometry("0x0+500+10") self.root.title("To do list in Python") self.root.configure(bg="green") self.widgets_builder() # Grab the saved data getdata(self) self.binding() self.root.mainloop() def widgets_builder(self): self.label1() self.entry1() self.listbox() self.label2() def label1(self): self.lab1 = tk.Label( self.root, text="Enter to add items, \nSelect to delete Items,\n ctr+s to save", bg="gold") self.lab1.pack(fill="both") def entry1(self): self.v = tk.StringVar() self.entry = tk.Entry(self.root, textvariable=self.v, font=24) self.entry.pack(fill="both") self.entry.focus() def listbox(self): self.lv = tk.Variable() self.lst = tk.Listbox(self.root, listvariable=self.lv) self.lst.pack(fill=tk.BOTH, expand=1) def label2(self): self.label = tk.Label(self.root, text="Press enter to add an item", bg="gold") self.label.pack(fill="both") def binding(self): self.lst.bind("<Double-Button>", lambda x: delete(x, self)) self.entry.bind("<Return>", lambda x: add(x, self)) self.root.bind("<Control-s>", lambda x: save(x, self)) # substitute the < with and angular parenthesis Window()
The file in the todo_script folder, called todo_functions.py is this, with the main functions to add, save, delete and retrieve the data made with the app
import os import tkinter as tk def add(event, self): "add item to listbox with entry when Return is pressed" self.lst.insert(tk.END, self.entry.get()) self.v.set("") save("", self) def delete(event, self): "deletes items in listbox with double click on item" self.lst.delete(tk.ANCHOR) save("", self) def save(event, self): "saves memos in listbox" with open("data.txt", "w") as file: file.write("\n".join(self.lv.get())) self.label["text"] = "Data saved" def getdata(self): "grab saved data" if "data.txt" in os.listdir(): with open("data.txt") as file: for line in file: self.lst.insert(tk.END, line.strip())
The program is not complicated, so the code could have been contained in just one file, but I think that it is a good role to follow to make things organized and simple, so that if you want to make a bigger app out of this starting point, you can easily figure out how it works, even after many days after you do not looked after this code.
Subscribe to the newsletter for updates
Tkinter templates
My youtube channel
Twitter: @pythonprogrammi - python_pygame