I wanted to write a code that will check the availability of sites using "status_code"
But in the end I got into a stupor, I do not know how to implement the verification of each site entered into the widgets
I manage to check only one site from one widget, but I need to check each one, and set a time for each site to check
I would like to know, or at least get hints on how to implement it
I will be grateful for any help
My attempt:
import tkinter as tk
from tkinter import ttk
import requests
import time
from tkinter import *
from tkinter import messagebox
window = Tk()
window.geometry('400x700')
window.title("SiteChecker")
def SiteCheck():
res=int(tim1.get())
Site_Value = txt1.get()
Get_Response = requests.get(Site_Value)
time.sleep(res)
if Get_Response.status_code != 200:
#as I understand it, you need to make a "for" loop, but I don't understand how to implement
def clicked():
txt = Entry(window, width=18)
txt.grid(column=0, pady=8)
txt_row = txt.grid_info()['row']
tim = Entry(window, width=3)
tim.grid(row=txt_row, column=1, pady=8)
lbl1 = Label(window, text="Enter references:")
lbl1.grid(column=0, row=1)
lbl2 = Label(window, text="Enter the test time: ")
lbl2.grid(column=1, row=1)
lbl3 = Label(window, text="Availability status ")
lbl3.grid(column=2, row=1)
txt1 = Entry(window,width=18)
txt1.grid(column=0, row=2, pady=8)
txt2 = Entry(window,width=18)
txt2.grid(column=0, row=3,pady=8)
txt3 = Entry(window,width=18)
txt3.grid(column=0, row=4,pady=8)
txt4 = Entry(window,width=18)
txt4.grid(column=0, row=5,pady=8)
txt5 = Entry(window,width=18)
txt5.grid(column=0, row=6,pady=8)
tim1 = Entry(window,width=3)
tim1.grid(column=1, row=2, pady=8)
tim2 = Entry(window,width=3)
tim2.grid(column=1, row=3, pady=8)
tim3 = Entry(window,width=3)
tim3.grid(column=1, row=4, pady=8)
tim4 = Entry(window,width=3)
tim4.grid(column=1, row=5, pady=8)
tim5 = Entry(window,width=3)
tim5.grid(column=1, row=6, pady=8)
result1 = Label(window,text="status")
result1.grid(column=2, row=2, pady=8)
result2 = Label(window,text="status")
result2.grid(column=2, row=3, pady=8)
result3 = Label(window,text="status")
result3.grid(column=2, row=4, pady=8)
result4 = Label(window,text="status")
result4.grid(column=2, row=5, pady=8)
result5 = Label(window,text="status")
result5.grid(column=2, row=6, pady=8)
btn = Button(window, text="Add another site", command=clicked)
btn.grid(column=1, row = 0)
Check_Button = Button(
window,
command = SiteCheck,
text='Start checking',
)
Check_Button.grid(row=0, column=2)
window.mainloop()
try this but i am do it without time sleep you can add later
import tkinter as tk
from tkinter import ttk
import requests
import time
from tkinter import *
from tkinter import messagebox
data_list = []
window = Tk()
window.geometry('400x700')
window.title("SiteChecker")
def set_input(obj, value):
obj.delete(1.0, "END")
obj.insert("END", value)
def SiteCheck():
#res=int(tim1.get())
#time.sleep(res)
for data in data_list:
url = data[0].get()
status = data[2]
if not str(url).startswith('http'):
continue
print(url)
Get_Response = None
try:
Get_Response = requests.get(url)
except:
status.config(text = 'status bad')
continue
if Get_Response.status_code == 200:
status.config(text = 'status ok')
pass
#as I understand it, you need to make a "for" loop, but I don't understand how to implement
else:
status.config(text = 'status bad')
def clicked():
txt = Entry(window, width=18)
txt.grid(column=0, pady=8)
txt_row = txt.grid_info()['row']
tim = Entry(window, width=3)
tim.grid(row=txt_row, column=1, pady=8)
txt_row = tim.grid_info()['row']
result1 = Label(window,text="status")
result1.grid(row=txt_row, column=2, pady=8)
data_list.append([txt, tim, result1])
lbl1 = Label(window, text="Enter references:")
lbl1.grid(column=0, row=1)
lbl2 = Label(window, text="Enter the test time: ")
lbl2.grid(column=1, row=1)
lbl3 = Label(window, text="Availability status ")
lbl3.grid(column=2, row=1)
for loop in range(2 ,6):
txt1 = Entry(window,width=18)
txt1.grid(column=0, row=loop, pady=8)
tim1 = Entry(window,width=3)
tim1.grid(column=1, row=loop, pady=8)
result1 = Label(window,text="status")
result1.grid(column=2, row=loop, pady=8)
data_list.append([txt1, tim1, result1])
btn = Button(window, text="Add another site", command=clicked)
btn.grid(column=1, row = 0)
Check_Button = Button(
window,
command = SiteCheck,
text='Start checking',
)
Check_Button.grid(row=0, column=2)
window.mainloop()
Related
I started working on the code, and when I put the widgets in places, there was a problem, the widgets move down
I.e. on pressing the button that adds more "entry" fields
they appear very crooked, and I do not know why, what to do with this, and what I did wrong?
1: https://i.stack.imgur.com/b8DBm.png - a picture of my problem
import tkinter as tk
from tkinter import ttk
import requests
import time
from tkinter import *
from tkinter import messagebox
window = Tk()
window.geometry('400x700')
window.title("SiteChecker")
def clicked():
txt = Entry(window, width=18)
txt.grid(column=0, pady=8)
tim = Entry(window, width=3)
tim.grid(column=1, pady=8)
lbl1 = Label(window, text="Enter links: ")
lbl1.grid(column=0, row=1)
lbl2 = Label(window, text="Enter the test time: ")
lbl2.grid(column=1, row=1)
lbl3 = Label(window, text="Availability status ")
lbl3.grid(column=2, row=1)
txt1 = Entry(window,width=18)
txt1.grid(column=0, row=2, pady=8)
txt2 = Entry(window,width=18)
txt2.grid(column=0, row=3,pady=8)
txt3 = Entry(window,width=18)
txt3.grid(column=0, row=4,pady=8)
txt4 = Entry(window,width=18)
txt4.grid(column=0, row=5,pady=8)
txt5 = Entry(window,width=18)
txt5.grid(column=0, row=6,pady=8)
tim1 = Entry(window,width=3)
tim1.grid(column=1, row=2, pady=8)
tim2 = Entry(window,width=3)
tim2.grid(column=1, row=3, pady=8)
tim3 = Entry(window,width=3)
tim3.grid(column=1, row=4, pady=8)
tim4 = Entry(window,width=3)
tim4.grid(column=1, row=5, pady=8)
tim5 = Entry(window,width=3)
tim5.grid(column=1, row=6, pady=8)
btn = Button(window, text="Add more site", command=clicked)
btn.grid(column=1, row = 0)
window.mainloop()
The new line isn't "crooked." The second Entry widget is being placed on the next row, because the row value auto-increments in calls to .grid() if not declared.
You could just keep track of on which row you want to place the new pair of widgets. Or, you can place the first one, which works as expected. Then ask the layout manager on which row it placed the first one, and then place the second widget on that same row.
Here's the code that does that:
def clicked():
txt = Entry(window, width=18)
txt.grid(column=0, pady=8)
txt_row = txt.grid_info()['row'] # the row the widget was mapped onto
tim = Entry(window, width=3)
tim.grid(row=txt_row, column=1, pady=8) # put the 2nd widget on the same row
Below is a small code where if you click add button a pop-up will appear where you write desired number. The number in the bottom represents the sum of all numbers you entered.
What I am trying to achieve is to update the sum_lbl and index_no as I delete any of the labels.
Code:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = []
index_no = 0
def destroy(widget):
widget.destroy()
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
while True:
def ok_():
global index_no
name = add_room_area_var.get()
index_no += 1
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=index_no)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:destroy(entry_frame))
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
area_lst.append(int(name))
add_room_area.destroy()
area_sum = sum(area_lst)
sum_lbl.config(text=area_sum)
break
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()
Output:
After deleting the 3rd and 4th label the output is:
I would suggest to change area_lst to dictionary using the frame as the key and the two labels as the value for each row.
Then update destroy() to use area_lst to update the total and indexes:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = {} # dictionary to hold labels of each row using frame as the key
def destroy(frame):
frame.destroy()
del area_lst[frame]
update_total()
# update index of remaining rows
for idx, (lbl, _) in enumerate(area_lst.values(), 1):
lbl['text'] = idx
# function to update the total label
def update_total():
area_sum = sum(int(room['text']) for _, room in area_lst.values())
sum_lbl.config(text=area_sum)
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
def ok_():
name = add_room_area_var.get()
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=len(area_lst)+1)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:destroy(entry_frame))
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
# store current row to area_lst
area_lst[entry_frame] = (index_lbl, add_room_lbl)
add_room_area.destroy()
update_total()
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()
You can allow buttons to call multiple commands, so for your 'close_button' button, I added two more commands: remove the name from 'area_lst' and update the 'sum_lbl' text with the new sum for 'area_lst'
Like this:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = []
index_no = 0
def destroy(widget):
widget.destroy()
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
while True:
def ok_():
global index_no
name = add_room_area_var.get()
index_no += 1
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=index_no)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:[destroy(entry_frame), area_lst.remove(int(name)), sum_lbl.config(text=sum(area_lst))])
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
area_lst.append(int(name))
add_room_area.destroy()
area_sum = sum(area_lst)
sum_lbl.config(text=area_sum)
break
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()
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()
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()
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