Filling Tkinter window - python-3.x

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()

Related

Display different frames based on logged in value in tkinter

I am creating an office management application. In this, there is admin and staff. In the Log In page based on whether it is admin or staff different frames needs to be displayed.
I used an if-else statement for this purpose.I tried to compare the value of username using get() but was unable to print its value inside the function.
Following is the code I executed.
import tkinter as tk
from tkinter import ttk
import mysql.connector
class SchoolApp(tk.Tk):
BKGR_IMAGE_PATH = 'images\\bg11.png'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.geometry("1500x750")
main_frame = tk.Frame(self,width=200,height=50,highlightbackground="black",highlightthickness=1)
main_frame.pack(side='top', fill='both', expand='True')
main_frame.grid_rowconfigure(0, weight=1)
main_frame.grid_columnconfigure(0, weight=1)
self.bkgr_image = tk.PhotoImage(file=self.BKGR_IMAGE_PATH)
self.frames = {}
for F in (HomePage,LogIn,AdminPage,StaffPage):
frame = F(main_frame, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky='nsew')
self.show_frame(HomePage)
def show_frame(self,container):
frame = self.frames[container]
frame.tkraise()
class BasePage(tk.Frame):
def __init__(self, parent, controller):
super().__init__(parent)
label_bkgr = tk.Label(self, image=controller.bkgr_image)
label_bkgr.place(x=0,y=0) # Center label w/image.
class HomePage(BasePage):
def __init__(self, parent, controller):
super().__init__(parent, controller)
home_frame = tk.Frame(self, width=200, height=100, background="white")
home_frame.grid(row=50, column=150, padx=300, pady=100)
self.label_title = tk.Label(home_frame, text="Office Management System", font=("Helvetica", 40), bg="white")
self.label_title.grid(row=0, column=0)
staff_frame = tk.Frame(home_frame, width=100, height=50)
staff_frame.grid(row=55, column=0, padx=50, pady=50)
self.staff_Image = tk.PhotoImage(file="images\\staff1.png")
self.staff_Image_Pack = tk.Label(staff_frame, image=self.staff_Image)
self.staff_Image_Pack.grid()
self.staff_button = tk.Button(home_frame, text="Staff", width=20, font=("Helvetica", 12),command = lambda: controller.show_frame(LogIn))
self.staff_button.grid(row=60, column=0, pady=20)
admin_frame = tk.Frame(home_frame, width=100, height=50)
admin_frame.grid(row=55, column=10, padx=50, pady=50)
self.Admin_Image = tk.PhotoImage(file="images\\admin1.png")
self.Admin_Image_Pack = tk.Label(admin_frame, image=self.Admin_Image)
self.Admin_Image_Pack.grid()
self.admin_button = tk.Button(home_frame, text="Admin", width=20, font=("Helvetica", 12),command = lambda: controller.show_frame(LogIn))
self.admin_button.grid(row=60, column=10, pady=20)
class LogIn(BasePage):
def __init__(self,parent,controller):
super().__init__(parent, controller)
login_window = tk.Frame(self, width=200, height=100, background="white")
login_window.grid(row=50, column=150, padx=300, pady=100)
login_img_frame = tk.Frame(login_window, width=200, height=50, background="white")
login_img_frame.grid(row=55, column=0, padx=50, pady=50)
self.login_Image = tk.PhotoImage(file="images\\lock3.png")
self.login_Image_Pack = tk.Label(login_img_frame, image=self.login_Image)
self.login_Image_Pack.grid()
login_frame = tk.Frame(login_window, width=100, height=50, background="white", highlightbackground="black",highlightthickness=1)
login_frame.grid(row=55, column=10, padx=50, pady=50)
self.label_title = tk.Label(login_frame, text="Log In", font=("Helvetica", 40), bg="white")
self.label_title.grid(row=0, column=20, padx=10, pady=10)
self.label_username = tk.Label(login_frame, text="Username", font=("Helvetica", 20), bg="white")
self.label_username.grid(row=50, column=20, padx=10, pady=10)
self.entry_username = tk.Entry(login_frame, width=15, font=("Helvetica", 20), bd=3)
self.entry_username.grid(row=50, column=30, padx=10, pady=10)
self.label_password = tk.Label(login_frame, text="Password", font=("Helvetica", 20), bg="white")
self.label_password.grid(row=60, column=20, padx=10, pady=10)
self.entry_password = tk.Entry(login_frame, width=15, font=("Helvetica", 20), bd=3)
self.entry_password.grid(row=60, column=30, padx=10, pady=10)
#print(self.entry_username.get())
if(self.entry_username.get()=="admin"):
self.login_button = tk.Button(login_frame, text="Log In", command=lambda:[self.submit(),controller.show_frame(AdminPage)],font=("Helvetica", 20), bg="white")
self.login_button.grid(row=70, column=25, padx=10, pady=10)
else:
self.login_button = tk.Button(login_frame, text="Log In", command=lambda:[self.submit(),controller.show_frame(StaffPage)],font=("Helvetica", 20), bg="white")
self.login_button.grid(row=70, column=25, padx=10, pady=10)
def submit(self):
self.u_name = self.entry_username.get()
self.p_word = self.entry_password.get()
employee = mysql.connector.connect(host="localhost", user="root", password="", database="edatabase")
cursor_variable = employee.cursor()
cursor_variable.execute("INSERT INTO login VALUES ('" + self.u_name + "','" + self.p_word + "')")
employee.commit()
employee.close()
class AdminPage(BasePage):
def __init__(self,parent,controller):
super().__init__(parent, controller)
admin_window = tk.Frame(self, width=200, height=100, background="white")
admin_window.grid(row=50, column=150, padx=300, pady=100)
self.label_title_admin = tk.Label(admin_window, text="Welcome Admin", font=("Helvetica", 40), bg="white")
self.label_title_admin.grid(row=0, column=0, padx=10, pady=10, sticky='W')
admin_add = tk.Frame(admin_window, width=100, height=50)
admin_add.grid(row=55, column=0, padx=50, pady=50)
self.admin_add_Image = tk.PhotoImage(file="images\\add3.png")
self.admin_add_Image_Pack = tk.Label(admin_add, image=self.admin_add_Image)
self.admin_add_Image_Pack.grid()
self.add_staff_button = tk.Button(admin_window, text="Add Staff", width=15, font=("Helvetica", 12))
self.add_staff_button.grid(row=60, column=0, pady=20)
admin_delete = tk.Frame(admin_window, width=100, height=50)
admin_delete.grid(row=55, column=10, padx=50, pady=50)
self.admin_delete_Image = tk.PhotoImage(file="images\\delete2.png")
self.admin_delete_Image_Pack = tk.Label(admin_delete, image=self.admin_delete_Image)
self.admin_delete_Image_Pack.grid()
self.delete_staff_button = tk.Button(admin_window, text="Remove Staff", width=15, font=("Helvetica", 12))
self.delete_staff_button.grid(row=60, column=10, pady=20)
admin_select = tk.Frame(admin_window, width=100, height=50)
admin_select.grid(row=55, column=20, padx=50, pady=50)
self.admin_select_Image = tk.PhotoImage(file="images\\select2.png")
self.admin_select_Image_Pack = tk.Label(admin_select, image=self.admin_select_Image)
self.admin_select_Image_Pack.grid()
self.select_staff_button = tk.Button(admin_window, text="Select Staff", width=15, font=("Helvetica", 12))
self.select_staff_button.grid(row=60, column=20, pady=20)
admin_display = tk.Frame(admin_window, width=100, height=50)
admin_display.grid(row=55, column=30, padx=50, pady=50)
self.admin_display_Image = tk.PhotoImage(file="images\\display1.png")
self.admin_display_Image_Pack = tk.Label(admin_display, image=self.admin_display_Image)
self.admin_display_Image_Pack.grid()
self.display_staff_button = tk.Button(admin_window, text="Display Staff", width=15, font=("Helvetica", 12))
self.display_staff_button.grid(row=60, column=30, pady=20)
class StaffPage(BasePage):
def __init__(self,parent,controller):
super().__init__(parent, controller)
staff_window = tk.Frame(self, width=200, height=100, background="white", highlightbackground="black",highlightthickness=1)
staff_window.grid(row=50, column=150, padx=300, pady=100)
self.label_title_staff = tk.Label(staff_window, text="Welcome Staff", font=("Helvetica", 40), bg="white")
self.label_title_staff.grid(row=0, column=0, padx=10, pady=10, sticky='W')
staff_register = tk.Frame(staff_window, width=100, height=50)
staff_register.grid(row=55, column=0, padx=50, pady=50)
self.register_Image = tk.PhotoImage(file="images\\register1.png")
self.register_Image_Pack = tk.Label(staff_register, image=self.register_Image)
self.register_Image_Pack.grid()
self.register_staff_button = tk.Button(staff_window, text="Add Details", width=15, font=("Helvetica", 12))
self.register_staff_button.grid(row=60, column=0, pady=20)
staff_display = tk.Frame(staff_window, width=100, height=50)
staff_display.grid(row=55, column=30, padx=50, pady=50)
self.staff_display_Image = tk.PhotoImage(file="images\\display1.png")
self.staff_display_Image_Pack = tk.Label(staff_display, image=self.staff_display_Image)
self.staff_display_Image_Pack.grid()
self.display_staff_button = tk.Button(staff_window, text="Display Details", width=15, font=("Helvetica", 12))
self.display_staff_button.grid(row=60, column=30, pady=20)
app = SchoolApp()
app.mainloop()
This is my log in page code
class LogIn(BasePage):
def __init__(self,parent,controller):
super().__init__(parent, controller)
login_window = tk.Frame(self, width=200, height=100, background="white")
login_window.grid(row=50, column=150, padx=300, pady=100)
login_img_frame = tk.Frame(login_window, width=200, height=50, background="white")
login_img_frame.grid(row=55, column=0, padx=50, pady=50)
self.login_Image = tk.PhotoImage(file="images\\lock3.png")
self.login_Image_Pack = tk.Label(login_img_frame, image=self.login_Image)
self.login_Image_Pack.grid()
login_frame = tk.Frame(login_window, width=100, height=50, background="white", highlightbackground="black",highlightthickness=1)
login_frame.grid(row=55, column=10, padx=50, pady=50)
self.label_title = tk.Label(login_frame, text="Log In", font=("Helvetica", 40), bg="white")
self.label_title.grid(row=0, column=20, padx=10, pady=10)
self.label_username = tk.Label(login_frame, text="Username", font=("Helvetica", 20), bg="white")
self.label_username.grid(row=50, column=20, padx=10, pady=10)
self.entry_username = tk.Entry(login_frame, width=15, font=("Helvetica", 20), bd=3)
self.entry_username.grid(row=50, column=30, padx=10, pady=10)
self.label_password = tk.Label(login_frame, text="Password", font=("Helvetica", 20), bg="white")
self.label_password.grid(row=60, column=20, padx=10, pady=10)
self.entry_password = tk.Entry(login_frame, width=15, font=("Helvetica", 20), bd=3)
self.entry_password.grid(row=60, column=30, padx=10, pady=10)
#print(self.entry_username.get())
if(self.entry_username.get()=="admin"):
self.login_button = tk.Button(login_frame, text="Log In", command=lambda:[self.submit(),controller.show_frame(AdminPage)],font=("Helvetica", 20), bg="white")
self.login_button.grid(row=70, column=25, padx=10, pady=10)
else:
self.login_button = tk.Button(login_frame, text="Log In", command=lambda:[self.submit(),controller.show_frame(StaffPage)],font=("Helvetica", 20), bg="white")
self.login_button.grid(row=70, column=25, padx=10, pady=10)
def submit(self):
self.u_name = self.entry_username.get()
self.p_word = self.entry_password.get()
employee = mysql.connector.connect(host="localhost", user="root", password="", database="edatabase")
cursor_variable = employee.cursor()
cursor_variable.execute("INSERT INTO login VALUES ('" + self.u_name + "','" + self.p_word + "')")
employee.commit()
employee.close()
I have no errors. Whether it's admin or staff the else condition works and staff page is getting displayed.
Any help is highly appreciated.
I modified the class LogIn(BasePage) as follows and it works. I changed the submit(self) to submit(self,controller).
Thank you everyone for your response.
class LogIn(BasePage):
def __init__(self,parent,controller):
super().__init__(parent, controller)
login_window = tk.Frame(self, width=200, height=100, background="white")
login_window.grid(row=50, column=150, padx=300, pady=100)
login_img_frame = tk.Frame(login_window, width=200, height=50, background="white")
login_img_frame.grid(row=55, column=0, padx=50, pady=50)
self.login_Image = tk.PhotoImage(file="images\\lock3.png")
self.login_Image_Pack = tk.Label(login_img_frame, image=self.login_Image)
self.login_Image_Pack.grid()
login_frame = tk.Frame(login_window, width=100, height=50, background="white", highlightbackground="black",highlightthickness=1)
login_frame.grid(row=55, column=10, padx=50, pady=50)
self.label_title = tk.Label(login_frame, text="Log In", font=("Helvetica", 40), bg="white")
self.label_title.grid(row=0, column=20, padx=10, pady=10)
self.label_username = tk.Label(login_frame, text="Username", font=("Helvetica", 20), bg="white")
self.label_username.grid(row=50, column=20, padx=10, pady=10)
self.entry_username = tk.Entry(login_frame, width=15, font=("Helvetica", 20), bd=3)
self.entry_username.grid(row=50, column=30, padx=10, pady=10)
self.label_password = tk.Label(login_frame, text="Password", font=("Helvetica", 20), bg="white")
self.label_password.grid(row=60, column=20, padx=10, pady=10)
self.entry_password = tk.Entry(login_frame, width=15, font=("Helvetica", 20), bd=3)
self.entry_password.grid(row=60, column=30, padx=10, pady=10)
#print(self.entry_username.get())
self.login_button = tk.Button(login_frame, text="Log In", command=lambda:self.submit(controller),font=("Helvetica", 20), bg="white")
self.login_button.grid(row=70, column=25, padx=10, pady=10)
def submit(self,controller):
self.u_name = self.entry_username.get()
self.p_word = self.entry_password.get()
employee = mysql.connector.connect(host="localhost", user="root", password="", database="edatabase")
cursor_variable = employee.cursor()
cursor_variable.execute("INSERT INTO login VALUES ('" + self.u_name + "','" + self.p_word + "')")
employee.commit()
employee.close()
if (self.u_name== "admin"):
controller.show_frame(AdminPage)
else:
controller.show_frame(StaffPage)

Having some trouble using geometry manager .grid in tkinter

I have some code here and I can't figure out why everything is getting smashed together. Also with the function I have, it isn't getting the actual text that I type into the Text widget. I'm a semi-newbie to Python and have been developing this game for a while.
def comments():
root = tk.Tk()
root.title("Comments")
root.geometry("300x200+300+300")
var = tk.IntVar()
top_frame = tk.Frame(root, bg="red", width=300, height=50)
name_label = tk.Label(top_frame, text="Username", bg='red', fg="yellow", font=("arial, 17"), justify=LEFT)
name_entry = tk.Entry(top_frame)
comment_frame = tk.Frame(root, bg="yellow", width=300, height=100, relief=GROOVE)
comment_entry = tk.Text(comment_frame, bd=2, relief=SUNKEN, width=35, height=5)
comment = comment_entry.get('1.0', 'end-1c')
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()
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')
submit_button = tk.Button(like_dislike_frame, text="Submit", command=save_comment)
top_frame.grid(row=0, column=0, columnspan=3)
name_label.grid(row=0, sticky=W, padx="5px")
name_entry.grid(row=0, sticky=E, padx="5px")
comment_frame.grid(row=1, column=0, columnspan=3)
comment_entry.grid(row=1, column=0, sticky=E)
like_dislike_frame.grid(row=2, columnspan=2)
like_button.grid(row=2, sticky=W, padx="6px")
dislike_button.grid(row=2, padx="6px")
submit_button.grid(row=2, sticky=E)
root.mainloop()**
Basically you haven't specified unique row/column numbers for most of your widgets.
Each frame has its own row/grid system so you can place a frame at row=0 column=0. If that frame then has two widget inside it, one to the right of the other you'd use row=0 column=0, row=0 column=1 for each widget respectively.
I looked at the like/dislike frame and specified a column for each of those
like_button.grid(row=0,column=0, sticky=W, padx="6px")
dislike_button.grid(row=0,column=1, padx="6px")
submit_button.grid(row=0,column=2, sticky=E)
They now appear spaced out correctly.

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()

How Can I write Python code for Temperature Convert to C orF using Frames, Entry Box and Label?

from tkinter import*
def convert2c():
try:
f = float(tempIN.get())
c = (f-32)*5.0/9.0
tempOUTc.set(c)
except ValueError:
pass
def convert2f():
try:
c = float(tempIN.get())
f = c*9.0/5.0 + 32
tempOUTf.set(f)
except ValueError:
pass
root = Tk()
f = root
root.title("Temperature Converter")
root.geometry('{}x{}'.format(500,200))
topFrm = Frame(root, width=500, height=80, bg="#e01111")
midFrm = Frame(root, width=500, height=150, bg="#795fb5")
btmFrm = Frame(root, width=500, height=100)
btmL = Frame(btmFrm, width=250, height=100, bg="#4117a5")
btmR = Frame(btmFrm, width=250, height=100, bg="#3f454f")
topFrm.grid(row=0, sticky="W")
midFrm.grid(row=1)
btmFrm.grid(row=3)
btmL.grid(row=2, column=0)
btmR.grid(row=2, column=2)
tempIN = StringVar()
tempOUTc = StringVar()
tempOUTf = StringVar()
Label(f, text="Temperature Converter\n A number in temperature degree is converted into another as one of the button is clicked").grid(column=0, row=0)
Label(f, text="Enter a Temperature").grid(column=0, row=1)
Entry(f, textvariable=tempIN, width=10) .grid(column=0, rowspan=1, row=1, sticky=W)
Button(f, text=" to Celsius", command=convert2c) .grid(column=0, row=3, sticky=W)
Button(f, text=" to Fahrenheit", command=convert2f) .grid(column=1, row=3, sticky=W)
Label(f, textvariable=tempOUTc) .grid(column=2, row=1, sticky=W)
Label(f, textvariable=tempOUTf) .grid(column=2, row=2, sticky=W)
root.mainloop()

Resources