First tkinter program - python-3.x

I'm relatively new to the whole tkinter/python thing and I've just created the following Calculator:
import tkinter as tk
class theCalculator:
def __init__(self, master):
master.wm_title("Calculator")
master.geometry("340x350")
master.resizable(0, 0)
signsList = ["-","+","*","/","%"]
#Declaring the buttons
self.textField = tk.Entry(master, width=16, font=("Arial Bold",20))
self.textField.place(x=40,y=50)
self.cButton = tk.Button(master, text="C", width=14, height=2, command = lambda:cleanSpace(self))
self.cButton.place(x=40, y=100)
self.modButton = tk.Button(master, text="%", width=5, height=2,command=lambda:signThings(self,"%"))
self.modButton.place(x=180, y=100)
self.divButton = tk.Button(master, text="/", width=5, height=2,command=lambda:signThings(self,"/"))
self.divButton.place(x=248, y=100)
self.xButton = tk.Button(master, text="x", width=5, height=2, bg="yellow",command=lambda:signThings(self,"*"))
self.xButton.place(x=248, y=142)
self.minusButton = tk.Button(master, text="-", width=5, height=2, bg="yellow",command=lambda:signThings(self,"-"))
self.minusButton.place(x=248, y=185)
self.plusButton = tk.Button(master, text="+", width=5, height=2, bg ="yellow",command=lambda:signThings(self,"+"))
self.plusButton.place(x=248, y=228)
self.nineButton = tk.Button(master, text="9", width=5, height=2,command=lambda:setText(self,"9"))
self.nineButton.place(x=40, y=142)
self.eightButton = tk.Button(master, text="8", width=5, height=2,command=lambda:setText(self,"8"))
self.eightButton.place(x=110, y=142)
self.sevenButton = tk.Button(master, text="7", width=5, height=2,command=lambda:setText(self,"7"))
self.sevenButton.place(x=180, y=142)
self.sixButton = tk.Button(master, text="6", width=5, height=2,command=lambda:setText(self,"6"))
self.sixButton.place(x=40, y=185)
self.fiveButton = tk.Button(master, text="5", width=5, height=2,command=lambda:setText(self,"5"))
self.fiveButton.place(x=110, y=185)
self.fourButton = tk.Button(master, text="4", width=5, height=2,command=lambda:setText(self,"4"))
self.fourButton.place(x=180, y=185)
self.threeButton = tk.Button(master, text="3", width=5, height=2,command=lambda:setText(self,"3"))
self.threeButton.place(x=40, y=228)
self.twoButton = tk.Button(master, text="2", width=5, height=2,command=lambda:setText(self,"2"))
self.twoButton.place(x=110, y=228)
self.oneButton = tk.Button(master, text="1", width=5, height=2,command=lambda:setText(self,"1"))
self.oneButton.place(x=180, y=228)
self.zeroButton = tk.Button(master, text="0", width=14, height=2,command=lambda:zeroThings(self))
self.zeroButton.place(x=40, y=271)
self.pointButton = tk.Button(master, text=".", width=5, height=2,command=lambda:dotThings(self))
self.pointButton.place(x=180, y=271)
self.equalsButton = tk.Button(master, text="=", width=5, height=2, bg="yellow",command=lambda:calculate(self))
self.equalsButton.place(x=248, y=271)
#Declaring the methods
def setText(self, text):
self.textField.insert(tk.END, text)
def signThings(self, sign):
theText = self.textField.get()
if(len(theText)==0):
print("The first character can't be a sign")
return 0;
if(theText[-1] in signsList):
print("Can't have two signs one after another")
return 0;
if(theText[-1]=="."):
print("Can't have a sign after .")
return 0;
self.textField.insert(tk.END, sign)
def calculate(self):
theResult = eval(self.textField.get())
self.textField.delete(0, tk.END)
self.textField.insert(0, str(round(theResult,4)))
def cleanSpace(self):
self.textField.delete(0, tk.END)
def zeroThings(self):
theText = self.textField.get()
if(len(theText)==1):
if(theText==0):
print("Can't have two zeroes one after another")
else:
self.textField.insert(tk.END,"0")
elif(len(theText)>1):
self.textField.insert(tk.END,"0")
def dotThings(self):
theText = self.textField.get()
numberOfSigns = 0
numberOfDots = 0
for c in theText:
if c in signsList:
numberOfSigns +=1
if c==".":
numberOfDots +=1
try:
if (numberOfSigns>=numberOfDots and theText[-1] not in signsList):
self.textField.insert(tk.END,".")
except Exception as e:
self.textField.insert(tk.END,".")
root = tk.Tk()
calc = theCalculator(root)
root.mainloop()
I want to ask for your opinions on this and I have some questions:
Is there any other way I could have declared the buttons? ie using something like a for loop to create them?
I'm pretty sure my "self" game isn't on point. Could you give me some advice on improving it?
What is your advice on improving my functions' logic?
Please, point out any another flaws you see.
Thank you

Related

Is it possible to bind without using the class?

def click():
top1 = Toplevel(root)
top1.title("Test")
top1.geometry("200x200")
top1.overrideredirect(True)
top1.config(bg = "blue", relief='raised', bd=0,highlightthickness=0)
top1.window = Canvas(top1, width=0, height=38, bg="blue", bd=2, relief='raised', highlightthickness=0)
top1.window.pack(fill="both", expand=False)
top1.btn3 = tkinter.Button(top1, text="X", font="bold", bg="blue", padx=1, pady=1,activebackground='red',bd = 0,fg='white',highlightthickness=0, command= root.destroy)
top1.btn3.place(x=169, y=3)
top1.btn4 = tkinter.Button(top1, text="Hello", font=("bold", 16), bg="skyblue", command=click2)
top1.btn4.place(x=10, y=70)
def click2():
top2 = Toplevel(root)
top2.title("Test")
top2.geometry("200x200")
top2.overrideredirect(True)
top2.config(bg = "red", relief='raised', bd=0,highlightthickness=0)
top2.window = Canvas(top2, width=0, height=38, bg="red", bd=2, relief='raised', highlightthickness=0)
top2.window.pack(fill="both", expand=False)
top2.btn5 = tkinter.Button(top2, text="X", font="bold", bg="red", padx=1, pady=1,activebackground='red',bd = 0,fg='white',highlightthickness=0, command= root.destroy)
top2.btn5.place(x=169, y=3)
btn2 = Button(root, text="Hello", font=("bold", 16), bg="pink", command=click)
btn2.place(x=45, y=45)
The child window won't move. Is it possible to bind without class with the above code?
I want to use the class function, but it's very difficult. I'd appreciate it if you could tell me briefly!

Filling Tkinter window

I'm having some trouble get my frames and widgets to fill out the tkinter window. I don't know what I have wrong here. I have been trying to mess around with columnspan sticky and width/height. I am fairly new to using Tkinter and still trying to figure out the basics of widgets and geometry management.
def comments():
root = tk.Tk()
root.title("Comments")
root.geometry("300x200+300+300")
var = tk.IntVar()
top_frame = tk.Frame(root, bg="red", width=350, height=50)
name_label = tk.Label(top_frame, text="Username", bg='red', fg="yellow", font=("arial, 17"))
name_entry = tk.Entry(top_frame)
comment_frame = tk.Frame(root, bg="yellow", width=40, height=70, bd="3px", relief=GROOVE)
comment_entry = tk.Text(comment_frame, bd=2, relief=SUNKEN, width=40, height=5)
comment = comment_entry.get('1.0', 'end-1c')
like_dislike_frame = tk.Frame(root, relief=GROOVE, bg='green', width=300, height=50)
#like_button = tk.Button(like_dislike_frame, text="Like").grid(row=2, sticky=W, padx="6px")
#dislike_button = tk.Button(like_dislike_frame, text="Dislike").grid(row=2)
like_button = tk.Checkbutton(like_dislike_frame, text="Like", font=("arial, 12"), onvalue=1,offvalue=0, variable=var, bg='green', fg='yellow')
dislike_button = tk.Checkbutton(like_dislike_frame, text="Dislike", font=("arial, 12"), onvalue=1,offvalue=0, variable=var, bg='green', fg='yellow')
def save_comment():
#if like_dislike == 0:
#dislikes =+ 1
#opinion = dislike
#elif like_dislike == 1:
#likes =+ 1
#opinion = like
now = datetime.datetime.now()
if now.hour > 12:
hour = now.hour-12
meridiem = 'pm'
else:
hour = now.hour
meridiem = 'am'
timestamp = str(now.month)+'/'+str(now.day)+'/'+str(now.year)+'\t'+str(hour)+':'+str(now.minute)+':'+str(now.second)
with open(comments_file, 'a') as file:
file.write(comment + timestamp + meridiem + '\r\n\n')
exit_comments = tk.messagebox.askyesno('Exit', 'Return to About Page?')
if exit_comments == True:
root.destroy()
submit_button = tk.Button(like_dislike_frame, text="Submit", command=save_comment)
top_frame.grid(row=0, column=0, sticky=EW)
name_label.grid(row=0, column=0, sticky=W, padx="5px")
name_entry.grid(row=0, column=1, sticky=E, padx="5px")
comment_frame.grid(row=1, column=0)
comment_entry.grid(row=1, column=0, sticky=EW)
like_dislike_frame.grid(row=2, column=0, sticky=NSEW)
like_button.grid(row=2, column=0, sticky=W, padx="6px")
dislike_button.grid(row=2, column=1, padx="6px")
submit_button.grid(row=2, column=2, sticky=E)
root.mainloop()

Is it possible to grab input from the topview tkinter window and retrieve saved entry field value from within master tk window

The program is made up of classes and I am trying to use a tkinter topview from within a function so that when it's called it is able to retrieve the entryfield value to the master class
from tkinter import
from PIL import Image, ImageTk
Below is the driver code handling the transitioning from one class to another
class SeaofBTCapp(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
container = Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (
WelcomePage, Register_new_user): # ,PageThree,PageFour):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(WelcomePage)
# def show_frame(self, cont):
# frame = self.frames[cont]
# frame.tkraise()
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
frame.update()
frame.event_generate("<<show_frame>>")
def get_page(self, cont):
for page in self.frames.values():
if str(page.__class__.__name__) == cont:
return page
return None
class Register_new_user(object):
pass
Below is the entry point of the program and is the first page to be displayed
class WelcomePage(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
# self.bind("<<show_frame>>", self.main_prog)
def resize_image(event):
global photo
new_width = event.width
new_height = event.height
image = copy_of_image.resize((new_width, new_height))
photo = ImageTk.PhotoImage(image)
label.config(image=photo)
label.image = photo # avoid garbage collection
def pin_input():
top = Toplevel()
top.geometry("180x100")
top.title("toplevel")
l2 = Label(top, text="This is toplevel window")
global entry_1
global password
password = StringVar
entry_1 = None
def cleartxtfield():
global password
new = "3"
password.set(new)
# ############# Function to parse for only numerical input
def validate(input):
if input.isdigit():
return True
elif input == "":
return True
else:
return False
def enternumber(x):
global entry_1
setval = StringVar()
setval = str(x)
# print(setval)
entry_1.insert(END, setval)
entry_1 = Entry(top, textvariable=password, width=64, show='*')
entry_1.place(x=200, y=100)
entry_1.focus()
reg = top.register(validate)
entry_1.config(validate="key", validatecommand=(reg, '%P'))
def getcreds():
# check if four digit entered and is not empty
global passwd
passwd = password.get()
print(f"The Credentials are {passwd}")
def funcbackspace():
length = len(entry_1.get())
entry_1.delete(length - 1, 'end')
def killwindow():
# when the user quits it should clear all the data input fields filled in in the previous steps. and should display information that it is about to quit in a few seconds
command = top.destroy()
# Label(top,text="Goodbye\n (Closing in 2 seconds)")
top.after(2000, top.quit())
cancel = Button(top, width=8, height=3, text="Cancel", bg="red", fg="black", command=killwindow)
cancel.place(x=220, y=150)
backspace = Button(top, width=8, height=3, text="Backspace", bg="red", fg="black", command=funcbackspace)
backspace.place(x=500, y=150)
# ----number Buttons------
def enternumber(x):
global entry_1
setval = StringVar()
setval = str(x)
# print(setval)
entry_1.insert(END, setval)
btn_numbers = []
for i in range(10):
btn_numbers.append(
Button(top, width=8, height=3, text=str(i), bd=6, command=lambda x=i: enternumber(x)))
btn_text = 1
for i in range(0, 3):
for j in range(0, 3):
btn_numbers[btn_text].place(x=220 + j * 140, y=250 + i * 100)
btn_text += 1
btn_zero = Button(top, width=15, height=2, text='0', bd=5, command=lambda x=0: enternumber(x))
btn_zero.place(x=330, y=550)
clear = Button(top, text="Clear", bg="green", fg="white", width=8, height=3, command=cleartxtfield)
clear.place(x=220, y=550)
okbtn = Button(top, text="Enter", bg="green", fg="black", width=8, height=3, command=getcreds)
okbtn.place(x=500, y=550)
val = getcreds()
print("The value to be returned is %s" % val)
return val
password = pin_input()
print("Gotten password is %s" % password)
copy_of_image = Image.open("image.png")
photoimage = ImageTk.PhotoImage(copy_of_image)
label = Label(self, image=photoimage)
label.place(x=0, y=0, relwidth=1, relheight=1)
label.bind('<Configure>', resize_image)
top_left_frame = Frame(self, relief='groove', borderwidth=2)
top_left_frame.place(relx=1, rely=0.1, anchor=NE)
center_frame = Frame(self, relief='raised', borderwidth=2)
center_frame.place(relx=0.5, rely=0.75, anchor=CENTER)
Button(top_left_frame, text='REGISTER', bg='grey', width=14, height=1,
command=lambda: controller.show_frame(Register_new_user)).pack()
Button(center_frame, text='ENTER', fg='white', bg='green', width=13, height=2,
command=lambda: controller.show_frame(Register_new_user)).pack()
if __name__ == '__main__':
app = SeaofBTCapp()
app.title("Password return on topview window")
width = 1000
height = 700
screenwidth = app.winfo_screenwidth()
screenheight = app.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
app.geometry(alignstr)
# app.resizable(width=False, height=False)
app.resizable(width=True, height=True)
app.mainloop()
If I understand this correctly you want to enter a password in a dialog and then get the password from the dialog when you close it.
Have a look at Dialog Windows at effbot for a discussion about creating dialog windows.
Here is an example of how you can implement a simple dialog:
from tkinter import *
from tkinter import simpledialog
class MyDialog(simpledialog.Dialog):
def body(self, master):
'''create dialog body.
return widget that should have initial focus.
This method should be overridden, and is called
by the __init__ method.'''
Label(master, text='Value:').grid(row=0)
self.e1 = Entry(master)
self.e1.grid(row=0, column=1)
return self.e1 # initial focus
def apply(self):
'''process the data
This method is called automatically to process the data, *after*
the dialog is destroyed. By default, it does nothing.'''
value = self.e1.get()
self.result = value
def validate(self):
'''validate the data
This method is called automatically to validate the data before the
dialog is destroyed. By default, it always validates OK.'''
return 1 # override
def buttonbox(self):
'''add standard button box.
override if you do not want the standard buttons
'''
box = Frame(self)
w = Button(box, text="OK", width=10, command=self.ok, default='active')
w.pack(side='left', padx=5, pady=5)
w = Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side='left', padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
if __name__ == '__main__':
root = Tk()
root.geometry('200x100+800+50')
def do():
d = MyDialog(root)
print(d.result)
b = Button(root, text='Go!', width=10, command=do)
b.pack(expand=True)
Did that answer your question?

I would like to use a buttons output in tkinter to answer an input in another function

This is a simple memory game, where the voice says a number, and you have to click the button with the same number. I want to use it with comparing lists. If you guessed correctly one the code will add another, and another and so on. My problem is, that I have the buttons and with the function button click I can define the values with print. I have the code where it should be linked, but I cannot lined them together. Please help me :)
import pyttsx3
import time
import random
import tkinter as tk
from tkinter import *
root = Tk()
root.title("A little memory game")
sound_or_color = IntVar() # for radiobutton 1, sound, 2 color
quiz_list = [] # this will be the random number
your_list = [] # this will get the input form the buttons
guess = StringVar() # for the label to add guesses
best_score = 2
best_score_final = IntVar()
best_score_final.set(best_score)
actual_score_actual = IntVar()
def button_click(number):
your_list.append(number)
print(your_list)
def game():
# if sound_or_color == 1: # this will work with sound
actual_score = 0
global best_score
while True:
# this will generate the task, each round
quiz_number = random.randint(1, 9)
quiz_list.append(quiz_number)
speaker = pyttsx3.init()
speaker.say(quiz_list)
speaker.runAndWait()
print(quiz_list)
guess.set("click your guess(es)")
**# take the user's guess:
for i in range(0, len(quiz_list)):
# your_list.append(int(input())) <------the problematic part
button_click()**
# was the guess right?
if quiz_list == your_list:
actual_score += 1
actual_score_actual.set(actual_score)
your_list.clear()
else:
end_text = "Coungratulation, your score is", actual_score
your_list.clear()
quiz_list.clear()
speaker2 = pyttsx3.init()
speaker2.say(end_text)
speaker2.say("Click the start button, to play again")
speaker2.runAndWait()
if actual_score > best_score:
best_score = actual_score
best_score_final.set(best_score)
break
# labels:
label_best = tk.Label(root, text="best score: ",
textvariable=best_score_final, fg="#900C3F")
label_score = tk.Label(root, text="actual score: ",
textvariable=actual_score_actual, fg="#07A0F1")
label_best2 = tk.Label(root, text="best score: ", fg="#900C3F")
label_score2 = tk.Label(root, text="actual score: ", fg="#07A0F1")
label_input = tk.Label(root, textvariable=guess)
# define buttons:
button_start = Button(root, text="Start",
command=game, bg="#65B9E5")
button_0 = Radiobutton(root, text="with sound",
variable=sound_or_color, value=1)
button_10 = Radiobutton(root, text="with color",
variable=sound_or_color, value=2)
button_1 = Button(root, text="1", padx=40, pady=20,
command=lambda: button_click(1))
button_2 = Button(root, text="2", padx=40, pady=20,
command=lambda: button_click(2))
button_3 = Button(root, text="3", padx=40, pady=20,
command=lambda: button_click(3))
button_4 = Button(root, text="4", padx=40, pady=20,
command=lambda: button_click(4))
button_5 = Button(root, text="5", padx=40, pady=20,
command=lambda: button_click(5))
button_6 = Button(root, text="6", padx=40, pady=20,
command=lambda: button_click(6))
button_7 = Button(root, text="7", padx=40, pady=20,
command=lambda: button_click(7))
button_8 = Button(root, text="8", padx=40, pady=20,
command=lambda: button_click(8))
button_9 = Button(root, text="9", padx=40, pady=20,
command=lambda: button_click(9))
# Put buttons on the screen
label_input.grid(row=0, column=0, columnspan=3)
button_1.grid(row=1, column=0)
button_2.grid(row=1, column=1)
button_3.grid(row=1, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=3, column=0)
button_8.grid(row=3, column=1)
button_9.grid(row=3, column=2)
button_0.grid(row=4, column=0)
button_10.grid(row=4, column=1)
button_start.grid(row=4, column=2)
label_score2.grid(row=5, column=0)
label_best2.grid(row=5, column=1)
label_score.grid(row=6, column=0)
label_best.grid(row=6, column=1)
root.mainloop()

SQLite Python Query not working when using tkinter with no error messages

I am learning python for my A level and have come across a problem in my project, any help would be immensely appreciated. Thank you.
I have a series of tkinter pages that are designed to be linked by one central page. The search, delete and update functions successfully run SQL queries on their own but lose their functionality when called from the main page, I am getting no visible error messages. I am running SQLite 3.11.2 and Python 3.7.3
The main page calls the attendance page like this (triggered using a button):
def ap():
AttendancePage.Attendance(Tk())
The actual attendance page is as follows:
import tkinter as tk
from tkinter import*
import tkinter.messagebox
import NEA_SQL_IIII
class Attendance:
def __init__ (self,root):
self.root =root
self.root.title("ODIN Attendance Page")
self.root.geometry("1350x750+0+0")
self.root.config(bg="ghost white")
#These are all the entry widgets, where the values will be added
Absent = BooleanVar()
AbsenceNote = BooleanVar()
TotalAbsences = IntVar()
StudentName = StringVar()
StudentID = StringVar()
should_auto = BooleanVar()
#function
#This is the section that will give the buttons their functionality
def Clear():
self.entStudentID.delete(0,END)
self.entStudentName.delete(0,END)
self.chkAbsent.deselect()
self.chkAbsenceNote.deselect()
self.entTotalAbsences.delete(0,END)
def Exit():
Exit = tk.messagebox.askyesno("ODIN","Do you wish to exit?")
if Exit > 0:
root.destroy()
return
def searchDatabase():
attendanceList.delete(0,END)
for row in NEA_SQL_IIII.searchA(StudentID.get(),StudentName.get()):
attendanceList.insert(END,row,str(""))
def viewData():
attendanceList.delete(0,END)
for row in NEA_SQL_IIII.displayA():
attendanceList.insert(END,row,str(""))
def deleteData():
if(len(StudentName.get())!=0):
NEA_SQL_IIII.DeleteDataA(sd[0])
Clear()
viewData()
def AttendRec(event):
global sd
searchAttend = attendanceList.curselection()[0]
sd = attendanceList.get(searchAttend)
self.entStudentID.delete(0,END)
self.entStudentID.insert(END,sd[0])
self.entStudentName.delete(0,END)
self.entStudentName.insert(END,sd[1])
self.chkAbsent.deselect()
self.chkAbsent.select()
self.chkAbsenceNote.deselect()
self.chkAbsenceNote.select()
self.entTotalAbsences.delete(0,END)
self.entTotalAbsences.insert(END,sd[4])
def Update():
if(len(StudentID.get())!=0):
NEA_SQL_IIII.DeleteDataA(sd[0])
if(len(StudentID.get())!=0):
NEA_SQL_IIII.addStudentA(StudentID.get(),StudentName.get(),Absent.get(),AbsenceNote.get(),TotalAbsences.get())
attendanceList.delete(0,END)
attendanceList.insert(END,(StudentID.get(),StudentName.get(),Absent.get(),AbsenceNote.get(),TotalAbsences.get()))
#Frames
#These will define all the different frames
MainFrame = Frame(self.root, bg="Ghost White")
MainFrame.grid()
TitFrame = Frame(MainFrame, bd=2, padx=54, pady=8, bg="Ghost White", relief = RIDGE)
TitFrame.pack(side=TOP)
self.lblTit = Label(TitFrame ,font=('ariel', 47,'bold'),text="ODIN Attendance Page",bg="Ghost White")
self.lblTit.grid()
ButtonFrame = Frame(MainFrame, bd=2, width=1350, height=70, padx=18, pady=10, bg="blue2", relief = RIDGE)
ButtonFrame.pack(side=BOTTOM)
DataFrame = Frame(MainFrame, bd=1, width=1300, height=400, padx=20, pady=20, bg="ghost white", relief = RIDGE)
DataFrame.pack(side=BOTTOM)
#DataFrameTOP = LabelFrame(DataFrame, bd=1, width=1000, height=300, padx=20, pady=4, relief = RIDGE, bg="Ghost White", font=('ariel', 20,'bold'), text = "Student Info\n")
#DataFrameTOP.pack(side=TOP)
DataFrameLEFT = LabelFrame(DataFrame, bd=1, width=450, height=200, padx=20,pady=3, bg="Ghost White", relief = RIDGE, font=('ariel', 20,'bold'), text = "Student Info\n")
DataFrameLEFT.pack(side=LEFT)
DataFrameRIGHT = LabelFrame(DataFrame, bd=1, width=450, height=200, padx=31,pady=3, bg="Ghost White", relief = RIDGE, font=('ariel', 20,'bold'), text = "Student Details\n")
DataFrameRIGHT.pack(side=RIGHT)
#Label and Entry Widget
#These are the widgets that will allow for labels onto the entry sections
self.lblStudentID = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Student ID", padx=2, pady=2, bg="Ghost White")
self.lblStudentID.grid(row=0, column=0, sticky=W)
self.entStudentID = Entry(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=StudentID, width=39)
self.entStudentID.grid(row=0, column=1)
self.lblStudentName = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Student Name", padx=2, pady=2, bg="Ghost White")
self.lblStudentName.grid(row=1, column=0, sticky=W)
self.entStudentName = Entry(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=StudentName, width=39)
self.entStudentName.grid(row=1, column=1)
self.lblAbsent = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Absent?", padx=2, pady=2, bg="Ghost White")
self.lblAbsent.grid(row=2, column=0, sticky=W)
self.chkAbsent = Checkbutton(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=Absent, variable = should_auto, onvalue = True, offvalue = False, width=39)
self.chkAbsent.grid(row=2, column=1)
self.lblAbsenceNote = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Absence Note?", padx=2, pady=2, bg="Ghost White")
self.lblAbsenceNote.grid(row=3, column=0, sticky=W)
self.chkAbsenceNote = Checkbutton(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=AbsenceNote, width=39, onvalue = True, offvalue = False)
self.chkAbsenceNote.grid(row=3, column=1)
self.lblTotalAbsences = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Total Absences?", padx=2, pady=2, bg="Ghost White")
self.lblTotalAbsences.grid(row=4, column=0, sticky=W)
self.entTotalAbsences = Entry(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=TotalAbsences, width=39)
self.entTotalAbsences.grid(row=4, column=1)
#scrollbar
scrollbar = Scrollbar(DataFrameRIGHT)
scrollbar.grid(row=0, column=1, sticky = 'ns')
attendanceList = Listbox(DataFrameRIGHT, width=41, height=16, font=('ariel',12,'bold'), yscrollcommand=scrollbar.set)
attendanceList.bind('<<ListboxSelect>>',AttendRec)
attendanceList.grid(row=0, column=0, padx=8)
scrollbar.config(command = attendanceList.yview)
#button
#self.btnAddDate = Button(ButtonFrame, text='Add New', font=('ariel',20,'bold'),height=1,width=10, bd=4, command=addData)
#self.btnAddDate.grid(row=0, column=0)
self.btnDisplay = Button(ButtonFrame, text='Display', font=('ariel',20,'bold'),height=1,width=10, bd=4, command=viewData)
self.btnDisplay.grid(row=0, column=0)
self.btnClear = Button(ButtonFrame, text='Clear', font=('ariel',20,'bold'),height=1,width=10, bd=4, command=Clear)
self.btnClear.grid(row=0, column=1)
self.btnDelete = Button(ButtonFrame, text='Delete', font=('ariel',20,'bold'),height=1,width=10, bd=4, command = deleteData)
self.btnDelete.grid(row=0, column=2)
self.btnSearch = Button(ButtonFrame, text='Search', font=('ariel',20,'bold'),height=1,width=10, bd=4, command = searchDatabase)
self.btnSearch.grid(row=0, column=3)
#self.btnUpdate = Button(ButtonFrame, text='Update', font=('ariel',20,'bold'),height=1,width=10, bd=4, command = updateData)
#self.btnUpdate.grid(row=0, column=4)
self.btnUpdate = Button(ButtonFrame, text='Update', font=('ariel',20,'bold'),height=1,width=10, bd=4, command = Update)
self.btnUpdate.grid(row=0, column=4)
self.btnQuit = Button(ButtonFrame, text='Quit', font=('ariel',20,'bold'),height=1,width=10, bd=4, command=Exit)
self.btnQuit.grid(row=0, column=5)
if __name__=='__main__':
root = tk.Tk()
application = Attendance(root)
root.mainloop()'''
The SQL code that is being called is:
def Attendance():
con=sqlite3.connect("Attendance.db")
cur=con.cursor()
cur.execute("CREATE TABLE IF NOT EXIST Attendance (Absent BOOLEAN, AbsenceNote BOOLEAN, TotalAbsences INTEGER, FOREIGN KEY StudentName REFERENCES StudentRecord(StudentName),FOREIGN KEY StudentID REFERENCES StudentRecord(StudentID), PRIMARY KEY(StudentID)")
con.commit()
con.close()
def displayA():
con=sqlite3.connect("Attendance.db")
cur=con.cursor()
cur.execute("SELECT * FROM Attendance")
rows =cur.fetchall()
con.close()
return rows
def DeleteDataA(StudentID):
con=sqlite3.connect("Attendance.db")
cur=con.cursor()
cur.execute("DELETE FROM Attendance WHERE StudentID=?", (StudentID,))
con.commit()
return con, cur
con.close()
def searchA(StudentName="", StudentID=""):
con=sqlite3.connect("Attendance.db", isolation_level=None)
cur=con.cursor()
cur.execute("SELECT * FROM Attendance WHERE StudentName=? OR StudentID=?", (StudentName,StudentID,))
rows = cur.fetchall()
con.close()
return rows
def UpdateDataA(StudentID="", StudentName="", Behaviour="", Achievement="", Detention="", ProgressLevel=""):
con=sqlite3.connect("StudentRecord.db")
cur=con.cursor()
cur.execute("UPDATE StudentRecord SET StudentName=?, Behaviour=?, Achievement=?, Detention=?, ProgressLevel=? WHERE StudentID=? ", (StudentID,StudentName,Behaviour,Achievement,Detention,ProgressLevel))
con.commit()
con.close()

Resources