How to store multiple distinct Python Tkinter OptionMenu selections - python

Ive created a function that creates and packs some drop down menus. the only issue Im now facing is figuring out how to store the selection from all 6 menus into a list? im able to access the menus selection through the func() method, but im stuck as how to store all these? ideally id like to have all 6 selections stored in a list, is this possible?
def func(value):
x = value
print(value)
def GetEntry(x):
var = StringVar()
var.set('select one')
formatted = x.get().split()##gets the entry and forms a list
getMeal = CsvLoadSearch(u, formatted)
meal = OptionMenu(root, var, *getMeal, command = func ).pack()
mealOneButton = Button(root, text = "query database", command = lambda : GetEntry(mealOneString))
mealTwoButton = Button(root, text = "query database", command = lambda : GetEntry(mealTwoString))
mealThreeButton = Button(root, text = "query database", command = lambda : GetEntry(mealThreeString))
mealFourButton = Button(root, text = "query database", command = lambda : GetEntry(mealFourString))
mealFiveButton = Button(root, text = "query database", command = lambda : GetEntry(mealFiveString))
mealSixButton = Button(root, text = "query database", command = lambda : GetEntry(mealSixString))
this is the program bellow:
from tkinter import *
from tkinter import ttk
import csv
import os
u = "C:\\Users\\luke daniels\\Documents\\fooddata.csv"
"""
Loads csv and compares elements from foodList with current row.
returns a list of rows that match elements in foodList.
"""
def CsvLoadSearch(u, foodList):
results = []
inputfile = open(u)
for row in csv.reader(inputfile):
for food in foodList:
if food in row[0]:
results.append(row)
##print(row)
return results
##gets selection from drop down
def func(value):
x = value
def GetEntry(x):
var = StringVar()
var.set('select one')
formatted = x.get().split()##gets the entry and forms a list
getMeal = CsvLoadSearch(u, formatted)
meal = OptionMenu(root, var, *getMeal, command = func ).pack()
root = Tk()
root.title("MacroCalc")
caloriesAim = StringVar()
protien = StringVar()
fat = StringVar()
carbs = StringVar()
mealOneString = StringVar()
mealTwoString = StringVar()
mealThreeString = StringVar()
mealFourString = StringVar()
mealFiveString = StringVar()
mealSixString = StringVar()
mealOneKeyword = Entry(root, textvariable = mealOneString)
mealTwoKeyword = Entry(root, textvariable = mealTwoString)
mealThreeKeyword = Entry(root, textvariable = mealThreeString)
mealFourKeyword = Entry(root, textvariable = mealFourString)
mealFiveKeyword = Entry(root, textvariable = mealFiveString)
mealSixKeyword = Entry(root, textvariable = mealSixString)
mealLabel = Label(root,text = "meals")
mealLabel.config(font=("Courier", 30))
mealLabel.pack()
mealLone = Label(root,text = "meal one")
mealLtwo = Label(root,text = "meal two")
mealLthree = Label(root,text = "meal three")
mealLfour = Label(root,text = "meal four")
mealLfive = Label(root,text = "meal five")
mealLsix = Label(root,text = "meal six")
caloriesLabel = Label(root,text = "calories needed").pack()
calories = Text(root, height = 1, width = 10).pack()
protienLabel= Label(root,text = "protien ratio").pack()
protien = Text(root, height = 1, width = 4).pack()
carbsLabel = Label(root,text = "carbohydrate ratio").pack()
carbs = Text(root, height = 1, width = 4).pack()
fatsLabel = Label(root,text = "fats ratio").pack()
fats = Text(root, height = 1, width = 4).pack()
displayText = Text(root).pack(side = RIGHT)
mealOneButton = Button(root, text = "query database", command = lambda : GetEntry(mealOneString))
mealTwoButton = Button(root, text = "query database", command = lambda : GetEntry(mealTwoString))
mealThreeButton = Button(root, text = "query database", command = lambda : GetEntry(mealThreeString))
mealFourButton = Button(root, text = "query database", command = lambda : GetEntry(mealFourString))
mealFiveButton = Button(root, text = "query database", command = lambda : GetEntry(mealFiveString))
mealSixButton = Button(root, text = "query database", command = lambda : GetEntry(mealSixString))
mealButtons = [mealOneButton, mealTwoButton, mealThreeButton, mealFourButton, mealFiveButton, mealSixButton]
mealKeywords = [mealOneKeyword, mealTwoKeyword, mealThreeKeyword, mealFourKeyword, mealFiveKeyword, mealSixKeyword]
mealLabels = [mealLone, mealLtwo, mealLthree, mealLfour, mealLfive, mealLsix]
##packs the drop downs and respective lables
i = 0
while i < len(mealLabels):
mealLabels[i].pack()
mealKeywords[i].pack()
mealButtons[i].pack()
##meal.pack()
i = i + 1
root.mainloop()

Related

Label Not Continually Updating Tkinter

I have read through several answers to similar topics but none of them are relevant to my situation, I am trying to display a list on a label and whenever the button is pressed to update the list the label should update as well but it only updates when submitbtn_name is clicked. Any help appreciated I am very new to Tkinter.
My Code:
from tkinter import *
root = Tk()
root.title("Path Creator")
root.geometry('1680x1080')
root['background'] = '#aaaaaa'
list_of_paths_list = []
path_list = []
name = Entry(root, width=400)
name.insert(0, "Name")
name.pack()
def add_name():
path_list.append(name.get())
list_label = Label(root, text="path name:" + str(path_list))
list_label.pack()
submitbtn_name = Button(root, text="submit name", command=add_name)
submitbtn_name.pack()
value1 = Entry(root, width=400)
value1.insert(0, "value1")
value1.pack()
distance1 = Entry(root, width=400)
distance1.insert(0, "distance1")
distance1.pack()
def submitbtn_value_dist():
temp_list = []
temp_list.append(value1.get())
temp_list.append(distance1.get())
path_list.append(tuple(temp_list))
list_label = Label(root, text="current path: " + path_list)
list_label.pack()
submitbtn_pathpart = Button(root, text="submit path part", )
submitbtn_pathpart.pack()
root.mainloop()
Using f-string format. Added command in submitbtn_pathpart
Snippet:
def submitbtn_value_dist():
temp_list = []
temp_list.append(value1.get())
temp_list.append(distance1.get())
path_list.append(tuple(temp_list))
list_label = Label(root, text=f"current path:{path_list}")
list_label.pack()
submitbtn_pathpart = Button(root, text="submit path part", command=submitbtn_value_dist )
submitbtn_pathpart.pack()
root.mainloop()
Output for name:
Output for value and distance:

RE: TKinter Table Row Deletion (PYTHON)

(If anyone has seen my previous question, I found a way to save the row indexes and use them in the delete function :3)
Is there a way to stop/delete a running function/table on a button click? I am making a simple customer registration program which saves data from text fields (cID, custName, custEmail, and custBday) and deletes a selected row. My problem is that whenever I delete a row, the last row somehow leaves/lags behind creating this duplicate whenever a row is deleted. Any suggestions or is there something I've done wrong or I've missed?
My Code:
from tkinter import *
from tkinter import messagebox
import tkinter as tk
at = False
dotcom = False
list = [['ID', 'NAME', 'EMAIL', 'BIRTHDATE']]
recentIndex = []
ID = 1
storedIndex = 0
def callback(event):
custid.config(state=NORMAL)
custid.delete('1.0', END)
custid.insert(1.0, list[event.widget._values][0])
custid.config(state=DISABLED)
cName.set(list[event.widget._values][1])
cEmail.set(list[event.widget._values][2])
birthdate.set(list[event.widget._values][3])
indexPosition = event.widget._values
recentIndex.append(indexPosition)
print(recentIndex)
def createTable():
for i in range(len(list)):
for j in range(len(list[0])):
mgrid = tk.Entry(window, width = 10, bg= 'yellow')
mgrid.insert(tk.END, list[i][j])
mgrid._values= i
mgrid.grid (row = i + 5,column = j + 5)
mgrid.bind("<Button-1>", callback)
def delete():
try:
list.pop(recentIndex[-1])
if recentIndex[-1] > 0 or NONE:
msgbox("Data Delete", "Record")
createTable()
else:
msgbox("No Data Selected", "record")
return
except:
msgbox("No Data Selected", "record")
def save ():
custid.config(state= NORMAL)
initialValue = int(custid.get('1.0', END))
custid.delete('1.0', END)
list.append([ID, custName.get(), custEmail.get(), custBday.get()])
custid.insert(1.0, initialValue + 1)
custid.config(state=DISABLED)
createTable()
msgbox("Saved", "Record")
ID = ID + 1
def msgbox (msg, titlebar):
messagebox.showinfo(title = titlebar, message=msg)
def products():
window = Tk()
window.title("Products Form")
window.geometry("550x400")
window.configure(bg="orange")
window = Tk()
window.title("Sample Window")
window.geometry("550x400")
window.configure(bg="orange")
menubar = Menu(window)
filemenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Products", command=products)
filemenu.add_command(label="Orders")
filemenu.add_separator()
filemenu.add_command(label="Close", command = window.quit)
window.config(menu=menubar)
labelTitle = Label(window, text="Customer Registration System", width=30, height=1, bg="yellow", anchor= "center")
labelTitle.config(font=("Courier", 10))
labelTitle.grid(column=2, row=1)
labelID = Label(window, text="Customer ID", width = 20, height = 1, bg = "yellow")
labelID.grid(column=1, row=2)
cID = StringVar()
custid = Text(window, width=15, height=1)
custid.grid(column=2, row=2)
custid.insert(1.0, "1")
custid.config(state = DISABLED)
labelNameCheck = Label(window, text="Last Name, First Name", width = 20, height = 1, bg = "yellow")
labelNameCheck.grid(column=3, row=3)
labelName = Label(window, text="Customer Name", width = 20, height = 1, bg = "yellow")
labelName.grid(column=1, row=3)
cName = StringVar()
custName = Entry(window, textvariable = cName)
custName.grid(column=2, row=3)
labelEmail = Label(window, text="Customer Email", width = 20, height = 1, bg = "yellow")
labelEmail.grid(column=1, row=4)
cEmail = StringVar()
custEmail = Entry(window, textvariable = cEmail)
custEmail.grid(column=2, row=4)
custEmail.bind("<KeyRelease>", keyup)
labelEmail = Label(window, text="[a-z]#[a-z].com", width = 20, height = 1, bg = "yellow")
labelEmail.grid(column=3, row=4)
labelBday = Label(window, text="Customer Birthdate", width = 20, height = 1, bg = "yellow")
labelBday.grid(column=1, row=5)
birthdate= StringVar()
custBday = Entry(window, textvariable = birthdate)
custBday.grid(column=2, row=5)
custBday.bind("<KeyRelease>", keyupBdate)
birthdateCheck = Label(window, text="mm/dd/yyyy", width = 20, height = 1, bg = "yellow")
birthdateCheck.grid(column=3, row=5)
savebtn = Button(text = "Save", command = save)
savebtn.grid(column=1)
deletebtn = Button(text = "Delete", command = delete)
deletebtn.grid(column=1)
window.mainloop()
You need to delete current displayed records before showing updated records inside createTable(). Also better create a frame for showing the records, so that it is more easier to clear the displayed records:
def createTable():
# clear current displayed records
for w in tableFrame.winfo_children():
w.destroy()
# populate records
for i in range(len(list)):
for j in range(len(list[0])):
mgrid = tk.Entry(tableFrame, width = 10, bg= 'yellow') # use tableFrame as parent
mgrid.insert(tk.END, list[i][j])
mgrid._values= i
mgrid.grid (row = i,column = j)
mgrid.bind("<Button-1>", callback)
...
# frame for showing records
tableFrame = Frame(window)
tableFrame.grid(row=5, column=5)
...

How to load a url which is in entry widget of tkinter which is linked with saved user input of a list in list-box?

My Problem is described in these following steps:
1. Opened Application
2. Typed name = Mike ; id = 11 ; url = www.google.com
3. Clicked on "Add"
4. Closed the application.
5. Again Run the application.
6. Shows "Mike = 11" in the list box.
7. But when I select "Mike = 11" and click on "load" , it does not take me to "www.google.com", Why?
Please give me some solutions about how can I open a URL attaching with saved list.
Please HELP me!!
from tkinter import*
import webbrowser
def add():
name = entry1.get()
id = entry2.get()
listbox.insert(END, name+ " : " +id)
def delete():
select = listbox.curselection()
index = select[0]
listbox.delete(index)
def save():
with open("file.txt","w") as f:
for i in listbox.get(0,END):
f.write(i+"\n")
#f.close()
def load():
url = entry3.get()
select=listbox.curselection()
index=select[0]
webbrowser.open(index)
read = open("file.txt","r")
data_list = read.readlines()
read.close()
data_list = [data.rstrip() for data in data_list]
win = Tk()
win.title("Class")
frame1=Frame(win)
frame2=Frame(win)
frame1.pack()
frame2.pack()
label1 = Label(frame1,text="Name : ")
label1.grid(row=0,column=0)
label2 = Label(frame1,text="Id : ")
label2.grid(row=1,column=0)
label3 = Label(frame1,text="Url : ")
label3.grid(row=2,column=0)
name = StringVar()
entry1 = Entry(frame1,textvariable=name)
entry1.grid(row=0,column=1)
id = StringVar()
entry2 = Entry(frame1,textvariable=id)
entry2.grid(row=1,column=1)
url = StringVar()
entry3 = Entry(frame1,textvariable=url)
entry3.grid(row=2,column=1)
scrollbar = Scrollbar(frame2,orient=VERTICAL)
listbox = Listbox(frame2,selectmode=EXTENDED,yscrollcommand=scrollbar.set,width=60)
listbox.pack()
scrollbar.config(command=listbox)
for item in data_list:
listbox.insert(END,item)
button1 = Button(frame2,text="Add",command=add)
button1.pack()
button2 = Button(frame2,text="Delete",command=delete)
button2.pack()
button3 = Button(frame2,text="Save to File",command=save)
button3.pack()
button4 = Button(frame2,text="Load Url",command=load)
button4.pack()
win.mainloop()
You need to use two list.one list saves data in the file,this could be seen in the Listbox.The another list is to save the url in the file.this couldn't be seen.And also you need to synchronize them.(save(),delete(),add() need to operate both Listbox widget and the list).A minimal example.:
from tkinter import*
import webbrowser
def add():
name = entry1.get()
id = entry2.get()
url = entry3.get()
url_list.append(url)
listbox.insert(END, name+ " : " +id)
def delete():
select = listbox.curselection()
index = select[0]
url_list.pop(index)
listbox.delete(index)
def save():
with open("file.txt","w") as f:
for i,j in zip(listbox.get(0,END),url_list):
f.write(f"{i} Url:{j}\n")
def load():
select=listbox.curselection()
index=select[0]
load_url = url_list[index]
webbrowser.open(load_url)
read = open("file.txt","r")
data_url_list = read.readlines()
read.close()
data_list = [data.rstrip().split("Url")[0] for data in data_url_list]
url_list = [data.rstrip().split("Url:")[1] for data in data_url_list]
win = Tk()
win.title("Class")
frame1=Frame(win)
frame2=Frame(win)
frame1.pack()
frame2.pack()
label1 = Label(frame1,text="Name : ")
label1.grid(row=0,column=0)
label2 = Label(frame1,text="Id : ")
label2.grid(row=1,column=0)
label3 = Label(frame1,text="Url : ")
label3.grid(row=2,column=0)
name = StringVar()
entry1 = Entry(frame1,textvariable=name)
entry1.grid(row=0,column=1)
id = StringVar()
entry2 = Entry(frame1,textvariable=id)
entry2.grid(row=1,column=1)
url = StringVar()
entry3 = Entry(frame1,textvariable=url)
entry3.grid(row=2,column=1)
scrollbar = Scrollbar(frame2,orient=VERTICAL)
listbox = Listbox(frame2,selectmode=EXTENDED,yscrollcommand=scrollbar.set,width=60)
listbox.pack()
scrollbar.config(command=listbox)
for item in data_list:
listbox.insert(END,item)
button1 = Button(frame2,text="Add",command=add)
button1.pack()
button2 = Button(frame2,text="Delete",command=delete)
button2.pack()
button3 = Button(frame2,text="Save to File",command=save)
button3.pack()
button4 = Button(frame2,text="Load Url",command=load)
button4.pack()
win.mainloop()
In this example,the format in the file:
name : id Url:xxxxxx
You also could use another way to save them and read them.

Login page with tkinter and python for API to AWS cloud

My code for login page not working , when i am calling the function 'HTTP_Connection' from button "open' on main page.
It will make connection to F5 device, syntax working fine, when i am giving
input for a,b,c directly, from Tkinter i am trying to achieve .
from tkinter import *
root=Tk()
root.title("Automated Configuration Manager")
def HTTP_Connection():
a=et1.get()
b=et2.get()
c=et3.get()
urllib3.disable_warnings()
mgmt = ManagementRoot('a','b','c')
ltm = mgmt.tm.ltm
virtuals = mgmt.tm.ltm.virtuals
virtual = mgmt.tm.ltm.virtuals.virtual
mainframe = Frame(root)
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 100, padx = 100)
#choices = { 'F5','A5A','PA' }
var = StringVar()
popupMenu = OptionMenu(mainframe, var,'F5','A5A','PA')
Label(mainframe, text="Choose a Option").grid(row = 1, column = 1)
popupMenu.grid(row = 2, column =1)
l1 = Label(root, text = "Enter IP Address:")
l1.pack()
global et1
global et2
global et3
et1 = Entry(root, bd = 5)
et1.pack()
a=et1.get()
l2 = Label(root, text = "User Name:")
l2.pack()
et2 = Entry(root, bd=5)
et2.pack()
b=et2.get()
g=StringVar()
g="enter password:"
l3=Label(root, text = g)
l3.pack()
et3 = Entry(root, bd=5, show = "*")
et3.pack()
b = Button(root, text = "Open", bd =5,command=HTTP_Connection)
b.pack()
root.mainloop()
In this function:
def HTTP_Connection():
a=et1.get()
b=et2.get()
c=et3.get()
urllib3.disable_warnings()
mgmt = ManagementRoot('a','b','c')
ltm = mgmt.tm.ltm
virtuals = mgmt.tm.ltm.virtuals
virtual = mgmt.tm.ltm.virtuals.virtual
You are declaring three variables a, b and c which you then don't use. Instead you are running ManagementRoot('a','b','c') which uses strings containing the values "a", "b" and "c" instead of the variables you declared earlier.
You should be able to fix this by changing the line to the below:
mgmt = ManagementRoot(et1.get(),et2.get(),et3.get())

Python treeview and grid

The problem is that when some objects are being created in the double click subroutine the grid goes messed up. The tree view expands a bit to the right and labels and buttons which are suppose to go in column 1 look like they are in column 3(went off button above tree view which is in column 3). Also when I try making a button it puts it above the tree view no matter its row.
Code:
from tkinter import *
import os
import datetime
import sqlite3
from tkinter.ttk import Combobox,Treeview,Scrollbar
class Application(Frame):
""" Binary to Decimal """
def __init__(self, master):
""" Initialize the frame. """
super(Application, self).__init__(master)
self.grid()
self.create_GUI()
def Quit(self):
self.master.destroy()
def create_GUI(self):
self.title_lbl = Label(self, text = "Students")
self.title_lbl.grid(row = 0, column = 2)
self.fn_lbl = Label(self, text = "First Name:")
self.fn_lbl.grid(row = 1 , column = 1)
self.fn_txt = Entry(self)
self.fn_txt.grid(row = 1, column = 2)
self.ln_lbl =Label(self, text = "Last Name:")
self.ln_lbl.grid(row = 2, column = 1)
self.ln_txt = Entry(self)
self.ln_txt.grid(row = 2, column = 2)
self.q_btn = Button(self, text = "Back",padx=80,pady=10, command = lambda: self.Quit)
self.q_btn.grid(row = 3, column = 0)
self.s_btn = Button(self, text = "search",padx=80,pady=10, command = lambda: self.search())
self.s_btn.grid(row = 3,column = 3)
self.tree = Treeview(self.master,height = 6)
self.tree["columns"] = ("StudentID","First Name","Last Name")#,"House Number", "Street Name", "Town Or City Name","PostCode","MobilePhoneNumber")
self.tree.column("StudentID",width = 20)
self.tree.column("First Name",width = 40)
self.tree.column("Last Name", width = 40)
## self.tree.column("House Number", width = 60)
## self.tree.column("Street Name", width = 60)
## self.tree.column("Town Or City Name", width = 60)
## self.tree.column("PostCode", width = 60)
## self.tree.column("MobilePhoneNumber", width = 60)
self.tree.heading("StudentID",text="StudentID")
self.tree.heading("First Name",text="First Name")
self.tree.heading("Last Name",text="Last Name")
## self.tree.heading("House Number",text="House Number")
## self.tree.heading("Street Name",text="Street Name")
## self.tree.heading("Town Or City Name",text="Town Or City Name")
## self.tree.heading("PostCode",text="PostCode")
## self.tree.heading("MobilePhoneNumber",text="MobilePhoneNumber")
self.tree["show"] = "headings"
yscrollbar = Scrollbar(self.master, orient='vertical', command=self.tree.yview)
xscrollbar = Scrollbar(self.master, orient='horizontal', command=self.tree.xview)
self.tree.configure(yscroll=yscrollbar.set, xscroll=xscrollbar.set)
yscrollbar.grid(row=4, column=3, padx=2, pady=2, sticky=NS)
self.tree.grid(row=4,column=0,columnspan =5, padx=2,pady=2,sticky =NSEW)
self.tree.bind("<Double-1>",lambda event :self.OnDoubleClick(event))
def OnDoubleClick(self, event):
curItem = self.tree.focus()
contents =(self.tree.item(curItem))
StudentDetails = contents['values']
print(StudentDetails)
self.tStudentID=StringVar()
self.tFirstName = StringVar()
self.tLastName = StringVar()
self.tHouseNumber = StringVar()
self.tStreetName = StringVar()
self.tTownOrCityName = StringVar()
self.tPostCode = StringVar()
self.tEmail = StringVar()
self.tMobilePhoneNumber = StringVar()
self.tStudentID.set(StudentDetails[0])
self.tFirstName.set(StudentDetails[1])
self.tLastName.set(StudentDetails[2])
self.tHouseNumber.set(StudentDetails[3])
self.tStreetName.set(StudentDetails[4])
self.tTownOrCityName.set(StudentDetails[5])
self.tPostCode.set(StudentDetails[6])
self.tEmail.set(StudentDetails[7])
self.tMobilePhoneNumber.set(StudentDetails[8])
self.inst_lbl0 = Label(self.master, text = "Student ID").grid(row=5,column=0,sticky=W)
self.NStudentID = Label(self.master, textvariable=self.tStudentID).grid(row =5,column=1,stick=W)
self.inst_lbl1 = Label(self.master, text = "First Name").grid(row=6,column=0,sticky=W)
self.NFirstName = Entry(self.master, textvariable=self.tFirstName).grid(row =6,column=1,stick=W)
self.inst_lbl2 = Label(self.master, text = "Last Name").grid(row=7,column=0,sticky=W)
self.NLastName = Entry(self.master, textvariable=self.tLastName).grid(row =7,column=1,stick=W)
self.inst_lbl3 = Label(self.master, text = "House Number").grid(row=8,column=0,sticky=W)
self.HouseNumber = Entry(self.master,textvariable=self.tHouseNumber).grid(row=8,column=1,sticky=W)
self.inst_lbl4 = Label(self.master, text = "Street Name").grid(row=9,column=0,sticky=W)
self.StreetName =Entry(self.master,textvariable=self.tStreetName).grid(row=9,column=1,sticky=W)
self.inst_lbl5 = Label(self.master, text = "Town or City Name").grid(row=10,column=0,sticky=W)
self.TownOrCityName =Entry(self.master,textvariable=self.tTownOrCityName).grid(row=10,column=1,sticky=W)
self.inst_lbl6 = Label(self.master, text = "Postcode").grid(row=11,column=0,sticky=W)
self.PostCode = Entry(self.master,textvariable=self.tPostCode).grid(row=11,column=1,sticky=W)
self.inst_lbl7 = Label(self.master, text = "Email").grid(row=12,column=0,sticky=W)
self.Email =Entry(self.master,textvariable=self.tEmail).grid(row=12,column=1,sticky=W)
self.inst_lbl8 = Label(self.master, text = "Mobile phonenumber").grid(row=13,column=0,sticky=W)
self.MobilePhoneNumber =Entry(self.master,textvariable=self.tMobilePhoneNumber).grid(row=13,column=1,sticky=W)
self.btnSaveChanges = Button(self, text = "save changes",padx=80,pady=10,command = lambda:self.SaveChanges).grid(row=14,column=0,sticky=W)
#self.btnSaveChanges = Button(self, text = "delete record",padx=80,pady=10,command = lambda:self.DeleteRecord).grid(row=14,column=1,sticky=W)
def search(self):
FirstName = self.fn_txt.get()
LastName = self.ln_txt.get()
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
cursor.row_factory = sqlite3.Row
sql = "select StudentID,FirstName,LastName,HouseNumber,StreetName,TownOrCityName,PostCode,Email,MobilePhoneNumber"\
" from tblStudents"\
" where FirstName like ?"\
" and LastName like ?"
cursor.execute(sql,("%"+FirstName+"%","%"+LastName+"%",))
StudentList = cursor.fetchall()
print(StudentList)
self.loadStudents(StudentList)
def loadStudents(self,StudentList):
for i in self.tree.get_children():
self.tree.delete(i)
for student in StudentList:
self.tree.insert("" , 0,values=(student[0],student[1],student[2],student[3],student[4],student[5],student[6],student[7],student[8]))
def SaveChanges(self):
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
sql = "update tblStudents set FirstName =?,LastName=?,HouseNumber=?,StreetName=?,TownOrCityName=?,PostCode=?,Email=?,MobilePhoneNumber=? where StudentID=?"
cursor.execute(sql,("%"+NFirstName+"%","%"+NLastName+"%","%"+NHouseNumber+"%","%"+NStreetName+"%","%"+NTownOrCityName+"%","%"+NPostCode+"%","%"+NEmail+"%","%"+NMobilePhoneNumber+"%"))
db.commit()
def DeleteRecord(self):
print("")
root = Tk()
root.title("booking system")
root.geometry("800x800")
root.configure(bg="white")
app = Application(root)
root.mainloop()
The mistake you are making is that you're trying to put everything into one massive grid, but the code to populate that grid is scattered throughout your program. Your UI clearly has three distinct sections, you should organize your GUI that way.
Create a frame for the top, a frame for the treeview, and a frame for the bottom section. You can use pack to place these in the master window, one on top of the other. Then, place your other widgets in the appropriate frame. This way, changes you make in one section (adding or removing columns or rows, switching to pack, etc) won't affect the other areas.

Categories

Resources