update Flaw in My python tkinter sqlite application

荒凉一梦 提交于 2021-02-11 12:50:22

问题


i a beginner and i am trying to make a blood sugar tracking application using python Tkinter and Sqlite, so the problem is that after "selecting" a row from treeview widget and "updating" its values the Blue highlight no longer exists but the data is stored and if the "UPDATE" button/function is clicked again even without selecting a row from treeview the values on the previously selected row get updated.


import numpy as np
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
import datetime
from db import Database

db = Database('sugar.db')

main = Tk()

main.title('Blood Sugar Tracker')
width_of_main = 840
height_of_main = 420
main.resizable(width=True, height =False)
screen_width = main.winfo_screenwidth()
screen_height = main.winfo_screenheight()
x_co = (screen_width/2)-(width_of_main/2)
y_co = (screen_height/2) - (height_of_main/2)
main.geometry( "%dx%d+%d+%d" % (width_of_main, height_of_main , x_co,y_co))

####fuctions###
def populate_list():
    table_list.delete(*table_list.get_children())
    for row in db.fetch():
        table_list.insert("","end", values = row)

def add_entry():

    try:
        comment = comment_entry.get("1.0","end-1c")
        if fbs.get()=='' and ppbs.get()=='' and insulin.get()=='' and comment=="":
            messagebox.showerror('Required Fields', 'Please entry atleast'"\n"'ONE'"\n"'entry field')
        else:
                db.insert(date,fbs.get(), ppbs.get(),insulin.get(),comment)
                table_list.delete(*table_list.get_children())
                table_list.insert("", "end",(date,fbs.get(), ppbs.get(),insulin.get(),comment))
                clear_fields()
                populate_list()
    except ValueError:
        messagebox.showerror('Entry field error','Enter ONLY Numerals in '"\n"'Fasting/Before food Blood sugar level'"\n"'After Food sugar levels'"\n"'Insulin Units')


def update_entry():
    try:
        comment = comment_entry.get("1.0","end-1c")
        if fbs.get()=='' and ppbs.get()=='' and insulin.get()=='' and comment=="":
            messagebox.showerror('Required Fields', 'Please entry atleast'"\n"'ONE'"\n"'entry field')
        else:
            db.update(selected[0],fbs.get(), ppbs.get(),insulin.get(),comment)
            clear_fields()
            populate_list()
    except ValueError:
        messagebox.showerror('Entry field error','Enter ONLY Numerals in '"\n"'Fasting/Before food Blood sugar level'"\n"'After Food sugar levels'"\n"'Insulin Units')
    except NameError:
        pass

        
def selection(event):
    try:
        global selected
        index = table_list.focus()
        selected = (table_list.item(index)).get("values")
        fbs_entry.delete(0,END)
        fbs_entry.insert(END, selected[2])
        ppbs_entry.delete(0,END)
        ppbs_entry.insert(END, selected[3])
        insulin_entry.delete(0,END)
        insulin_entry.insert(END, selected[4])
        comment_entry.delete('1.0',END)
        comment_entry.insert(END, selected[5])
    except IndexError:
        pass


def remove_entry():
    try:
        db.remove(selected[0])
        clear_fields()
        populate_list()
    except:
        pass

    

def clear_fields():
    fbs_entry.delete(0,END)
    ppbs_entry.delete(0,END)
    insulin_entry.delete(0,END)
    comment_entry.delete('1.0',END) 








####blood gloucose levels####
###frames###
frame_top = LabelFrame(main,)
frame_top.grid(row =0, column = 0, columnspan = 4, padx=10, pady = 6)
frame_bottom = LabelFrame(main,)
frame_bottom.grid(row=2,column=0, columnspan =6, padx=10, pady = 12)


###fbs###
fbs = StringVar()
fbs_label= Label(frame_top, text = 'Fasting/Before food'"\n"'Blood Sugar levels')
fbs_label.grid(row =0,column=0)
fbs_entry = Entry(frame_top,textvariable=fbs, width=16,)
fbs_entry.grid(row=0,column=1, padx=10)

###insulin ###
insulin = StringVar()
insulin_label = Label(frame_top, text = 'Insulin Units')
insulin_label.grid(row=0,column = 2)
insulin_entry =Entry(frame_top,textvariable = insulin, width = 16)
insulin_entry.grid(row=0,column=3, padx = 10)

###ppbs###
ppbs =StringVar()
ppbs_label=Label(frame_top,text ='2hrs After food'"\n"'Blood sugar levels')
ppbs_label.grid(row=0,column=4)
ppbs_entry=Entry(frame_top,textvariable = ppbs,width=16)
ppbs_entry.grid(row =0,column=5,padx=10)

####buttons###
add_btn=Button(main, text = 'Add Entry', width=25, command = add_entry )
add_btn.grid(row=1, column=2)

update_btn=Button(main, text = 'Update Entry', width=11,command = update_entry)
update_btn.grid(row=1, column=1 )

remove_btn=Button(main, text = 'Remove Entry', width=12,command = remove_entry )
remove_btn.grid(row=1, column=0 )

clear_btn=Button(main, text = 'Clear fields', width=10,command = clear_fields )
clear_btn.grid(row=1, column=3,sticky = W, padx=(80,0))


####comment###
comment_label = Label(frame_bottom, text = 'Comments\Remarks:')
comment_label.grid(row = 1,column = 2,sticky=W,padx = (15,0))
comment_entry = Text(frame_bottom, width =30, height=12)
comment_entry.grid(row=2,column =2,sticky=W+S,padx = (15,0)) 

###table###
records_table = Label(frame_bottom, text='Records Table')
records_table.grid(row=1,column =0,)
table_list = ttk.Treeview(frame_bottom, columns =( 'id','date','fbs','ppbs','insulin','comment'), show = 'headings', height = 11)
table_list.heading("#1", text = "SL.no")
table_list.column("#1", width =50)
table_list.heading("#2",  text = "Date")
table_list.column("#2", width= 120)
table_list.heading("#3",  text = "FBS")
table_list.column("#3", width= 60)
table_list.heading("#4",  text = "PPBS")
table_list.column("#4", width= 60)
table_list.heading("#5",  text = "Insulin")
table_list.column("#5", width= 60)
table_list.heading("#6",  text = "Comment")
table_list.column("#6", width= 100)
table_list.grid(row=2, column =0,  rowspan=1,sticky= W, pady= (10,0), padx=(20,0))

##bind selection##

table_list.bind('<ButtonRelease-1>', selection)

###created###
date = str(datetime.datetime.today().strftime("%y-%m-%d, %H:%M"))

###scorllbar###
scrollbar =Scrollbar(frame_bottom)
scrollbar.grid(row=2,column=1, rowspan = 1, sticky=N+S)

###set scrollbar to tabel###
table_list.configure(yscrollcommand=scrollbar.set)
scrollbar.configure(command = table_list.yview)


populate_list()
main.mainloop()

this is the main Tkinter python file. and the below one is Sqlite file.

import sqlite3 

class Database:
    def __init__(self,db):
        self.conn=sqlite3.connect(db)
        self.cur=self.conn.cursor()
        self.cur.execute('''CREATE TABLE IF NOT EXISTS sugarvalue (id 
                         INTEGER PRIMARY KEY,date text,fbs real,ppbs real,insulin real,
                         comment text)''')
        self.conn.commit()
        
        
    def fetch(self):
        self.cur.execute("SELECT * FROM sugarvalue")
        rows=self.cur.fetchall()
        return rows


    def insert(self,date,fbs,ppbs,insulin,comment):
        self.cur.execute("INSERT INTO sugarvalue VALUES(NULL,:date,:fbs,:ppbs,:insulin,:comment)",
                            {'date':date,'fbs':fbs,'ppbs':ppbs,'insulin':insulin, 'comment':comment})
        self.conn.commit()
    
    
    def remove(self,id):
        self.cur.execute("DELETE FROM sugarvalue WHERE id=?",(id,))
        self.conn.commit()
        
    
    def update(self,id,fbs,ppbs,insulin,comment):
        self.cur.execute('''UPDATE sugarvalue SET fbs=:fbs, ppbs=:ppbs, insulin=:insulin,comment=:comment WHERE id=:id''',
                         {'fbs':fbs,'ppbs':ppbs,'insulin':insulin,'comment':comment ,'id':id})
        self.conn.commit()
        
    
    def __del__(self):
        self.conn.close()

to show you the problem i have uploaded a video on youtube showing this. https://youtu.be/2-hgG6gX364 this app still is under construction. and thank you for your time

来源:https://stackoverflow.com/questions/64060874/update-flaw-in-my-python-tkinter-sqlite-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!