I'm making a program with a GUI using Tkinter.
The program receives a CSV file. And then has functions Add Delete Update
I'm done with the add part, but I could also finish the delete part, but somehow I just want to try out deleting via column. For example, entry is:
2012-1221, Name Lastname,
I want to delete all this entry just by the ID Number 2012-1221
I can't just do it. Here's my code:
from Tkinter import *
import sys
import sys
import os
import operator
import datetime
import csv
import fileinput
root = Tk()
root.title("SCS Club/Guilds/Committee System")
root.grid()
root.geometry("400x450")
root.resizable(width=False, height=False)
files = StringVar()
label = Label(root, text="Clearance and Management", bg="white", fg="black")
label.pack(fill=X)
label1 = Label(root, text="Student Record", bg = "lightgreen", font = "chiller 20 bold").pack()
label2 = Label(root, text ="Enter file name:").pack()
fileName = Entry(root, textvariable=files, relief=GROOVE, bg="lightgreen").pack()
def fileOpen():
def newWindow():
def addData():
idGet = str(idno.get())
nameGet = str(nme.get())
courseGet = str(crse.get())
yearGet = str(yr.get())
fileNameGet = str(files.get())
with open(fileNameGet, 'ab') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar = '|')
completeFields = idGet + ',' + nameGet +','+ courseGet +','+ yearGet
writer.writerow([completeFields])
addEntry.delete(0,"end")
idEntry.delete(0,"end")
crseEntry.delete(0,"end")
newWin = Toplevel()
newWin.geometry("400x200")
newWin.resizable(width=False,height=False)
newWin.title("Add Student")
addId = Label(newWin, text="ID Number").grid(row=1, column=0)
idno = StringVar(None)
idEntry = Entry(newWin, textvariable=idno,bg="lightgreen")
idEntry.grid(row=1, column=1)
addNme = Label(newWin, text="Name").grid(row=2, column=0)
nme = StringVar(None)
addEntry = Entry(newWin, textvariable=nme, text="Name")
addEntry.grid(row=2, column=1)
addCrse = Label(newWin, text="course").grid(row=3, column=0)
crse = StringVar(None)
crseEntry = Entry(newWin, textvariable=crse, text="Course")
crseEntry.grid(row=3, column=1)
addYr = Label(newWin, text="Year").grid(row=4, column=0)
yr = StringVar(None)
yrEntry = Entry(newWin, textvariable=yr, text="Year")
yrEntry.grid(row=4, column=1)
addFinal = Button(newWin, text="ADD", command=addData, relief=GROOVE).grid(row=5, column=1)
def deleteWindow():
def deleteData():
getID = str(idno.get())
fileName = str(files.get())
f = open(fileName,"r")
lines = f.readlines()
f.close()
f = open(fileName,"w")
for line in lines:
if line!=getID+"\n":
f.write(line)
f.close()
idEntry.delete(0,"end")
msg = Label(deleteWin, text="Removed Successfully", font="fixedsys 12 bold").place(x=10,y=50)
deleteWin = Toplevel()
deleteWin.geometry("200x100")
deleteWin.resizable(width=False, height=False)
deleteWin.title("DELETE")
delete_id = Label(deleteWin, text="ID Number ").grid(row=0,column=0)
idno = StringVar(None)
idEntry = Entry(deleteWin, text=idno, bg="lightgreen")
idEntry.grid(row=0,column=1)
deleteFinal = Button(deleteWin, text="REMOVE", command=deleteData, relief=GROOVE).grid(row=4, column=1)
filename = str(files.get())
nfile = open(filename, 'a+')
display = Label(root, text="Opened file successfully", font = "fixedsys 12 bold").place(x=10,y=120)
studentList = Listbox(root, width=45, height=14, bg="lightgreen")
for line in nfile:
studentList.insert(END, line)
studentList.place(x=12, y=200)
nfile.close()
addStud = Button(root, text="Add Student", width = 12, height = 2, command=newWindow, relief=GROOVE).place(x=12,y=150)
deleteStud = Button(root, text="Remove Student", width = 12, height = 2,command=deleteWindow, relief=GROOVE).place(x=115,y=150)
updateStud = Button(root, text="Update", width = 9, height = 2,command=updateWindow, relief=GROOVE).place(x=215, y=150)
addFile = Button(root, text="Open File", width = 12, height = 2, command=fileOpen, relief=GROOVE).pack()
root.mainloop()
root.mainloop()
Please look at my delete part. I can delete an entry but I have to Spell out everything, and for the users it would be a hassle right? I want to make it easier by deleting the entry via ID number only. Any help is appreciated. Thanks!
Related
New to Tkinter
I have a json file which contains some Firewall-rules, then convert it into two different csvs. As the firewall-rules have two different sets with ARules.csv and YRules.csv Don't want to merge it because of the requirement.
Then using splunk we pull the stats which will generate firewall-rules for that day. We then export it with the name - logReport.csv. Let's say there are 50 rows of data
check the results of logReport (data) is present in both the csvs[ARules(150 rows) and YRules(100 rows)]
ARules.loc[ARules['name'].isin(logReport['data'])] - [result - 30]
YRules.loc[YRules['name'].isin(logReport['data'])] - [result - 20]
What I am trying to achieve here is to create a process, where I call the api, and convert that JSON into multiple csv and display it in "tkinter" in two different frames one for ARules and other for YRules, then ask the user to import that logReport.csv using "filedialog or opencsv" and then get the matching/difference results and export it to csv.
my code
import pandas as pd
import json
f = open("/Users/Documents/Info/data.json")
data = json.load(f)
f.close()
ARules = pd.DataFrame(data['ARules'])
YRules = pd.DataFrame(data['YRules'])
csvfile = "/Users/Downloads/logReport.csv"
logReport = pd.read_csv(csvfile,error_bad_lines=False, engine="python")
ARulesV1 = ARules.loc[ARules['ARules'].isin(logReport['data'])]
YRulesV1 = XRules.loc[XRules['YRules'].isin(logReport['data'])]
I was able to do this much but not able to display the output on GUI.
import pandas as pd
import csv
import json,os
from tkinter import *
import tkinter as tk
from tkinter.filedialog import askopenfilename
def import_csv_data():
global v
csv_file_path = askopenfilename()
v.set(csv_file_path)
colnames=['rules', 'count']
logReport = pd.DataFrame(pd.read_csv(csv_file_path,error_bad_lines=False,names=colnames, header=None, engine="python"))
logReport.drop(logReport.index[0],inplace=True)
search(logReport)
def search(logReport):
f = open("/Users/Documents/Info/data.json")
data = json.load(f)
f.close()
ARules = pd.DataFrame(data['ARules'])
YRules = pd.DataFrame(data['YRules'])
print("Total Number of ARules:",ARules.shape[0])
print("Total Number of YRules:",YRules.shape[0])
print()
print("Stats Report from Splunk:",logReport.shape[0])
print("Number of Rules Triggered in ARules:",ARules.loc[ARules['name'].isin(logReport['data'])].shape[0])
print("Number of Rules Triggered in YRules:",YRules.loc[YRules['name'].isin(logReport['data'])].shape[0])
window = tk.Tk()
window.title("Search CSV")
frame = Frame(window, width=500, height=500)
frame.pack()
tk.Label(frame, text='File Path').grid(row=0, column=0)
v = tk.StringVar()
entry = tk.Entry(frame, textvariable=v,width=30).grid(row=0, column=1)
tk.Button(frame, text='Browse',command=import_csv_data).grid(row=1, column=0)
lbl3 = tk.Label(frame, text = "Total Number of Rules: ").grid(row = 3, column = 1)
window.mainloop()
Want to display the print details on GUI
import pandas as pd
import csv
import json,os
from tkinter import *
import tkinter as tk
from tkinter import messagebox
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfile
def import_csv_data():
global v,csvData
csv_file_path = askopenfilename()
v.set(csv_file_path)
colnames=['rules', 'count']
csvData = pd.DataFrame(pd.read_csv(csv_file_path,error_bad_lines=False,names=colnames, header=None, engine="python"))
csvData.drop(csvData.index[0],inplace=True)
search()
def loadJson():
global data
name = askopenfilename(initialdir="../Path/For/JSON_file",
filetypes=(("Json File", "*.json"), ("All Files", "*.*")),
title="Choose a file."
)
try:
f = open(name)
data = json.load(f)
f.close()
except Exception:
messagebox.showerror("Error Message", 'File Corrupted’)
def search():
global Adata, Ydata
Adata = pd.DataFrame(data['Arules'])
Ydata = pd.DataFrame(data['Yrules'])
adata.config(text=Adata.shape[0])
ydata.config(text=Ydata.shape[0])
tData.config(text=csvData.shape[0])
AResult.config(text=Adata.loc[Adata['name'].isin(csvData['rules'])].shape[0])
YResult.config(text=Ydata.loc[Ydata['name'].isin(csvData['rules'])].shape[0])
def write_to_csv():
notTriggered = Adata['name'].loc[~Adata['name'].isin(csvData['rules'])]
notTriggered2 = Ydata['name'].loc[~Ydata['name'].isin(csvData['rules'])]
bigResult = notTriggered.append(notTriggered2, ignore_index=True)
name = asksaveasfile(initialfile = 'Untitled.csv’,mode='w',
defaultextension=".csv",filetypes=[("All Files","*.*"),("Text Documents","*.txt")])
if name:
bigResult.to_csv(name)
name.close()
window = tk.Tk()
window.title("Search Match Alerts“)
frame = Frame(window, width=500, height=500)
frame.pack()
tk.Label(frame, text='File Path').grid(row=1, column=0)
v = tk.StringVar()
entry = tk.Entry(frame, textvariable=v,width=40).grid(row=1, column=1)
tk.Button(frame, text='Import Json',command=loadJson).grid(row=0, column=0)
tk.Button(frame, text='Browse',command=import_csv_data).grid(row=2, column=0)
tk.Button(frame, text='Export',command=write_to_csv).grid(row=2, column=3)
font1 = ("Arial", 14)
tk.Label(frame, text = "Total Number of ARules: ").grid(row = 3, column = 0)
adata = Label(frame, font=font1)
adata.grid(row=3, column=1, sticky=W)
tk.Label(frame, text = "Total Number of YRules: ").grid(row = 4, column = 0)
ydata = Label(frame, font=font1)
ydata.grid(row=4, column=1, sticky=W)
tk.Label(frame, text = "Stats Report from Splunk: ").grid(row = 5, column = 0)
tData = Label(frame, font=font1)
tData.grid(row=5, column=1, sticky=W)
tk.Label(frame, text = "No. of Match Result on ARules: ").grid(row = 6, column = 0)
AResult = Label(frame, font=font1)
AResult.grid(row=6, column=1, sticky=W)
tk.Label(frame, text = "No. of Match Result on YRules: ").grid(row = 7, column = 0)
YResult = Label(frame, font=font1)
YResult.grid(row=7, column=1, sticky=W)
window.mainloop()
I'm trying to create a GUI that allows to the user to manipulate data from mysql database. So the user must add a trip(trip-id, trip-short-name ...) then add stop times for each trip using Entry from tkinter.
paths=''
new_trip_id=''
def add_trip():
top = Toplevel()
top.title("Trips")
top.geometry("600x300")
lbl1 = Label(top, text = 'service_id:', font = {'Helvetica',10})
lbl1.place(relx=0.2, rely=0.1)
entry1 = Entry(top)
entry1.place(relx=0.45, rely=0.1)
global new_trip_id
lbl2 = Label(top, text = 'trip_id:', font = {'Helvetica',10})
lbl2.place(relx=0.2, rely=0.25)
entry2 = Entry(top)
entry2.place(relx=0.45, rely=0.25)
new_trip_id=entry2.get()
lbl3 = Label(top, text = 'trip_headsign')
entry3 = Entry(top)
entry3.place(relx=0.45, rely=0.4)
lbl4 = Label(top, text = 'trip_short_name:', font{'Helvetica',10})
lbl4.place(relx=0.2, rely=0.55)
entry4 = Entry(top)
entry4.place(relx=0.45, rely=0.55)
entry4.bind('<Return>', add_times)
button1 = Button(top, text="Cancel")
button1.place(relx=0.5 ,rely=0.7)
def add_times(event):
mysql.connector("INSERT INTO trips VALUES service_id, trip_id,
trip_headsign, trip_short_name",
[enty1.get(), entry2.get(), enty3.get(),
enty4.get()])
top = Toplevel()
top.title("Trips")
top.geometry("600x300")
Ididn't found a solution that allows to the user to add data.
I have a long chunk of code. I do not want to paste it all here, so let me explain what I am trying to accomplish here. Based on a number provided by the user I want to create that many text boxes and then get what is entered into that text box and insert that into the dictionary. I have tried this a few ways and just cannot get it to work correctly. The list is either empty or it only contains the last text box as the value for each key.
def multiple_choice():
def add():
top.destroy()
top = Tk()
top.title("Add Question")
w = 800
h = 800
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
question = Label(top, text="Question to be asked?", font = "Times 14 bold", fg = "blue")
question.grid(row = 2, column = 4)
questionText = Text(top, borderwidth = 5, width=50,height=5, wrap=WORD, background = 'grey')
questionText.grid(row = 3, column = 4)
numQuestions = Label(top, text = "Number of answer choices?", font = "Times 14 bold", fg = "blue")
numQuestions.grid(row = 4, column=4)
num = Entry(top, bd = 5)
num.grid(row=5, column = 4)
answerList = {}
def multiple():
def preview():
preview = Tk()
top.title("Question Preview")
w = 500
h = 500
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
title = Label(preview, text = "Short Answer Question Preview", font = "Times 18 bold", fg = "blue" )
title.grid(row = 0, column = 2)
qtext = "Question text will read: "
ques = Label(preview, text = qtext)
ques.grid(row=1, column = 2)
ques2 = Label( preview, text = questionText.get("1.0",END))
let = 'A'
i = 1
for word in answerList:
prev = let + ": " + word
ans = Label(preview, text = prev)
ans.grid(row=1+i, column = 2)
let = chr(ord(let) + 1)
answerCor = "The correct answer(s): "
a = Label(preview, text = answerCor)
a.grid(row=4, column = 2)
b = Label(preview, text = cor.get)
b.grid(row=5, column = 2)
if num.get().isdigit():
number = int(num.get())
AnswerChoices = Label(top, text = "Answer Choices?", font = "Times 14 bold", fg = "blue")
AnswerChoices.grid(row = 6, column=4)
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
print answerList
correct = Label(top, text = "Correct Answer(s) (seperated by commas)",
font = "Times 14 bold", fg = "blue")
correct.grid(row =99 , column=4)
cor = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
cor.grid(row=100, column = 4)
else:
error = Tk()
w = 500
h = 100
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
error.geometry('%dx%d+%d+%d' % (w, h, x, y))
text = "ERROR: You must enter an integer number"
Label(error,text = text, fg = "red", font = "Times 16 bold").pack()
MyButton5 = Button(top, text="Preview Question", width=20, command = preview, anchor=S)
MyButton5.grid(row=102, column=5)
MyButton4 = Button(top, text="Finish and Add Question", width=20, command = add, anchor=S)
MyButton4.grid(row=102, column=2)
but = Button(top, text="Submit", width=10, command = multiple)
but.grid(row=6, column = 4)
top.mainloop()
def button():
MyButton21 = Button(quiz, text="Short Answer Question", width=20, command = short_answer)
MyButton21.grid(row=8, column=2)
MyButton22 = Button(quiz, text="True/False Question", width=20, command = true_false)
MyButton22.grid(row=8, column=4)
MyButton23 = Button(quiz, text="Multiple Choice Question", width=20, command = multiple_choice)
MyButton23.grid(row=9, column=2)
#MyButton24 = Button(quiz, text="Matching Question", width=20, command = matching)
#MyButton24.grid(row=9, column=4)
MyButton25 = Button(quiz, text="Ordering Question", width=20, command =order)
MyButton25.grid(row=10, column=2)
MyButton26 = Button(quiz, text="Fill in the Blank Question", width=20, command = fill_blank)
MyButton26.grid(row=10, column=4)
MyButton3 = Button(quiz, text="Finsh Quiz", width=10, command = quiz)
MyButton3.grid(row=12, column=3)
quiz = Tk()
w = 700
h = 300
ws = quiz.winfo_screenwidth()
hs = quiz.winfo_screenheight()
x = 0
y = 0
quiz.geometry('%dx%d+%d+%d' % (w, h, x, y))
quiz.title("eCampus Quiz Developer")
L1 = Label(quiz, text="Quiz Title?")
L1.grid(row=0, column=0)
E1 = Entry(quiz, bd = 5)
E1.grid(row=0, column=3)
name_file = E1.get()
name_file = name_file.replace(" ", "")
name_file = name_file + ".txt"
with open(name_file,"w") as data:
MyButton1 = Button(quiz, text="Submit", width=10, command = button)
MyButton1.grid(row=1, column=3)
quiz.mainloop()
I am trying to create the dictionary using this chunk of code:
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
I have even tried putting a loop in the preview function but that is when the last box was the only value contained in the dictionary. Any ideas would be appreciated
Please see my commeneted snippet below which demonstrates this:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.entry = Entry(self.root) #entry to input number of entries later
self.button = Button(self.root, text="ok", command=self.command) #calls command to draw the entry boxes
self.frame = Frame(self.root)
self.entry.pack()
self.button.pack()
self.frame.pack()
def command(self):
self.frame.destroy() #destroys frame and contents
self.frame = Frame(self.root) #recreates frame
self.text = [] #empty array to store entry boxes
for i in range(int(self.entry.get())):
self.text.append(Entry(self.frame, text="Question "+str(i))) #creates entry boxes
self.text[i].pack()
self.done = Button(self.frame, text="Done", command=self.dict) #button to call dictionary entry and print
self.done.pack()
self.frame.pack()
def dict(self):
self.dict = {}
for i in range(len(self.text)):
self.dict.update({self.text[i].cget("text"): self.text[i].get()})
#the above line adds a new dict entry with the text value of the respective entry as the key and the value of the entry as the value
print(self.dict) #prints the dict
root = Tk()
App(root)
root.mainloop()
The above asks the user how many entry widgets they want to create, fills a frame with those entry widgets and then iterates through the list which contains them on the press of a button, adding a new dictionary entry for each entry widget, where the key of the dict is the attribute text for each entry and the value of the dict is the value of each entry.
I am building a chat GUI. On enter-key press, I want the text fields to be shown on the text box as well as be saved in a file. I do not want to use separate button. It is being shown in the text box correctly but not getting saved in the file. Please tell me how can it be done. This is my first time using tkinter.
from Tkinter import *
root = Tk()
frame = Frame(root, width=300, height=1000)
frame.pack(side=BOTTOM)
#username entry
L1 = Label(frame, text="User Name")
L1.pack(side = LEFT)
input_username = StringVar()
input_field1 = Entry(frame, text=input_username, width=10)
input_field1.pack(side=LEFT, fill=X)
#addresee entry
L2 = Label(frame, text="#")
L2.pack(side = LEFT)
input_addresee = StringVar()
input_field2 = Entry(frame, text=input_addresee, width=10)
input_field2.pack(side=LEFT, fill=X)
#user comment entry
L3 = Label(frame, text="Comment")
L3.pack(side = LEFT)
input_usertext = StringVar()
input_field3 = Entry(frame, text=input_usertext, width=100)
input_field3.pack(side=LEFT, fill=X)
#write to a file
def save():
text = input_field1.get() + input_field2.get() + input_field3.get()
with open("test.txt", "w") as f:
f.write(text)
#chat box
chats = Text(root)
chats.pack()
def Enter_pressed(event):
input_get_name = input_field1.get()
print(input_get_name)
chats.insert(INSERT, '%s : ' % input_get_name)
input_username.set('')
input_get_add = input_field2.get()
print(input_get_add)
chats.insert(INSERT, '#%s : ' % input_get_add)
input_addresee.set('')
input_get_comment = input_field3.get()
print(input_get_comment)
chats.insert(INSERT, '%s\n' % input_get_comment)
input_usertext.set('')
save()
frame2 = Frame(root)
L2_1 = Label(frame2, text="All chats")
L2_1.pack(side = TOP)
input_field1.bind(Enter_pressed)
input_field2.bind(Enter_pressed)
input_field3.bind("<Return>", Enter_pressed)
frame2.pack()
root.mainloop()
As you said you are setting the input fields to blank
Here's the solution:
def save(text):
with open("test.txt", "w") as f:
f.write(text)
And when calling save:
save(input_get_name+": "+input_get_add+": "+input_get_comment)
For my coursework i am doing a booking system which uses some tree views. The problem is that if ran from cmd when i double click on a row in the tree view it does not populate the boxes below it, however if i run it from the idle it does. Below is my where i have made my class and two defs which are create_GUI(for first part of gui before double click) and double click(makes second part of GUI)
from tkinter import *
import os
import datetime
import sqlite3
from tkinter.ttk import Combobox,Treeview,Scrollbar
import tkinter as tk
import Utilities
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):
frame1 = tk.LabelFrame(root, text="frame1", width=300, height=130, bd=5)
frame2 = tk.LabelFrame(root, text="frame2", width=300, height=130, bd=5)
frame1.grid(row=0, column=0, columnspan=3, padx=8)
frame2.grid(row=1, column=0, columnspan=3, padx=8)
self.title_lbl = Label(frame1, text = "Students")
self.title_lbl.grid(row = 0, column = 2)
self.fn_lbl = Label(frame1, text = "First Name:")
self.fn_lbl.grid(row = 1 , column = 1)
self.fn_txt = Entry(frame1)
self.fn_txt.grid(row = 1, column = 2)
self.ln_lbl =Label(frame1, text = "Last Name:")
self.ln_lbl.grid(row = 2, column = 1)
self.ln_txt = Entry(frame1)
self.ln_txt.grid(row = 2, column = 2)
self.q_btn = Button(frame1, text = "Back",padx=80,pady=10, command = lambda: self.Quit())
self.q_btn.grid(row = 3, column = 0)
self.s_btn = Button(frame1, text = "search",padx=80,pady=10, command = lambda: self.search())
self.s_btn.grid(row = 3,column = 3)
self.tree = Treeview(frame2,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 = 100)
self.tree.column("First Name",width = 100)
self.tree.column("Last Name", width = 100)
## 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(frame2, orient='vertical', command=self.tree.yview)
xscrollbar = Scrollbar(frame2, orient='horizontal', command=self.tree.xview)
self.tree.configure(yscroll=yscrollbar.set, xscroll=xscrollbar.set)
yscrollbar.grid(row=1, column=5, padx=2, pady=2, sticky=NS)
self.tree.grid(row=1,column=0,columnspan =5, padx=2,pady=2,sticky =NSEW)
self.tree.bind("<Double-1>",lambda event :self.OnDoubleClick(event))
def OnDoubleClick(self, event):
frame3 = tk.LabelFrame(root, text="frame1", width=300, height=130, bd=5)
frame3.grid(row=2, column=0, columnspan=3, padx=8)
self.message=StringVar()
self.message.set("")
self.lblupdate = Label(frame3, textvariable = self.message).grid(row=0,column=0,sticky=W)
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(frame3, text = "Student ID").grid(row=5,column=0,sticky=W)
self.StudentID = Label(frame3, textvariable=self.tStudentID).grid(row =5,column=1,stick=W)
self.inst_lbl1 = Label(frame3, text = "First Name").grid(row=6,column=0,sticky=W)
self.NFirstName = Entry(frame3, textvariable=self.tFirstName).grid(row =6,column=1,stick=W)
self.inst_lbl2 = Label(frame3, text = "Last Name").grid(row=7,column=0,sticky=W)
self.NLastName = Entry(frame3, textvariable=self.tLastName).grid(row =7,column=1,stick=W)
self.inst_lbl3 = Label(frame3, text = "House Number").grid(row=8,column=0,sticky=W)
self.HouseNumber = Entry(frame3,textvariable=self.tHouseNumber).grid(row=8,column=1,sticky=W)
self.inst_lbl4 = Label(frame3, text = "Street Name").grid(row=9,column=0,sticky=W)
self.StreetName =Entry(frame3,textvariable=self.tStreetName).grid(row=9,column=1,sticky=W)
self.inst_lbl5 = Label(frame3, text = "Town or City Name").grid(row=10,column=0,sticky=W)
self.TownOrCityName =Entry(frame3,textvariable=self.tTownOrCityName).grid(row=10,column=1,sticky=W)
self.inst_lbl6 = Label(frame3, text = "Postcode").grid(row=11,column=0,sticky=W)
self.PostCode = Entry(frame3,textvariable=self.tPostCode).grid(row=11,column=1,sticky=W)
self.inst_lbl7 = Label(frame3, text = "Email").grid(row=12,column=0,sticky=W)
self.Email =Entry(frame3,textvariable=self.tEmail).grid(row=12,column=1,sticky=W)
self.inst_lbl8 = Label(frame3, text = "Mobile phonenumber").grid(row=13,column=0,sticky=W)
self.MobilePhoneNumber =Entry(frame3,textvariable=self.tMobilePhoneNumber).grid(row=13,column=1,sticky=W)
self.btnSaveChanges = Button(frame3, text = "save changes",padx=80,pady=10,command = lambda:self.SaveChanges()).grid(row=14,column=0,sticky=W)
self.btnSaveChanges = Button(frame3, 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):
valid = True
self.message.set("")
NFirstName = self.tFirstName.get()
NLastName = self.tLastName.get()
NHouseNumber = self.tHouseNumber.get()
NStreetName = self.tStreetName.get()
NTownOrCityName = self.tTownOrCityName.get()
NPostCode = self.tPostCode.get()
NEmail = self.tEmail.get()
NMobilePhoneNumber = self.tMobilePhoneNumber.get()
StudentID = self.tStudentID.get()
if NFirstName == "" or NLastName == "" or NEmail == "" or NMobilePhoneNumber == "":
valid = False
self.message.set('missing details,first name,last name,phone number, email are all needed')
if not Utilities.is_phone_number(NMobilePhoneNumber ):
valid = False
self.message.set('invalid mobile phone number')
if not Utilities.is_postcode(NPostCode):
valid = False
self.message.set('invalid postcode')
if not Utilities.is_email(NEmail):
valid = False
self.message.set('invalid email')
if NHouseNumber != "":
if int(NHouseNumber) < 0:
self.message.set('invalid house number')
if valid == True:
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,StudentID))
db.commit()
self.message.set("student details updated")
def DeleteRecord(self):
StudentID = self.tStudentID.get()
#StudentID = int(StudentID)
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
sql = "delete from tblStudents where StudentID = ?"
cursor.execute(sql,(StudentID))
db.commit()
self.tlabeupdate.set("student details deleted")
root = Tk()
root.title("booking system")
root.geometry("800x800")
root.configure(bg="white")
app = Application(root)
root.mainloop()
EDIT
when i was copyign and pasting the rest of my code that i forgot to put in the original post i found that it only stops working if i open it through the student menu(separate peice of code) but it works if i dont go through the menu
You must call mainloop() on the root window so that your program can process events.
You create LabelFrames in the parent called root, but root does not exist. To correct it pass master to the function, which receives it as root
class Application():
""" Binary to Decimal """
def __init__(self, master):
""" Initialize the frame. """
self.create_GUI(master)
def create_GUI(self, root):
frame1 = tk.LabelFrame(root, text="frame1", width=300, height=130, bd=5)