Update tkinter canvas widget on button click - python-3.x

I am trying to call a function on a button click which will call second function that updates the fill color of an oval. I am getting an error that the object doesnt have the attribute. The goal of the program will be to eventually update the the signal light colors as variables linked to each go from 0 to 1 but right now i'm just getting the back end working. I have looked at dozens of examples over the last two days and cant get this to work.
import tkinter as tk
class WaysideSimulator(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
# self.pack()
self.grid()
self.create_widgets()
def create_widgets(self):
# Draw Buttons
self.Start_Simulation_Button = tk.Button(self, text="Start Simulation", command=self.start_simulation)
self.Start_Simulation_Button.grid(row=0, column=0)
self.End_Simulation_Button = tk.Button(self, text="End Simulation", fg="red", command=self.master.destroy)
self.End_Simulation_Button.grid(row=1, column=0)
# Top Signal Buttons
self.Top_Red_Button = tk.Button(self, text="Set Top Signal Red", command=self.set_top_red)
self.Top_Red_Button.grid(row=2, column=0)
self.Top_Yellow_Button = tk.Button(self, text="Set Top Signal Yellow", command=self.set_top_yellow)
# self.Searchlight_Button.pack(side="bottom")
self.Top_Yellow_Button.grid(row=3, column=0)
self.Top_Green_Button = tk.Button(self, text="Set Top Signal Green", command=self.set_top_green)
self.Top_Green_Button.grid(row=4, column=0)
self.Top_Black_Button = tk.Button(self, text="Set Top Signal Black", command=self.set_top_off)
self.Top_Black_Button.grid(row=5, column=0)
# Middle Signal Buttons
self.Middle_Red_Button = tk.Button(self, text="Set Middle Signal Red", command=self.set_middle_red)
self.Middle_Red_Button.grid(row=2, column=1)
self.Middle_Yellow_Button = tk.Button(self, text="Set Middle Signal Yellow", command=self.set_middle_yellow)
self.Middle_Yellow_Button.grid(row=3, column=1)
self.Middle_Green_Button = tk.Button(self, text="Set Middle Signal Green", command=self.set_middle_green)
self.Middle_Green_Button.grid(row=4, column=1)
self.Middle_Black_Button = tk.Button(self, text="Set Middle Signal Black", command=self.set_middle_black)
self.Middle_Black_Button.grid(row=5, column=1)
# Bottom Signal Buttons
self.Bottom_Red_Button = tk.Button(self, text="Set Bottom Signal Red", command=self.set_bottom_red)
self.Bottom_Red_Button.grid(row=2, column=2)
self.Bottom_Yellow_Button = tk.Button(self, text="Set Bottom Signal Yellow", command=self.set_bottom_yellow)
self.Bottom_Yellow_Button.grid(row=3, column=2)
self.Bottom_Green_Button = tk.Button(self, text="Set Bottom Signal Green", command=self.set_bottom_green)
self.Bottom_Green_Button.grid(row=4, column=2)
self.Bottom_Black_Button = tk.Button(self, text="Set Bottom Signal Black", command=self.set_bottom_black)
self.Bottom_Black_Button.grid(row=5, column=2)
# Draw the Canvas
self.canvas = tk.Canvas(self, width=500, height=500, bg="white")
self.canvas.grid()
# Draw the Searchlight Signal Heads
self.signal_pole = self.canvas.create_rectangle(245, 20, 255, 500, fill="grey")
self.top_signal_head = self.canvas.create_oval(200, 10, 300, 110, fill="black")
self.middle_signal_head = self.canvas.create_oval(200, 160, 300, 260, fill="black")
self.bottom_signal_head = self.canvas.create_oval(200, 310, 300, 410, fill="black")
self.top_signal_light = self.canvas.create_oval(240, 50, 260, 70, fill="red", tags="top_light")
self.top_signal_light_ON = True
self.middle_signal_light_ON = self.canvas.create_oval(240, 200, 260, 220, fill="yellow", tags="middle_light")
self.middle_light_ON = True
self.bottom_signal_light = self.canvas.create_oval(240, 350, 260, 370, fill="green", tags="bottom_light")
self.bottom_signal_light_ON = True
# Function Definitions
def set_top_red(self):
self.canvas.itemconfig("top_light", fill="Red")
self.top_signal_light_ON = True
print("Top signal is RED")
def set_top_yellow(self):
self.canvas.itemconfig("top_light", fill="yellow")
self.top_signal_light_ON = True
print("Top signal is YELLOW")
def set_top_green(self):
self.canvas.itemconfig("top_light", fill="green")
self.top_signal_light_ON = True
print("Top signal is GREEN.")
def set_top_off(self):
self.canvas.itemconfig("top_light", fill="black")
self.top_signal_light_ON = False
print("Top signal is OFF.")
def set_middle_red(self):
self.canvas.itemconfig("middle_light", fill="Red")
self.middle_light_ON = True
print("Middle signal is RED")
def set_middle_yellow(self):
self.canvas.itemconfig("middle_light", fill="yellow")
self.middle_light_ON = True
print("middle signal is YELLOW")
def set_middle_green(self):
self.canvas.itemconfig("middle_light", fill="green")
self.middle_light_ON = True
print("Middle signal is GREEN.")
def set_middle_black(self):
self.canvas.itemconfig("middle_light", fill="black")
self.middle_light_ON = False
print("Middle signal is OFF.")
def set_bottom_red(self):
self.canvas.itemconfig("bottom_light", fill="Red")
self.middle_light_ON = True
print("Bottom signal is RED")
def set_bottom_yellow(self):
self.canvas.itemconfig("bottom_light", fill="yellow")
self.middle_light_ON = True
print("Bottom signal is YELLOW")
def set_bottom_green(self):
self.canvas.itemconfig("bottom_light", fill="green")
self.middle_light_ON = True
print("Bottom signal is GREEN.")
def set_bottom_black(self):
self.canvas.itemconfig("bottom_light", fill="black")
self.middle_light_ON = False
print("Bottom signal is OFF.")
# Simulation Functions
def start_simulation(self):
print("Searchlight Simulation Started")
self.canvas.itemconfig("top_light", fill="black")
self.canvas.itemconfig("middle_light", fill="black")
self.canvas.itemconfig("bottom_light", fill="black")
self.top_signal_light_ON = False
self.middle_signal_light_ON = False
self.bottom_signal_light_ON = False
print("All signals are OFF")
def main():
root = tk.Tk()
root.title("Searchlight Simulator")
root.geometry("500x650")
# root.resizable(0, 0)
s1 = WaysideSimulator(master=root)
s1.mainloop()
if __name__ == '__main__':
main()

Related

theard not responding while in mainloop

I'm working on a project where when a button is press in my controller a string needs to appear on the GUI. so I used threading, pyserial and tkinter for the mission but everytime I press the button in my controller it doesnt work after mainloop works, send text to the controller works, the terminal is a class I bulit with variable channel for serial
def chat_menu(terminal):
chat_window = Tk()
chat_window.geometry("650x480")
input_text = Text(chat_window, height=20, width=30)
output_text = Text(chat_window, height=20, width=30)
title = Label(chat_window, text="Chat Mode", font=("Arial",
14, "bold"))
title_in = Label(chat_window, text="Input", font=("Arial", 14,
"bold"))
title_out = Label(chat_window, text="Output", font=("Arial",
14, "bold"))
text = input_text.get("1.0", END)
submit_button = Button(chat_window, height=3, width=20,
text="Submit",
font=('Arial', 16, 'bold'),
command=lambda: send_text(terminal, chat_window, input_text))
back_button = Button(chat_window, height=3, width=20,
text='Back', font=('Arial', 16, 'bold'),
command=lambda:
terminal.close_main(chat_window, 'd'))
terminal.data = None
title.grid(row=0, column=1)
input_text.grid(row=1, column=0)
output_text.grid(row=1, column=2)
title_in.grid(row=2, column=0)
title_out.grid(row=2, column=2)
submit_button.grid(row=3, column=0)
back_button.grid(row=3, column=2)
thread = threading.Thread(target=receive_text(terminal,
output_text))
thread.start()
mainloop()
def receive_text(terminal, output):
time.sleep(2)
received = False
while True:
while terminal.channel.in_waiting > 0:
received_dataterminal.channel.read_until(expected='\n')
output.insert(END, received_data.decode("ascii"))
received = True
if received:
break

Hiding a frame depend on textbox value

This is the last stage of my Python file.
What I am attempting to do is have frame 5 unhidden when Textbox2 value is between 2 numeric numbers.
This an piece out of my original 100+ frames file.
I was able to complete this whole file as an Excel file.
I am stuck on the code for Deff onclick 5.
Any help would be greatly appreciated.
Thanks as always!!
from tkinter import *
from tkinter import Tk
import tkinter as tk
from tkinter import ttk
root=tk.Tk()
root.title("Dental Milling Machines")
root.geometry("1000x900")
def onclick5():
if ([textbox2], [">0" and "<10.1"]):
frame5.grid(row=0, column=2, pady=2,sticky="NW")
else:
frame5.grid_forget()
def onclick1():
textbox1.delete('1.0', 'end')
textbox1.insert('end', '2.83')
def onclick2():
textbox1.delete('1.0', 'end')
textbox1.insert('end', '5.66')
def onclick3():
textbox1.delete('1.0', 'end')
textbox1.insert('end', '8.49')
def to_float( string ):
try:
return float( string )
except ValueError:
return 0.0
def onclick4():
tot = 0.0
for box in text_boxes_to_sum:
v = box.get( '1.0', 'end' )
tot += to_float( v )
textbox2.delete( '1.0', 'end' )
textbox2.insert( 'end', str(tot) )
button_var1 = tk.IntVar()
button_var2 = tk.IntVar()
frame1 = Frame(root, height = 150, width= 150, relief= RAISED, bd=8, bg="blue")
frame2 = Frame(frame1, height = 150, width= 150, relief= RAISED, bd=8, bg="lightblue")
frame3 = Frame(frame1, height = 150, width= 150, relief= RAISED, bd=8, bg="lightblue")
frame4 = Frame(frame1, height = 150, width= 150, relief= RAISED, bd=8, bg="lightblue")
frame5 = Frame(frame1, height = 150, width= 150, relief= RAISED, bd=8, bg="lightblue")
textbox1 = Text(frame2, borderwidth=1, wrap="none", width=10, height=2)
textbox1.grid(row=5, column=0, sticky="w")
textbox2 = Text(frame3, borderwidth=1, wrap="none", width=10, height=1)
textbox2.grid(row=1, column=0, sticky="NESW")
textbox3 = Text(frame5, borderwidth=1, wrap="none", width=10, height=1)
textbox3.grid(row=0, column=0, sticky="NESW")
text_boxes_to_sum = [ textbox1 ]
frame1.grid(row=0, column=0, pady=2,sticky="NW")
frame2.grid(row=1, column=0, pady=2,sticky="NW")
label = Label(frame2, text="Select # Of Units Being Used", fg="red")
label.grid(row=0, column=0, pady= 1, padx=1, sticky= "W")
frame3.grid(row=2, column=0, pady=2,sticky="NW")
label = Label(frame3, text="Total CFM Values", fg="red")
label.grid(row=0, column=0, pady= 1, padx=1, sticky= "W")
frame4 = Frame(frame1, height = 150, width= 150, relief= RAISED, bd=0, bg="lightyellow")
frame4.grid(row=8, column=0, pady=2,padx=3, sticky="E")
frame5 = Frame(frame1, height = 150, width= 150, relief= RAISED, bd=0, bg="lightyellow")
label = Label(frame5, text="Reccommended Compressor Package", fg="red")
label.grid(row=0, column=0, pady= 1, padx=1, sticky= "W")
label = Label(frame5, text="Compressor Package 1", fg="black")
label.grid(row=2, column=0, pady= 10, padx=5, sticky= "EW")
button1=Radiobutton(frame2, text="1 Unit ", variable=button_var1, command=onclick1)
button1.grid(row=1, column=0, pady= 1, padx= 5, sticky= "W")
button2=Radiobutton(frame2, text="2 Units ", variable=button_var1, command=onclick2)
button2.grid(row=2, column=0, pady= 1, padx= 5, sticky= "W")
button3=Radiobutton(frame2, text="3 Units ", variable=button_var1, command=onclick3)
button3.grid(row=3, column=0, pady= 1, padx= 5, sticky= "W")
button4=Radiobutton(frame3, text="Show Values ", variable=button_var1, command=onclick4, value = 0 )
button4.grid(row=3, column=0, pady= 1, padx= 5, sticky= "W")
button5=Radiobutton(frame4, text="Show Reccommended Compressor Package ", variable=button_var2, command=onclick5)
button5.grid(row=0, column=0, pady= 1, padx= 5, sticky= "W")
root.mainloop()

Hiding and Unhiding Frames with the use of a Checkbox

I have deleted my previous posts as unusable for OS and would like to start over. As per Kate I have added code that I have tried along with the results. As per Bryan I have shortened script down to a minimal of 1 Checkbox and 1 mainframe and 3 additional frames. Any help would be greatly appreciated. Attached is the code I have used.
from tkinter import *
from tkinter import Tk
import tkinter as tk
from tkinter import ttk
from tkinter import Frame
root=Tk()
root.title("Dental Milling Machines")
root.geometry("400x200")
##Option 1 PRODUSES LINE 14 OBJECT IS NOT CALLABLE #####
#class HideFrames():
#def __init__(Frame):
#self.Frame = Frame()
#def HideFrames_info():
#def Hide():
#if cl is 0():
#Frame3.Hidden = True
#if c1 is 1():
#Frame3.Hidden = False
## Option 2 PRODUCES NO ERROR CODES But the code but will not work #####
class HideFrames():
def __call__(self):
self.Frame = Frame()
def HideFrames_info():
def Hide():
if cl is 0():
Frame3.Hidden = True
if c1 is 1():
Frame3.Hidden = False
#########################################
cb_var1 = tk.IntVar()
frame1 = Frame(root, height = 150, width= 150, relief= RAISED, bd=8, bg="blue")
frame2 = Frame(frame1, height = 150, width= 150, relief= RAISED, bd=8, bg="lightblue")
frame3 = Frame(frame1, height = 150, width= 150, relief= RAISED, bd=8, bg="lightblue")
frame4 = Frame(frame1, height = 150, width= 150, relief= RAISED, bd=8, bg="lightblue")
label = Label(frame3, text="FRAME 3", fg="red")
label.grid(row=0, columnspan=3, pady= 1, sticky= "W")
label = Label(frame4, text="FRAME 4", fg="red")
label.grid(row=0, columnspan=3, pady= 1, sticky= "W")
frame1.grid(row=0, column=0, pady=2,sticky="NW")
frame2.grid(row=1, column=0, pady=2,sticky="NW")
frame3.grid(row=2, column=0, pady=2,sticky="NW")
frame4.grid(row=3, column=0, pady=2,sticky="NW")
c1 = Checkbutton(frame2, text = "Check to SHOW Frame 3 Uncheck to HIDE Frame 3", variable=cb_var1)
c1.grid(row=1, column=0, pady= 1, padx= 5, sticky= "W")
app = HideFrames()
root.mainloop()
Good start. 2 big issues: You need to use the get() method to check the value of a tkinter variable, and you need to make the function run when checkbutton is triggered using the command argument. Try this:
import tkinter as tk
def frame3_disp():
if cb_var1.get():
frame3.grid(row=2, column=0, pady=2,sticky="NW")
else:
frame3.grid_forget()
root = tk.Tk()
root.title("Dental Milling Machines")
root.geometry("400x200")
frame1 = tk.Frame(root, height = 150, width= 150, relief= tk.RAISED, bd=8, bg="blue")
frame2 = tk.Frame(frame1, height = 150, width= 150, relief= tk.RAISED, bd=8, bg="lightblue")
frame3 = tk.Frame(frame1, height = 150, width= 150, relief= tk.RAISED, bd=8, bg="lightblue")
frame4 = tk.Frame(frame1, height = 150, width= 150, relief= tk.RAISED, bd=8, bg="lightblue")
label = tk.Label(frame3, text="FRAME 3", fg="red")
label.grid(row=0, columnspan=3, pady= 1, sticky= "W")
label = tk.Label(frame4, text="FRAME 4", fg="red")
label.grid(row=0, columnspan=3, pady= 1, sticky= "W")
frame1.grid(row=0, column=0, pady=2,sticky="NW")
frame2.grid(row=1, column=0, pady=2,sticky="NW")
frame4.grid(row=3, column=0, pady=2,sticky="NW")
cb_var1 = tk.IntVar()
c1 = tk.Checkbutton(frame2, text = "Check to SHOW Frame 3 Uncheck to HIDE Frame 3", variable=cb_var1, command=frame3_disp)
c1.grid(row=1, column=0, pady= 1, padx= 5, sticky= "W")
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 I can pause a thread for some time in python?

I am working for build a software where I wan't to pause/stop a thread for some time or for a event
here are some essential code to understand you better
self.staff_list_thread = Thread(target = self.get_staff_list, kwargs = {"master": self.frame_staff_list}, daemon = True)
self.staff_list_thread.start()
def get_staff_list(self, master, *args, **kwargs):
def add_staff_button_callback():
self.get_add_staff(self.frame_staff_add)
def detail_edit_staff_button_callback(email):
if email is not None:
self.get_detail_edit_staff(self.frame_staff_detail, email)
row = 1
self.staff_introduction = get_a_label(master, text="This is staff area", row=0, column=0, padx=(10, 10), pady=(10, 10))
self.staff_introduction.config(style="Title.TLabel")
self.add_staff_button = get_a_button(master, text="Add New Staff", row=0, column=1, padx=(10, 10), pady=(10, 10), ipadx=7, ipady=4)
self.add_staff_button.config(command=add_staff_button_callback)
staffs = self.get_staff_queryset()
if staffs is not None:
for staff in staffs:
self.staff_data_button = get_a_button(master, text='{} as {}'.format(staff[1], staff[5]), row=row, column=0, padx=(0, 0), pady=(5, 5), ipadx=10, ipady=10, relief=FLAT, use_ttk=False)
self.staff_data_button.config(command = lambda email=staff[2]: detail_edit_staff_button_callback(email))
row = row + 1
In the end of function I wan't to end of pause the thread and when the new staff is added I wan't to recount or reset the list with current data so I need to run thread again
Here are the button call func
def get_add_staff(self, master, *args, **kwargs):
self.add_staff_current = True
if self.have_one_detail:
# self.destroy_child(self.frame_staff_detail)
self.have_one_detail = False
self.frame_staff_detail.destroy()
self.frame_staff_detail = get_a_frame(self.staff_add_update_panedwindow, column=1, sticky="wn")
FullName, Email, Phone, Joining, Designation, Active = self.get_staff_variable()
def cancel_new_staff_button_callback():
# self.destroy_child(master)
self.frame_staff_detail.destroy()
self.frame_staff_detail = get_a_frame(self.staff_add_update_panedwindow, column=1, sticky="wn")
self.add_staff_current = False
def staff_button_callback():
data = {
'full_name': FullName.get(),
'email': Email.get(),
'phone': float(Phone.get()),
'joining': Joining.get(),
'designation': Designation.get(),
'responsibility': self.add_staff_responsibility_data.get(1.0, 'end'),
'about': self.add_staff_about_data.get(1.0, 'end'),
'active': Active.get()
}
execute = self.execute_staff_data(data=data)
if execute is True:
# self.staff_list_thread.start()
cancel_new_staff_button_callback()
self.get_staff_labels(master)
self.add_staff_fullname_data = get_a_entry(master, textvariable=FullName, width=36, row=1, column=1)
self.add_staff_email_data = get_a_entry(master, textvariable=Email, row=2, width=36, column=1)
self.add_staff_phone_data = get_a_entry(master, textvariable=Phone, row=3, column=1)
self.add_staff_joining_data = get_a_entry(master, textvariable=Joining, row=4, column=1)
self.add_staff_designation_data = get_a_entry(master, textvariable=Designation, width=36, row=5, column=1)
self.add_staff_responsibility_data = get_a_text(master, width=36, height=4, row=6, column=1)
self.add_staff_about_data = get_a_text(master, width=36, height=10, row=7, column=1)
self.add_staff_active_data = get_a_radio(master, text="Active", variable=Active, value=1, row=8, column=1)
self.add_staff_inactive_data = get_a_radio(master, text="Inactive", variable=Active, value=0, row=9, column=1)
self.save_new_staff_button = get_a_button(master, text="Add Staff", row=10, padx=(20, 20), pady=(30, 30))
self.cancel_new_staff_button = get_a_button(master, text="Cancel", row=10, column=1, padx=(20, 20), pady=(30, 30))
self.save_new_staff_button.config(command=staff_button_callback)
self.cancel_new_staff_button.config(command=cancel_new_staff_button_callback)
To simply answer your title question, you can pause a thread with the time.sleep()
import time
time.sleep(30) #pause for 30 seconds
With a naive implementation, you could just run this on a loop checking if the function should be called. Be careful that this will lock the whole paused thread.
From the code though I don't really understand where you want to pause it.
To react to an event, pausing a thread is not the right question, you need to implement a subscribe/register and callback logic.

Resources