my_conn we will use in our script.
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
try: # connection to database
my_path="D:\\testing\\sqlite\\my_db.db" #Change the path
my_conn = create_engine("sqlite:///" + my_path)
### for MySQL database , use the below line and remove the above line
#my_conn =create_engine("mysql+mysqldb://root:pw@localhost/my_tutorial")
except SQLAlchemyError as e:
error = str(e.__dict__['orig'])
print(error)
def my_upd(k):
if(my_ref[k][1].get()==True):
my_ref[k][0].config(font=f_done,fg='green')
q='UPDATE my_tasks SET status=True WHERE id='+str(k)
else:
my_ref[k][0].config(font=f_normal,fg='blue')
q='UPDATE my_tasks SET status=False WHERE id='+str(k)
r_set=my_conn.execute(q)
msg="No. Updated:"+str(r_set.rowcount) # Number of rows updated
my_msg(msg) # show message for 3 seconds
for w in task_frame.grid_slaves(): #Loop through each row
w.grid_forget() # remove the row
We will read the tasks and the status of the task from the my_tasks table to display. In our table my_tasks, we have three columns, id, tasks and status. We will create one dictionary by using id as Key with tasks, status list as values.
q='SELECT * FROM my_tasks '
my_cursor=my_conn.execute(q)
r_set=my_cursor.fetchall()
my_dict = {i[0]: [i[1],i[2]] for i in r_set}# create dictionary
Based on the value of status column ( True or False ) we will apply the option font to each checkbutton. my_ref={} # to store references to checkboxes
def my_show():
for w in task_frame.grid_slaves(): #Loop through each row
w.grid_forget() # remove the row
q='SELECT * FROM my_tasks '
my_cursor=my_conn.execute(q)
r_set=my_cursor.fetchall()
my_dict = {i[0]: [i[1],i[2]] for i in r_set}
i=1 # row number
for k in my_dict.keys(): # Number of checkbuttons
var=tk.BooleanVar() # variable
var.set(my_dict[k][1]) # set to value of status column
if my_dict[k][1]==True: # set font based on status column
font,fg=f_done,'green' # if True
else:
font,fg=f_normal,'blue'
ck = tk.Checkbutton(task_frame, text=my_dict[k][0],
variable=var,onvalue=True,offvalue=False,font=font,fg=fg,
command=lambda k=k: my_upd(k))
ck.grid(row=i,column=0,padx=20,pady=1,sticky='w')
my_ref[k]=[ck,var] # to hold the references
i=i+1 # increase the row number
b1=tk.Button(my_w,text='+',font=18,command=lambda:add_task())
b1.grid(row=0,column=2)
Inside the function add_task() we will first read the data entered by user in the Entry box e1 by using get() method.def add_task():
my_data=(e1.get(),False) # data to pass using query
#r_set=my_conn.execute("INSERT INTO my_tasks (tasks, status) \
# VALUES(?,?)",my_data)
### for MySQL use the below line and remove the above line
r_set=my_conn.execute("INSERT INTO my_tasks (tasks, status) \
VALUES(%s,%s)",my_data)
msg="Task ID:"+str(r_set.lastrowid)
e1.delete(0,'end') # remove the task from entry box
my_msg(msg) # show message for 3 seconds
my_show() # refresh the view
def delete_task(): # remove all completed tasks
r_set=my_conn.execute("DELETE FROM my_tasks WHERE status=True")
msg="No Deleted:"+str(r_set.rowcount) # Number of rows deleted
my_msg(msg) # show message for 3 seconds
my_show() # refresh the view
def my_msg(msg):
l2.config(text=msg) # show message
my_w.after(3000,lambda:l2.config(text='')) # remove after 3 seconds
Full code is here ( Change the path to your database or connection string.
CREATE TABLE IF NOT EXISTS `my_tasks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tasks` text,
`status` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `my_tasks`
--
INSERT INTO `my_tasks` (`id`, `tasks`, `status`) VALUES
(1, 'My tasks 1 ', 1),
(2, 'My tasks 2', 0),
(3, 'My tasks 3', 1);
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.