Is it possible to bind without using the class? - python-3.x

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!

Related

Tkinter Function

I am new to programming and just started learning python and Tkinter.
Since I am more of a visual and try and error learner I made a personal project which is a Scoreboard.
I created the interface and know that i need to change the label textvariables.
The problem where I am stuck is that I just cant get to understand how to get numbers that appear above the ok btn to display final score and clear once the ok btn is pressed. Another problem thatI have is that when the - btn is choosen how do I put the - before the int even though it is pressed after a number has been inserted and then subtracted from final score. I know code is a bit rough and could def be done better, but i repeat it is a 1st personal project.
Thank You
from tkinter import \*
import tkinter as tk
import ttkbootstrap as ttk
from ttkbootstrap.constants import \*
root = ttk.Window(themename="darkly")
root.resizable(0, 0)
def btn_click(item):
global expression
expression = expression + str(item)
input_text.set(expression)
def bt_clear():
global expression
expression = ""
input_text.set("")
expression = ""
input_text = StringVar()
root.title("")
root.iconbitmap("")
lbl_title = Label(root, text="",font=("", 14))
lbl_title.grid(row=0, column=6)
\#CLR SCOREBOARD
clr_scoreboard = Button(root, text="CLEAR SCOREBOARD", command=NONE).grid(row=6, column=6)
\#PLAYER1SIDE SETUP
\#PLAYER1SCORE
lbl_p1score = tk.Label(root, textvariable=p1score, font=("", 110))
lbl_p1score.grid(row=1, columnspan=3)
\#PLAYER1 INPUT
lbl1_p1points = Label(root, textvariable= input_text, font=("", 50))
lbl1_p1points.grid(row=3, column=4)
\#PLAYER1 BTNS
p1btn1 = Button(root, text = "1", font=("", 14), command = lambda: btn_click(1), height=4, width=8)
p1btn1.grid(row=2, column=0, padx=1, pady=1)
p1btn2 = Button(root, text = "2", font=("", 14), command = lambda: btn_click(2), height=4, width=8)
p1btn2.grid(row=2, column=1, padx=1, pady=1)
p1btn3 = Button(root, text = "3", font=("", 14), command = lambda: btn_click(3), height=4, width=8)
p1btn3.grid(row=2, column=2, padx=1, pady=1)
p1btn4 = Button(root, text = "4", font=("", 14), command = lambda: btn_click(4), height=4, width=8)
p1btn4.grid(row=3, column=0, padx=1, pady=1)
p1btn5 = Button(root, text = "5", font=("", 14), command = lambda: btn_click(5), height=4, width=8)
p1btn5.grid(row=3, column=1, padx=1, pady=1)
p1btn6 = Button(root, text = "6", font=("", 14), command = lambda: btn_click(6), height=4, width=8)
p1btn6.grid(row=3, column=2, padx=1, pady=1)
p1btn7 = Button(root, text = "7", font=("", 14), command = lambda: btn_click(7), height=4, width=8)
p1btn7.grid(row=4, column=0, padx=1, pady=1)
p1btn8 = Button(root, text = "8", font=("", 14), command = lambda: btn_click(8), height=4, width=8)
p1btn8.grid(row=4, column=1, padx=1, pady=1)
p1btn9 = Button(root, text = "9", font=("", 14), command = lambda: btn_click(9), height=4, width=8)
p1btn9.grid(row=4, column=2, padx=1, pady=1)
p1btn0 = Button(root, text = "0", font=("", 14), command = lambda: btn_click(0), height=4, width=8)
p1btn0.grid(row=5, column=1, padx=1, pady=1)
p1btnclear = Button(root, text = "C", font=("", 14), command = bt_clear, height=4, width=8)
p1btnclear.grid(row=5, column=2, padx=1, pady=1)
p1btnminus = Button(root, text = "-", font=("", 14), command = lambda: btn_click("-"), height=4, width=8)
p1btnminus.grid(row=5, column=0, padx=1, pady=1)
\#PLAYER1 OK BTN INPUT
p1btnok = Button(root, text = "OK", font=("", 14), command = lambda: p1_score, height=4, width=8, padx=100)
p1btnok.grid(row=5, column=4, padx=1, pady=1)
\#PLAYER1 SET INDICATORS
lbl_setp1= Label(root, text="0", font=("", 14))
lbl_setp1.grid(row=1, column=5)
btn_setp1plus = Button(root, text = "+", command = None, height=2, width=4)
btn_setp1plus.grid(row = 2, column = 5)
btn_setp1minus = Button(root, text = "-", command = None, height=2, width=4)
btn_setp1minus.grid(row = 3, column = 5)
lbl_set=Label(root, text="SET", font=("", 14))
lbl_set.grid(row=1, column=6)
\#PLAYER 2 SIDE SETUP
\#PLAYER2 SET INDICATORS
lbl_setp2= Label(root, text="0", font=("", 14))
lbl_setp2.grid(row=1, column=7)
btn_setp2plus = Button(root, text = "+", command = None, height=2, width=4)
btn_setp2plus.grid(row = 2, column = 7)
btn_setp2minus = Button(root, text = "-", command = None, height=2, width=4)
btn_setp2minus.grid(row = 3, column = 7)
\#PLAYER2 POINTS
lbl2_p1points = Label(root, text="112", font=("", 50))
lbl2_p1points.grid(row=3, column=8)
\#PLAYER2 OK BTN INPUT
p2btnok = Button(root, text = "OK", font=("", 14), command = None, height=4, width=8, padx=100)
p2btnok.grid(row=5, column=8, padx=1, pady=1)
\#PLAYER2 SCORE
lbl_p2score = Label(root, text="500", font=("", 110))
lbl_p2score.config(fg="yellow")
lbl_p2score.grid(row=1, column=9, columnspan=11)
\#PLAYER2 BTNS
p2btn1 = Button(root, text = "1", font=("", 14), command = None, height=4, width=8)
p2btn1.grid(row=2, column=9, padx=1, pady=1)
p2btn2 = Button(root, text = "2", font=("", 14), command = None, height=4, width=8)
p2btn2.grid(row=2, column=10, padx=1, pady=1)
p2btn3 = Button(root, text = "3", font=("", 14), command = None, height=4, width=8)
p2btn3.grid(row=2, column=11, padx=1, pady=1)
p2btn4 = Button(root, text = "4", font=("", 14), command = None, height=4, width=8)
p2btn4.grid(row=3, column=9, padx=1, pady=1)
p2btn5 = Button(root, text = "5", font=("", 14), command = None, height=4, width=8)
p2btn5.grid(row=3, column=10, padx=1, pady=1)
p2btn6 = Button(root, text = "6", font=("", 14), command = None, height=4, width=8)
p2btn6.grid(row=3, column=11, padx=1, pady=1)
p2btn7 = Button(root, text = "7", font=("", 14), command = None, height=4, width=8)
p2btn7.grid(row=4, column=9, padx=1, pady=1)
p2btn8 = Button(root, text = "8", font=("", 14), command = None, height=4, width=8)
p2btn8.grid(row=4, column=10, padx=1, pady=1)
p2btn9 = Button(root, text = "9", font=("", 14), command = None, height=4, width=8)
p2btn9.grid(row=4, column=11, padx=1, pady=1)
p2btn0 = Button(root, text = "0", font=("", 14), command = None, height=4, width=8)
p2btn0.grid(row=5, column=10, padx=1, pady=1)
p2btnclear = Button(root, text = "C", font=("", 14), command = None, height=4, width=8)
p2btnclear.grid(row=5, column=9, padx=1, pady=1)
p2btnminus = Button(root, text = "-", font=("", 14), command = None, height=4, width=8)
p2btnminus.grid(row=5, column=11, padx=1, pady=1)
root.mainloop()

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)

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

First tkinter program

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

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