Reputation: 11
I should be able to use a loop to do the below instead of writing out more widgets than I'll ever need and shorten my code.This is the way I'm doing it now:
db = sqlite3.connect('/path/to/database')
cursor = db.cursor()
cursor.execute("SELECT Drug FROM database where current >= 1")
allrec = cursor.fetchall()
numrec = len(allrec)
cursor.execute("SELECT Drug FROM database where current >= 1")
results = cursor.fetchone()
if numrec == 0:
exit
else:
c1=Checkbutton(frame1,variable=var1)
c1.grid(row=0,column=0,sticky='nw')
c1.config(bg='black')
e1=Entry(frame1, bg="black", fg="white")
e1.grid(row=0, column=1, sticky=NW)
e1.delete(0, END)
for row in results:
e1.insert(END, *results)
results = cursor.fetchone()
if numrec <= 1:
quit
else:
c2=Checkbutton(frame1,variable=var2)
c2.grid(row=1,column=0,sticky='nw')
c2.config(bg='black')
e2=Entry(frame1, bg="black", fg="white")
e2.grid(row=1, column=1, sticky=NW)
e2.delete(0, END)
for row in results:
e2.insert(END, *results)
record 3 ........
record 4 ........
.......
.......
record 15 .......
This creates 15 check boxes and entry boxes with different names so I can insert records from my database.
Upvotes: 1
Views: 1205
Reputation: 76194
Instead of having fifteen variables named c1
, c2
... c15
, create a single list which will hold all of your checkbuttons. Do the same for your entries and vars.
checkbuttons = []
entries = []
vars = []
for i in range(numrec):
results = cursor.fetchone()
var = IntVar()
check_button=Checkbutton(frame1,variable=var)
check_button.grid(row=i,column=0,sticky='nw')
check_button.config(bg='black')
entry=Entry(frame1, bg="black", fg="white")
entry.grid(row=i, column=1, sticky=NW)
entry.delete(0, END)
for row in results:
entry.insert(END, *results)
checkbuttons.append(check_button)
entries.append(entry)
vars.append(var)
Now instead of getting e.g. the sixth entry with e6
, you get it with entries[5]
.
Upvotes: 4