Threading while loading wxGrid - Python - multithreading

I'm loading a wxGrid with values from a dataframe. I'm trying to use threading so my GUI doesn't freeze(some of the SQL tables are ~60,000 x 16 and take some time to load), but I guess I'm not understanding the concept. Sometimes it runs just fine works.
Other times it crashes and exits with:
Could not convert to integer: 3221226525. Path 'exitCode'.
Value was either too large or too small for an Int32.
I have also tried implementing another thread so that my wx.gauge loads properly. That causes it to fail more often. Can anyone give me any leads? I've been stuck on this for hours.
Snippets from my code:
I also tried implementing another thread to update the wx.Gauge seperately with no success. The gauge updated but had very weird behavior. Any help would be greatly appreciated.
EDIT CODE ADDED Warning, this is probably going to be ugly
import sys
import os
import wx
import wx.grid as gridlib
import wx.lib.agw.pygauge as PG
import mysql.connector as sql
import MySQLdb
import datetime
import pandas as pd
from collections import OrderedDict
import threading #as thread
import time
from time import sleep
#import urllib
#result_available = threading.Event()
#df_data=pd.DataFrame()
class PageOne(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
#wx.StaticText(self, -1, "This is a PageOne object", (20,20))
class PageTwo(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
#wx.StaticText(self, -1, "This is a PageTwo object", (40, 40))
class PageThree(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
#wx.StaticText(self, -1, "This is a PageThree object", (60, 60))
class PageDynamic(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
wx.StaticText(self, -1, "This is a Dynamic object", (60, 60))
class MainFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, title="Varkey Foundation") #none
#Layout
self.__DoLayout()
def __DoLayout(self):
self.SetBackgroundColour( wx.Colour( 58, 56, 56 ) )
# Here we create a panel and a notebook on the panel
self.p = wx.Panel(self)
self.p.SetBackgroundColour( wx.Colour( 0, 0, 0 ) ) # 38,38,38
#self.Show() <Layout Error when GUI is launched
self.Maximize(True)
self.nb = wx.Notebook(self.p)
self.nb.SetBackgroundColour(wx.Colour(58, 56, 56) )
#CreateFonts
self.b_font = wx.Font(14,wx.ROMAN,wx.NORMAL,wx.BOLD, True)
self.lbl_font = wx.Font(14,wx.ROMAN,wx.NORMAL,wx.NORMAL, True)
self.cb_font = wx.Font(11,wx.SCRIPT,wx.ITALIC,wx.NORMAL, True)
self.h_font = wx.Font(18,wx.DECORATIVE,wx.ITALIC,wx.BOLD, True)
#Create Title bmp
ico = wx.Icon('varkey_bmp.bmp', wx.BITMAP_TYPE_ICO)
self.SetIcon(ico)
# create the page windows as children of the notebook
self.page1 = PageOne(self.nb)
self.page2 = PageTwo(self.nb)
self.page3 = PageThree(self.nb)
# add the pages to the notebook with the label to show on the tab
self.nb.AddPage(self.page1, "Data")
self.nb.AddPage(self.page2, "Analyze")
self.nb.AddPage(self.page3, "Change Log")
#Create widgets for top sizer
self.lbl_user = wx.StaticText(self.p,label="Username:")
self.lbl_password = wx.StaticText(self.p,label="Password:")
self.lbl_interaction = wx.StaticText(self.p,label="Interaction:")
self.lbl_table = wx.StaticText(self.p,label="Table:")
#SetForground colors
self.lbl_user.SetForegroundColour((255,255,255))
self.lbl_password.SetForegroundColour((255,255,255))
self.lbl_interaction.SetForegroundColour((255,255,255))
self.lbl_table.SetForegroundColour((255,255,255))
#Set Fonts
self.lbl_user.SetFont(self.lbl_font)
self.lbl_password.SetFont(self.lbl_font)
self.lbl_interaction.SetFont(self.lbl_font)
self.lbl_table.SetFont(self.lbl_font)
self.tc_user =wx.TextCtrl(self.p,size = (130,25))
self.tc_password =wx.TextCtrl(self.p, style=wx.TE_PASSWORD | wx.TE_PROCESS_ENTER,size = (130,25))
self.tc_password.Bind(wx.EVT_TEXT_ENTER,self.onLogin)
self.tc_user.SetFont(self.cb_font)
self.tc_password.SetFont(self.cb_font)
self.btn_login = wx.Button(self.p,label="Login", size=(105,25))
self.btn_login.SetBackgroundColour(wx.Colour(198, 89, 17))
self.btn_login.SetFont(self.b_font)
self.btn_login.Bind(wx.EVT_BUTTON, self.onLogin) #connect_mysql
self.btn_logout = wx.Button(self.p,label="Logout",size=(105,25))
self.btn_logout.SetBackgroundColour(wx.Colour(192,0,0))
self.btn_logout.SetFont(self.b_font)
self.btn_logout.Bind(wx.EVT_BUTTON, self.onLogout)
self.combo_interaction = wx.ComboBox(self.p, size = (160,25),style = wx.CB_READONLY | wx.CB_SORT | wx.CB_SORT)
self.combo_interaction.Bind(wx.EVT_COMBOBOX, self.onComboInteraction)
self.combo_table = wx.ComboBox(self.p, size = (160,25),style = wx.CB_READONLY | wx.CB_SORT | wx.CB_SORT)
self.combo_table.Bind(wx.EVT_COMBOBOX, self.onHideCommands)
self.combo_interaction.SetFont(self.cb_font)
self.combo_table.SetFont(self.cb_font)
#self.combo_table.Bind(wx.EVT_COMBOBOX ,self.OnComboTable)
self.btn_load = wx.Button(self.p,label="Load Table", size=(105,25))
self.btn_load.SetBackgroundColour(wx.Colour(31, 216, 6))
self.btn_load.SetFont(self.b_font)
self.btn_load.Bind(wx.EVT_BUTTON, self.onLoadData)
#Create Widgets for bottom sizer
self.lc_change = wx.ListCtrl(self.p,-1,style = wx.TE_MULTILINE | wx.LC_REPORT | wx.LC_VRULES)
self.lc_change.InsertColumn(0,"User ID")
self.lc_change.InsertColumn(1,"Status")
self.lc_change.InsertColumn(2,"Description")
self.lc_change.InsertColumn(3,"Date/Time")
#Set column widths
self.lc_change.SetColumnWidth(0, 75)
self.lc_change.SetColumnWidth(1, 75)
self.lc_change.SetColumnWidth(2, 450)
self.lc_change.SetColumnWidth(3, 125)
#Add Row Button
self.btn_new = wx.Button(self.page1,label="+", size = (35,25))
self.btn_new.SetForegroundColour(wx.Colour(112,173,71))
self.btn_new.SetFont(self.h_font)
self.btn_new.Bind(wx.EVT_BUTTON, self.onInsertRecordBelow)
#Page 1 - Create grids/sizers and add to notebook
self.color1 = (0,0,0)
self.title = wx.StaticText(self.page1,label="",style = wx.ALIGN_CENTER | wx.ST_NO_AUTORESIZE)
self.title.SetForegroundColour((255,255,255))
self.title.SetFont(self.h_font)
self.data_grid = gridlib.Grid(self.page1)
self.data_grid.CreateGrid(0,0) #219,16
self.p1_sizer = wx.BoxSizer(wx.VERTICAL)
self.p1_sizer.Add(self.title,0,wx.EXPAND,5)
self.p1_sizer.Add(self.data_grid,3,wx.RIGHT |wx.LEFT |wx.EXPAND, 20)
self.p1_sizer.Add(self.btn_new,-0,wx.ALIGN_CENTER,5)
self.page1.SetSizer(self.p1_sizer)
#Page 2 - Create grids/sizers and add to notebook #<<<<<<< Need to create correct table size
self.analyze_grid = gridlib.Grid(self.page2)
self.analyze_grid.CreateGrid(0, 10)
self.p2_sizer = wx.BoxSizer(wx.VERTICAL)
self.p2_sizer.Add(self.analyze_grid,1,wx.EXPAND)
self.page2.SetSizer(self.p2_sizer)
#Page 3 - Create Change Log
self.log_grid = gridlib.Grid(self.page3)
self.log_grid.CreateGrid(0, 9)
self.log_grid.EnableEditing(False)
self.p3_sizer = wx.BoxSizer(wx.VERTICAL)
self.p3_sizer.Add(self.log_grid,1,wx.EXPAND)
self.page3.SetSizer(self.p3_sizer)
#Insert Image
self.staticbitmap = wx.StaticBitmap(self.p)
#browse = wx.Button(self.p, label='Browse')
#browse.Bind(wx.EVT_BUTTON, self.OnBrowse)
self.staticbitmap.SetBitmap(wx.Bitmap('varkey_logo2.jpg'))
self
#Create Filler text
self.lbl_filler = wx.StaticText(self.p,label="",size = (125,20))
#Create FlexGridSizers(For top half)
self.left_fgs = wx.FlexGridSizer(3,4,25,15)
self.left_fgs.AddMany([(self.lbl_user,1,wx.ALIGN_LEFT | wx.LEFT,15),(self.tc_user,1,wx.EXPAND),(self.lbl_interaction,1,wx.ALIGN_RIGHT|wx.RIGHT, 10),(self.combo_interaction,1,wx.EXPAND),
(self.lbl_password,1,wx.ALIGN_LEFT| wx.LEFT,15),(self.tc_password,1,wx.EXPAND),(self.lbl_table,1,wx.ALIGN_RIGHT|wx.RIGHT, 10),(self.combo_table),
(self.btn_login,2,wx.EXPAND),(self.btn_logout,1,wx.EXPAND),(self.lbl_filler,1,wx.EXPAND),(self.btn_load,1)])
#Create Top Sizer and add FGS
self.top_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.top_sizer.Add(self.left_fgs,proportion = 1, flag = wx.ALL|wx.EXPAND,border = 30)
#self.top_sizer.Add(self.right_fgs,proportion = 1, flag = wx.TOP|wx.BOTTOM ,border = 30)
self.top_sizer.Add(self.staticbitmap,2,wx.TOP | wx.RIGHT, border = 40) #30
self.top_sizer.Add(self.lc_change,2,wx.RIGHT|wx.EXPAND ,30)
#Create bottom sizer(For Grid)
self.bottom_sizer = wx.BoxSizer(wx.VERTICAL)
self.bottom_sizer.Add(self.nb,proportion = 5, flag = wx.LEFT |wx.RIGHT | wx.EXPAND,border = 30)
#Create statusbar and progress bar
self.gauge = wx.Gauge(self.p, range = 100, size = (400, 20),style = wx.GA_HORIZONTAL)
#self.gauge = PG.PyGauge(self.p, 0, size=(400, 25), style=wx.GA_HORIZONTAL)
#self.gauge.SetDrawValue(draw=True, drawPercent=True, font=None, colour=wx.BLACK, formatString=None)
#self.gauge.SetBackgroundColour(wx.WHITE)
#self.gauge.SetBorderColor(wx.BLACK)
self.dummylbl = wx.StaticText(self.p,label="",size = (5,20))
self.status_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.status_sizer.Add(self.gauge, 1, wx.ALIGN_CENTER|wx.ALL, 5)
self.status_sizer.Add(self.dummylbl, 0, wx.ALL, 5)
# the layout
self.mainsizer = wx.BoxSizer(wx.VERTICAL)
self.mainsizer.Add(self.top_sizer,proportion = 0, flag = wx.ALL|wx.EXPAND,border = 5)
self.mainsizer.Add(self.bottom_sizer,proportion = 1,flag = wx.ALL|wx.EXPAND,border = 5)
self.mainsizer.Add(self.status_sizer,proportion =0,flag = wx.BOTTOM|wx.ALIGN_CENTER_HORIZONTAL, border = 15)
self.p.SetSizerAndFit(self.mainsizer)
#self.page3.Bind(wx.EVT_LEFT_DCLICK, self.dynamic_tab)
self.gauge.Hide()
self.hideWidgets()
self.onHideCommands(self)
def thread_start(self): #self,event
th = threading.Thread(target=self.populateGrid) #args=(event,), args=(self,)
th.start()
#th.join()
#result_available.wait()
#def status_thread(self): #TRIED FEEDING STATUS BAR HERE
# thr = threading.Thread(target=self.update_statusbar)
# thr.start()
#def update_statusbar(self):
#self.gauge.SetValue((round(i/self.rows)*100))
def hideWidgets(self): #Hide and disable widgets until login
if self.btn_logout.IsShown(): #Initialize and logout
self.btn_logout.Hide()
self.btn_load.Disable()
self.combo_interaction.Enable(False)
self.combo_table.Enable(False)
self.tc_user.Enable()
self.tc_password.Enable()
self.btn_login.Show()
else: #When logged in
self.btn_logout.Show()
self.combo_interaction.Enable(True)
self.combo_table.Enable(True)
self.btn_login.Hide()
self.tc_user.Disable()
self.tc_password.Disable()
def onHideCommands(self, event):
cbval = self.combo_table.GetValue()
if cbval:
self.btn_load.Enable()
self.btn_new.Enable()
else:
self.btn_load.Disable()
self.btn_new.Disable()
def onLogin(self,event):
#Get permissions from SQL table
self.tbl = 'permissions'
self.connect_mysql()
#try:
sql_query = "SELECT * FROM " + self.tbl
try:
self.cursor.execute(sql_query)
num_fields = len(self.cursor.description)
self.df_permissions = pd.read_sql(sql_query, con=self.db_con)
except:
self.stat = "ERROR"
self.msg = "ERROR: Failed to Connect. Check your internet connection and try again."
wx.MessageBox("Failed to Connect. Check your internet connection and try again.", 'CONNECTION ERROR',
wx.OK | wx.ICON_ERROR)
self.updateStatus()
return
if(len(self.tc_user.GetValue()) > 0):
id = str(self.tc_user.GetValue())
base = r'^{}'
expr = '(?:\s|^){}(?:,\s|$)'
try:
u = self.df_permissions[self.df_permissions.iloc[:,0].str.contains(base.format(''.join(expr.format(id))),na = False, case = False)].index.values[0]
#u = ((self.df_permissions[self.df_permissions.iloc[:,0].str.match(self.tc_user.GetValue())].index).values)[0] #,na=False,case=False
pwrd = (self.df_permissions.iloc[u,1])
except:
wx.MessageBox("Access denied. " + id + " is not an authorized user.", 'Access Denied',
wx.OK | wx.ICON_ERROR)
return
#If password is correct, make connection
if(self.tc_password.GetValue() == pwrd):
self.stat = "Successful"
self.msg = "Access Granted."
self.updateStatus()
self.tbl = 'tables'
sql_query = "SELECT * FROM " + self.tbl
self.cursor.execute(sql_query)
self.df_tables = pd.read_sql(sql_query, con=self.db_con)
if str(self.df_permissions.iloc[u,2])=="ALL":
self.interactionlist = self.df_tables['Interaction'].to_list()
self.interaction_filtered = self.df_tables #< For dependent combobox
else:
read_str = str(self.df_permissions.iloc[u,2])
read_str = read_str.replace(", ", ",")
read_tables = list(read_str.split(","))
self.interaction_filtered = self.df_tables[self.df_tables['Table_Name'].isin(read_tables)]
self.interactionlist = self.interaction_filtered['Interaction'].to_list()
#Remove duplicates and create lists for combobox
self.interactionlist = list(OrderedDict.fromkeys(self.interactionlist))
self.combo_interaction.SetItems(self.interactionlist)
self.hideWidgets()
else:
Access Denied." + "\n")
self.stat = "ERROR"
self.msg = "ERROR: Incorrect Password. Access Denied."
self.updateStatus()
else:
self.stat = "ERROR"
self.msg = "ERROR: Username cannot be blank!"
self.updateStatus()
self.buildChangeLog()
self.close_connection()
def onLogout(self,event):
self.hideWidgets()
self.destroy_Widgets()
def updateStatus(self):
#Update listControl
self.lc_change.Append([self.tc_user.GetValue(),self.stat,self.msg, str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + "\n"])
if self.lc_change.GetItemCount() > 0:
self.lc_change.EnsureVisible(self.lc_change.GetItemCount() - 1)
#Update Log Grid
if self.stat == "UPDATE" or self.stat == "DELETE" or self.stat == "INSERT":
self.log_grid.AppendRows(numRows = 1, updateLabels = True)
r = self.log_grid.GetNumberRows() -1
self.log_grid.SetCellValue(r,0,self.key_id.replace("'",""))
self.log_grid.SetCellValue(r,1,self.tc_user.GetValue())
self.log_grid.SetCellValue(r,2,self.action) #Action
self.log_grid.SetCellValue(r,3,self.tbl)
self.log_grid.SetCellValue(r,4,self.key_col) #'Column #target_col
self.log_grid.SetCellValue(r,5,self.target_col) #'Old Value
self.log_grid.SetCellValue(r,6,self.oVal.replace("'","")) #'New Value
self.log_grid.SetCellValue(r,7,self.nVal.replace("'","")) #'New Value
self.log_grid.SetCellValue(r,8,str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) #Timestamp
#Size the grid
self.log_grid.AutoSizeColumns(True)
#Set Font color
#index = self.lc_change.GetItemCount()
#item = self.lc_change.GetItem(index)
#self.lc_change.SetItemTextColour(index,'red')
#self.lc_change.InsertItem(index,item)
#print(index)
def destroy_Widgets(self):
#Destroy grid
self.Freeze()
self.data_grid.Destroy()
#Reset and insert blank grid
self.tbl = "elite_advocacy"
self.connect_mysql()
sql_query = "SELECT * FROM " + self.tbl
self.cursor.execute(sql_query)
num_fields = len(self.cursor.description)
self.df_data = pd.read_sql(sql_query, con=self.db_con)
rows, cols = (int(self.df_data.shape[0]),int(self.df_data.shape[1]))
self.data_grid = gridlib.Grid(self.page1)
self.data_grid.Bind(wx.grid.EVT_GRID_CELL_CHANGED, self.onCellChanged)
self.data_grid.Bind(wx.grid.EVT_GRID_CELL_RIGHT_DCLICK,self.onDeleteRecord)
self.data_grid.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK,self.rightClickMenu)
self.data_grid.CreateGrid(rows,cols)
self.p1_sizer.Insert(1,self.data_grid,1,wx.RIGHT| wx.LEFT| wx.EXPAND, 20)
self.p1_sizer.Layout()
#Clear Rows on log Grid
n = self.log_grid.GetNumberRows()
if n > 0:
self.log_grid.DeleteRows(0,n)
# Clear rows on analyze Grid
n = self.analyze_grid.GetNumberRows()
if n > 0:
self.analyze_grid.DeleteRows(0,n)
#Clear list listCtrl
x = self.lc_change.GetItemCount()
for i in range(x):
self.lc_change.DeleteItem(0)
#Clear textCtrl and ComboBoxes
self.tc_password.SetValue("")
self.tc_user.SetValue("")
self.title.SetLabel("")
self.combo_table.Clear()
self.combo_interaction.Clear()
self.combo_interaction.SetValue("")
self.combo_table.SetValue("")
self.close_connection()
self.Thaw()
def buildChangeLog(self):
self.tbl = 'change_log'
sql_query = "SELECT * FROM " + self.tbl
self.cursor.execute(sql_query)
num_fields = len(self.cursor.description)
#Create Grid Headers
try:
field_names = [i[0] for i in self.cursor.description]
for i,a in enumerate(field_names):
self.log_grid.SetColLabelValue(i,a)
#Size the grid
self.log_grid.AutoSizeColumns(True)
except:
pass
def onComboInteraction(self, event):
self.tables_filtered = self.interaction_filtered[self.interaction_filtered['Interaction'].str.contains(self.combo_interaction.GetValue())]
self.tableslist = self.tables_filtered['Table_Name'].to_list()
self.combo_table.SetItems(self.tableslist)
self.onHideCommands(event)
def dynamic_tab(self, event):
print('dynamic_tab()')
dynamic_page = PageDynamic(self.nb)
self.nb.AddPage(dynamic_page, "Page Dynamic")
def getTable(self):
#Determine SQL table from DataFrame
self.tbl_input = self.combo_table.GetValue()
r = ((self.df_tables[self.df_tables.iloc[:,2].str.contains(self.combo_table.GetValue(),na=False)].index).values)[0]
self.tbl = (self.df_tables.iloc[r,3])
def populateGrid(self):
t0 = time.time()
self.rows, self.cols = (int(self.df_data.shape[0]),int(self.df_data.shape[1]))
for i, seq in enumerate(self.df_data.index):
for j, v in enumerate(self.df_data.columns):
self.data_grid.SetCellValue(i, j, str(self.df_data.iloc[i,j]))
#self.gauge.SetValue(int(round(i/self.rows,2)*100)) #int(percentage*100)
self.gauge.SetValue(0)
self.gauge.Hide()
#Size the grid
self.data_grid.AutoSizeColumns(True)
self.stat = "QUERY"
self.msg = str(self.rows) + " loaded from " + self.tbl
self.updateStatus()
#Set title
self.title.SetLabel(str(self.combo_table.GetValue()))
t1 = time.time()
print(t1-t0)
def onLoadData(self,event):
if self.combo_table.GetValue():
#Establish Connection
self.connect_mysql()
#Get Table
self.getTable()
#self.testFunction()
if self.tbl:
#Get SQL Data
t0 = time.time()
self.gauge.Show()
sql_query = "SELECT * FROM " + self.tbl
self.cursor.execute(sql_query)
num_fields = len(self.cursor.description)
temp = pd.read_sql(sql_query, con=self.db_con)
self.df_data = temp[~pd.isnull(temp).all(1)].fillna('')
pd.set_option('display.max_columns', None)
#Destroy grid and insert new resized grid
rows, cols = (int(self.df_data.shape[0]),int(self.df_data.shape[1]))
self.data_grid.Destroy()
self.data_grid = gridlib.Grid(self.page1)
self.data_grid.Bind(wx.grid.EVT_GRID_CELL_CHANGED, self.onCellChanged)
self.data_grid.Bind(wx.grid.EVT_GRID_CELL_RIGHT_DCLICK,self.onDeleteRecord)
#self.data_grid.Bind(gridlib.EVT_GRID_CELL_RIGHT_CLICK,self.showPopupMenu)
self.data_grid.CreateGrid(rows,cols) #self.data_grid.CreateGrid(219, 16)
self.p1_sizer.Insert(1,self.data_grid,1,wx.RIGHT| wx.LEFT|wx.EXPAND, 20)
self.p1_sizer.Layout()
#Create Grid Headers
field_names = [i[0] for i in self.cursor.description]
for i,a in enumerate(field_names):
self.data_grid.SetColLabelValue(i,a)
self.data_grid.AutoSizeColumns(True)
#Populate Table
#####START THREAD#########
self.thread_start()
else: #self.tbl variable is blank
self.stat = "ERROR"
self.msg = "ERROR: No table exists in mySQL for Table: " + "'" + str(self.combo_table.GetValue()) + "'"
self.updateStatus()
return
else:
self.stat = "ERROR"
self.msg = "ERROR: Table Combobox is empty "
self.updateStatus()
return
def connect_mysql(self):
self.db_name = 'db'
self.server = 'server'
self.user_id = 'user1'
self.pw = 'pwrd'
try:
self.db_con = MySQLdb.connect(user=self.user_id,password=self.pw,database=self.db_name,
host=self.server,charset='utf8',autocommit=True)
self.cursor = self.db_con.cursor()
except:
print("Error connecting")
def close_connection(self):
try:
self.db_con.close()
except:
pass
def onCellChanged(self, evt):
self.connect_mysql()
try:
self.key_id = str("'") + self.data_grid.GetCellValue(evt.GetRow(),0) + str("'")
self.target_col = self.data_grid.GetColLabelValue(evt.GetCol())
self.key_col = self.data_grid.GetColLabelValue(0)
self.nVal = str("'") + self.data_grid.GetCellValue(evt.GetRow(),evt.GetCol()) + str("'")
sql_update = "UPDATE " + self.tbl + " SET " + self.target_col + " = " + self.nVal + " WHERE " + self.key_col + " = " + self.key_id + ""
print(sql_update)
self.cursor.execute(sql_update)
self.stat = "UPDATE"
self.oVal = evt.GetString()
self.action = "UPDATE"
self.msg = "Changed " + str("'") + self.oVal + str("'") + " to " + self.nVal + " for " + self.key_id + " in table: " + str("'") + self.tbl + str("'")
self.updateStatus()
except:
self.stat = "ERROR"
self.msg = "ERROR: Failed to update SQL table. " + "'" + self.tbl + "'"
self.updateStatus()
self.db_con.rollback()
self.close_connection()
def onInsertRecordBelow(self, evt):
self.key_id = str("'") + self.data_grid.GetCellValue(evt.GetRow(),0) + str("'")
self.target_col = "" #self.data_grid.GetColLabelValue(evt.GetCol())
self.key_col = self.data_grid.GetColLabelValue(0)
self.del_row = evt.GetRow()
dlg = wx.TextEntryDialog(self.p,'Enter a new Key ID to insert into the ' + str("'") + self.data_grid.GetColLabelValue(0) + str("'") + ' column.', 'Insert New Record')
#dlg.SetValue("Default")
if dlg.ShowModal() == wx.ID_OK:
#print('You entered: %s\n' % dlg.GetValue())
val = dlg.GetValue()
#Check if it exists in database
self.connect_mysql()
checkRec = ("SELECT " + str(self.key_col) + "," + " COUNT(*) FROM " + str(self.tbl) + " WHERE " + str(self.key_col) + " = " + "'" + str(val)
+ "'" + " GROUP BY " + str(self.key_col) + "")
self.cursor.execute(checkRec)
results = self.cursor.fetchall()
row_count = self.cursor.rowcount
if row_count > 0:
print("Exists")
self.stat = "ERROR"
self.msg = "ERROR: INSERT FAILED. " + "'" +str(val) + "'" + " already exists in table: " + "'" + self.tbl + "'." + " Abort."
self.close_connection()
self.updateStatus()
return
else:
try:
self.connect_mysql()
sql_update = ("INSERT INTO " + str(self.tbl) + "(" + self.key_col + ")" + "VALUES (" + str("'") + str(val) + str("'") + ")")
self.cursor.execute(sql_update)
#Append row to Grid
lRow = int(self.df_data.shape[0])
lCol = int(self.df_data.shape[1])
self.data_grid.InsertRows(lRow,1)
self.data_grid.SetCellValue(lRow, 0, str(val))
#Insert into Dataframe
self.df_data.append(pd.Series(dtype='object'), ignore_index=True)
#Update status
self.key_id = val
self.stat = "INSERT"
self.msg = "INSERTED record " + "'" + str(val) + "'" + " into table: " + "'" + self.tbl + "'"
self.action = "INSERT"
self.nVal = ""
self.oVal = ""
except:
self.db_con.rollback()
self.stat = "ERROR"
self.msg = "ERROR: Failed to INSERT record '" + str(val) + "'into table: " + "'" + self.tbl + "'"
else:
print("ABORTED")
self.close_connection()
self.updateStatus()
dlg.Destroy
def onDeleteRecord(self,evt):
#Connect
self.connect_mysql()
#Delete from mySQL table
try:
self.nVal = ""
sql_delete = "DELETE FROM " + self.tbl + " WHERE " + self.key_col + " = " + self.key_id + ""
print (sql_delete)
self.cursor.execute(sql_delete)
self.db_con.commit()
self.stat = "DELETE"
self.oVal = ""
self.action = "DELETE"
self.msg = "Deleted Record ID: " + self.key_id + " from " + str("'") + self.tbl + str("'")
#Delete from Grid
self.data_grid.DeleteRows(self.del_row,1,True)
except:
self.stat = "ERROR"
self.msg = "ERROR: Failed to Delete record from table: " + "'" + self.tbl + "'"
self.db_con.rollback()
self.close_connection()
self.updateStatus()
if __name__ == "__main__":
app = wx.App(False)
MainFrame(None).Show() # MainFrame().Show()
app.MainLoop()

Related

PySimpleGUI Checkbox

Idk why, but when i check a checkbox in the menu nothings, happens, but if i close the menu the cheat start. I think that i made some mistakes setting up the checkboxes, but im trying to fix this problem from 3 days now and i can't continue anymore. Can someone help?
import PySimpleGUI as sg
import threading
from globals import *
import math
import time
import keyboard
switch = True
rcsonoff = True
r = 255
g = 3
b = 3
def normalizeAngles(viewAngleX, viewAngleY):
if viewAngleX > 89:
viewAngleX -= 360
if viewAngleX < -89:
viewAngleX += 360
if viewAngleY > 180:
viewAngleY -= 360
if viewAngleY < -180:
viewAngleY += 360
return viewAngleX, viewAngleY
def checkangles(x, y):
if x > 89:
return False
elif x < -89:
return False
elif y > 360:
return False
elif y < -360:
return False
else:
return True
def nanchecker(first, second):
if math.isnan(first) or math.isnan(second):
return False
else:
return True
layout = [
# Use a modern font and color scheme
[sg.Text("External 2.3", font="Helvetica 20", text_color="#d80fc6")],
# Use tabs to organize the buttons into different categories
[sg.TabGroup([
# Tab for aim-related buttons
[sg.Tab("Aim", [[
sg.Column(
# Define the grid layout for the buttons
[
[sg.Checkbox("No Recoil", default=False, key="no_recoil_checkbox")],
[sg.Checkbox("TriggerBot", default=False, key="triggerbot_checkbox")]
],
# Set the number of rows and columns in the grid
)
]]),
# Tab for visual-related buttons
sg.Tab("Visuals", [[
sg.Column(
# Define the grid layout for the buttons
[
[sg.Checkbox("Glow", default=False, key="glow_checkbox")],
[sg.Checkbox("Chams", default=False, key="chams_checkbox")],
[sg.Checkbox("Fov", default=False, key="fov_checkbox")],
[sg.Text("Fov Value (MAX 140): "), sg.InputText(key="fov")],
[sg.Button("Set FOV Value", button_color=("magenta", "#a9a9a9"))]
],
# Set the number of rows and columns in the grid
)
]]),
sg.Tab("Misc", [[
sg.Column(
[
[sg.Checkbox("Bunny Hop", default=False, key="bunny_hop_checkbox")],
[sg.Checkbox("Radar Hack", default=False, key="radar_hack_checkbox")],
[sg.Checkbox("Show Rank", default=False, key="show_rank_checkbox")],
[sg.Checkbox("Third Person", default=False, key="3_person_checkbox")],
[sg.Checkbox("No Flash", default=False, key="no_flash_checkbox")]
],
)
]]),
sg.Tab("LocalPlayer", [[
sg.Column(
[
[sg.Text("Player Health:")],
[sg.Text(key="Health")],
[sg.Text("Armor:")],
[sg.Text(key="Armor")],
[sg.Text("Enter a new value:")],
[sg.InputText(key="NewArmor")],
[sg.Button("Update Armor")],
[sg.Text("Enter a new money value:")],
[sg.InputText(key="Money")],
[sg.Button("Update Money")]
],
)
]]),
# Tab for color-related buttons
sg.Tab("Color and Debug", [[
sg.Column(
# Define the grid layout for the sliders
[
[sg.Button("Debug", button_color=("magenta", "#a9a9a9"))],
[sg.Text("Enter the glow color values:")],
[sg.Text("Red:"), sg.InputText(key="Red")],
[sg.Text("Green:"), sg.InputText(key="Green")],
[sg.Text("Blue:"), sg.InputText(key="Blue")],
[sg.Button("Set Glow Color")]
],
# Set the number of rows and columns in the grid
)
]])
]])]
]
window = sg.Window("Buck3ts41", layout, element_justification="center")
def debug():
while True:
print("crossID ", crosshairID)
print("corssTeam ", crosshairTeam)
print("LocalPlayer ", player)
print("LocalTeam ", localTeam)
print("GlowManager ", glow_manager)
print("GetTeam ", getTeam)
time.sleep(2)
def esp():
while True:
try:
if glow == True:
for i in range(1, 32):
entity = pm.read_int(client + dwEntityList + i * 0x10)
if entity:
entity_hp = pm.read_uint(entity + m_iHealth)
entity_team_id = pm.read_uint(entity + m_iTeamNum)
entity_dormant = pm.read_uint(entity + m_bDormant)
entity_glow = pm.read_uint(entity + m_iGlowIndex)
if entity_team_id == 2 and localTeam != 2 and not entity_dormant: ###TERRORIST###
pm.write_float(glow_manager + entity_glow * 0x38 + 0x8, float(r)) # R
pm.write_float(glow_manager + entity_glow * 0x38 + 0xC, float(g)) # G
pm.write_float(glow_manager + entity_glow * 0x38 + 0x10, float(b)) # B
pm.write_float(glow_manager + entity_glow * 0x38 + 0x14, float(255)) # A
pm.write_int(glow_manager + entity_glow * 0x38 + 0x28, 1) # START
elif entity_team_id == 3 and localTeam != 3 and not entity_dormant: ###COUNTER###
pm.write_float(glow_manager + entity_glow * 0x38 + 0x8, float(r)) # R
pm.write_float(glow_manager + entity_glow * 0x38 + 0xC, float(g)) # G
pm.write_float(glow_manager + entity_glow * 0x38 + 0x10, float(b)) # B
pm.write_float(glow_manager + entity_glow * 0x38 + 0x14, float(255)) # A
pm.write_int(glow_manager + entity_glow * 0x38 + 0x28, 1) # START
except Exception as err:
pass
time.sleep(0.001)
def chamshack():
if chams:
rgbt = [255, 0, 0]
rgbc = [0, 0, 255]
while True:
try:
time.sleep(0.001)
for i in range(1, 32):
entity = pm.read_int(client + dwEntityList + i * 0x10)
if entity:
entity_team_id = pm.read_uint(entity + m_iTeamNum)
if entity_team_id == 2: # terrorist
pm.write_int(entity + m_clrRender, (rgbt[0])) # R
pm.write_int(entity + m_clrRender + 0x1, (rgbt[1])) # G
pm.write_int(entity + m_clrRender + 0x2, (rgbt[2])) # B
elif entity_team_id == 3: # counter
pm.write_int(entity + m_clrRender, (rgbc[0])) # R
pm.write_int(entity + m_clrRender + 0x1, (rgbc[1])) # G
pm.write_int(entity + m_clrRender + 0x2, (rgbc[2])) # B
else:
pass
except Exception as err:
pass
time.sleep(0.001)
def norcs():
if no_recoil:
oldpunchx = 0.0
oldpunchy = 0.0
while switch:
try:
time.sleep(0.01)
if rcsonoff:
rcslocalplayer = pm.read_uint(client + dwLocalPlayer)
rcsengine = pm.read_uint(engine + dwClientState)
if pm.read_int(rcslocalplayer + m_iShotsFired) > 1:
rcs_x = pm.read_float(rcsengine + dwClientState_ViewAngles)
rcs_y = pm.read_float(rcsengine + dwClientState_ViewAngles + 0x4)
punchx = pm.read_float(rcslocalplayer + m_aimPunchAngle)
punchy = pm.read_float(rcslocalplayer + m_aimPunchAngle + 0x4)
newrcsx = rcs_x - (punchx - oldpunchx) * 2.0
newrcsy = rcs_y - (punchy - oldpunchy) * 2.0
newrcs, newrcy = normalizeAngles(newrcsx, newrcsy)
oldpunchx = punchx
oldpunchy = punchy
if nanchecker(newrcsx, newrcsy) and checkangles(newrcsx, newrcsy):
pm.write_float(rcsengine + dwClientState_ViewAngles, newrcsx)
pm.write_float(rcsengine + dwClientState_ViewAngles + 0x4, newrcsy)
else:
oldpunchx = 0.0
oldpunchy = 0.0
newrcsx = 0.0
newrcsy = 0.0
except Exception as err:
pass
time.sleep(0.001)
def bhop():
if bunny_hop:
while True:
try:
if keyboard.is_pressed("space"):
force_jump = client + dwForceJump
player = pm.read_int(client + dwLocalPlayer)
on_ground = pm.read_int(player + m_fFlags)
if player and on_ground and on_ground == 257:
pm.write_int(force_jump, 5)
time.sleep(0.08)
pm.write_int(force_jump, 4)
except Exception as err:
pass
time.sleep(0.001)
def fovhack():
if fov:
while True:
try:
player = pm.read_int(client + dwEntityList)
pm.write_int(player + m_iDefaultFOV, Fov)
except Exception as err:
pass
time.sleep(0.001)
def r5():
if radar_hack:
while True:
try:
for i in range(1, 32):
entity = pm.read_int(client + dwEntityList + i * 0x10)
if entity:
pm.write_uchar(entity + m_bSpotted, 1)
except Exception as err:
pass
time.sleep(0.001)
def trigger():
if triggerbot:
while True:
try:
# If the crosshair is on an enemy, shoot
if crosshairID > 0 and crosshairID < 64 and crosshairTeam != localTeam:
keyboard.press("attack")
time.sleep(0.1)
keyboard.release("attack")
time.sleep(0.1)
except Exception as err:
pass
time.sleep(0.001)
def person():
if third_person:
switch = 0
while True:
try:
localplayer = pm.read_int(client + dwLocalPlayer)
if keyboard.is_pressed('z') and switch == 0:
pm.write_int(localplayer + m_iObserverMode, 1)
switch = 1
time.sleep(0.5)
if keyboard.is_pressed('z') and switch == 1:
pm.write_int(localplayer + m_iObserverMode, 0)
switch = 0
time.sleep(0.5)
except Exception as err:
pass
time.sleep(0.001)
def noflash():
if no_flash:
if player:
flash_value = player + m_flFlashMaxAlpha
if flash_value:
pm.write_float(flash_value, float(0))
else:
pass
def rank():
if show_rank:
ranks = ["Unranked",
"Silver I",
"Silver II",
"Silver III",
"Silver IV",
"Silver Elite",
"Silver Elite Master",
"Gold Nova I",
"Gold Nova II",
"Gold Nova III",
"Gold Nova Master",
"Master Guardian I",
"Master Guardian II",
"Master Guardian Elite",
"Distinguished Master Guardian",
"Legendary Eagle",
"Legendary Eagle Master",
"Supreme Master First Class",
"The Global Elite"]
for i in range(0, 32):
entity = pm.read_uint(client.lpBaseOfDll + dwEntityList + i * 0x10)
if entity:
entity_team_id = pm.read_uint(entity + m_iTeamNum)
if entity_team_id:
player_info = pm.read_uint(
(pm.read_uint(engine.lpBaseOfDll + dwClientState)) + dwClientState_PlayerInfo)
player_info_items = pm.read_uint(pm.read_uint(player_info + 0x40) + 0xC)
info = pm.read_uint(player_info_items + 0x28 + (i * 0x34))
playerres = pm.read_uint(client.lpBaseOfDll + dwPlayerResource)
rank = pm.read_uint(playerres + m_iCompetitiveRanking + (i * 4))
wins = pm.read_uint(playerres + m_iCompetitiveWins + i * 4)
if pm.read_string(info + 0x10) != 'GOTV':
print(rank)
print(pm.read_string(info + 0x10) + " --> " + ranks[rank])
print(wins)
global glow, chams, no_recoil, triggerbot, bunny_hop, radar_hack, fov, third_person, no_flash, show_rank
while True:
event, values = window.read(timeout=100)
if event == "exit" or event == sg.WIN_CLOSED:
break
if event == "__TIMEOUT__":
# Read the health value of the player
health = pm.read_uint(player + m_iHealth)
# Update the displayed health value
window["Health"].update(str(health))
if event == "Set Glow Color":
# Split the input string into a list of strings representing the red, green, and blue values
r = values["Red"]
g = values["Green"]
b = values["Blue"]
# Convert the strings to integers
r = int(r)
g = int(g)
b = int(b)
if event == "Update Money":
# Read the new money value from the textbox
new_money = values["Money"]
# Convert the new money value to an integer
new_money = int(new_money)
# Write the new money value to the game's memory
pm.write_int(player + m_iAccountID, new_money)
if event == "Update Armor":
# Read the new armor value from the textbox
new_armor = values["NewArmor"]
# Convert the new armor value to an integer
new_armor = int(new_armor)
# Update the armor value
pm.write_int(player + m_ArmorValue, new_armor)
# Update the displayed armor value
window["Armor"].update(str(new_armor))
if event == "Set FOV Value":
Fov = values["fov"]
Fov = int(Fov)
if values["glow_checkbox"] == True:
glow = True
else:
glow = False
if values["chams_checkbox"] == True:
chams = True
else:
chams = False
if values["bunny_hop_checkbox"] == True:
bunny_hop = True
else:
bunny_hop = False
if values["fov_checkbox"] == True:
fov = True
else:
fov = False
if values["radar_hack_checkbox"] == True:
radar_hack = True
else:
radar_hack = False
if values["triggerbot_checkbox"] == True:
triggerbot = True
else:
triggerbot = False
if values["3_person_checkbox"] == True:
third_person = True
else:
third_person = False
if values["no_flash_checkbox"] == True:
no_flash = True
else:
no_flash = False
if values["show_rank_checkbox"] == True:
show_rank = True
else:
show_rank = False
if values["no_recoil_checkbox"] == True:
no_recoil = True
else:
no_recoil = False
if event == "Debug":
debug()
def start_threads():
try:
threading.Thread(target=esp, name='esp').start()
threading.Thread(target=chamshack, name='chamshack').start()
threading.Thread(target=person, name='person').start()
threading.Thread(target=rank, name='rank').start()
threading.Thread(target=norcs, name='norcs').start()
threading.Thread(target=trigger, name='trigger').start()
threading.Thread(target=bhop, name='bhop').start()
threading.Thread(target=r5, name='r5').start()
threading.Thread(target=noflash, name='noflash').start()
threading.Thread(target=fovhack, name='fovhack').start()
except Exception as err:
print(f'Threads have been canceled! Exiting...\nReason: {err}\nExiting...')
exit(1)
start_threads()
window.close()
i really don't know what im i doing wrong, i have decent experience with python but pysimpleGUI is another thing...

ValueError: Length of values (1) does not match length of index (50)

Hey there awesome peeps,
I am trying to retrieve some trend information based on some keywords that I have in a list (1000 keywords). In order to minimize the chance of getting blocked by Google I have a cutoff period of 50 and a 10 second pause. At the moment I get an error saying that my Length of value does not match the length of the index. This fails on the
df3['Trend'] = trends
If anyone can help I will really appreciate it.
Thanks!
!pip install pytrends
import pandas as pd
import json
import time
from pytrends.request import TrendReq
get_gsc_file = "/content/Queries.csv"
sortby = "Clicks"
cutoff = 50
pause = 10
timeframe = "today 3-m"
geo = "US"
df = pd.read_csv(get_gsc_file, encoding='utf-8')
df.sort_values(by=[sortby], ascending=False, inplace=True)
df = df[:cutoff]
d = {'Keyword': [], sortby:[], 'Trend': []}
df3 = pd.DataFrame(data=d)
keywords = []
trends = []
metric = df[sortby].tolist()
up = 0
down = 0
flat = 0
na = 0
for index, row in df.iterrows():
keyword = row['Top queries']
pytrends = TrendReq(hl='en-US', tz=360, retries=2, backoff_factor=0.1)
kw_list = [keyword]
pytrends.build_payload(kw_list, cat=0, timeframe=timeframe, geo=geo, gprop='')
df2 = pytrends.interest_over_time()
keywords.append(keyword)
try:
trend1 = int((df2[keyword][-5] + df2[keyword][-4] + df2[keyword][-3])/3)
trend2 = int((df2[keyword][-4] + df2[keyword][-3] + df2[keyword][-2])/3)
trend3 = int((df2[keyword][-3] + df2[keyword][-2] + df2[keyword][-1])/3)
if trend3 > trend2 and trend2 > trend1:
trends.append('UP')
up+=1
elif trend3 < trend2 and trend2 < trend1:
trends.append('DOWN')
down+=1
else:
trends.append('FLAT')
flat+=1
except:
trends.append('N/A')
na+=1
time.sleep(pause)
df3['Keyword'] = keywords
df3['Trend'] = trends
df3[sortby] = metric
def colortable(val):
if val == 'DOWN':
color="lightcoral"
elif val == 'UP':
color = "lightgreen"
elif val == 'FLAT':
color = "lightblue"
else:
color = 'white'
return 'background-color: %s' % color
df3 = df3.style.applymap(colortable)
total = len(trends)
print("Up: " + str(up) + " | " + str(round((up/total)*100,0)) + "%")
print("Down: " + str(down) + " | " + str(round((down/total)*100,0)) + "%")
print("Flat: " + str(flat) + " | " + str(round((flat/total)*100,0)) + "%")
print("N/A: " + str(na) + " | " + str(round((na/total)*100,0)) + "%")
df3

How to pass values from one thread to another thread Python?

I begin to code the python and I am not have more experience in syntax of python
I want to send a value from the RFID reader. If it saves successfully, the PIR Motion Sensor will be disabled in a moment. and reworking within the specified time.
If the temperature is measured And send the value to the function RFID Reader to record the temperature and the PIR Motion Sensor stops working as well.
class Security:
global dbHost
global dbUser
global dbPass
global dbNameEmp
global dbNameSecure
dbHost = 'localhost'
dbUser = 'root'
dbPass = 'iTdev#2020'
dbNameEmp = 'empinfo'
dbNameSecure = 'secureinfo'
def __init__(self):
self.msg=""
def Temperature(self):
while True:
GPIO.output(TRIG, False)
time.sleep(0.5)
GPIO.output(TRIG, True)
time.sleep(0.01)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0 :
pulse_start = time.time()
while GPIO.input(ECHO) == 1 :
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 11150
distance = round(distance,2)
if distance > 0 and distance < 3 :
buzzer.on()
time.sleep(0.1)
buzzer.off()
print ("Distance: %scm" % (distance))
#print "Ambient Temperature :", sensor.get_ambient()
print ("Temperature: %.1fc" % (sensor.get_object_1()))
msgTemp = ("%.1f" % (sensor.get_object_1()))
w, h = textsize(msgTemp, font=proportional(CP437_FONT))
if w <= device.width:
x = round((device.width - w) / 2)
with canvas(device) as draw:
text(draw, (x, 0), msgTemp, fill="white", font=proportional(CP437_FONT))
else:
show_message(device, msgTemp, fill="white", font=proportional(CP437_FONT),scroll_delay=0.04)
time.sleep(1)
device.clear()
def rfid_callback(self, state, dev):
rfid_presented = ""
keys = "X^1234567890XXXXqwertzuiopXXXXasdfghjklXXXXXyxcvbnmXXXXXXXXXXXXXXXXXXXXXXX"
while True:
r,w,x = select([dev], [], [])
for event in dev.read():
if event.type==1 and event.value==1:
if event.code==28:
rfid_presented = rfid_presented.replace("X", "")
travel = state.replace("Thread-", "")
dbConnEmp = mysql.connect(host=dbHost, user=dbUser, passwd=dbPass, db=dbNameEmp)
curEmp = dbConnEmp.cursor()
curEmp.execute("Select RFidEmp FROM RFidMaster WHERE (RFidStatus = 1) AND RFidNumber = '%s'" % (rfid_presented))
resultRFid = curEmp.fetchone()
if curEmp.rowcount != 1:
# print("Access Denied." + travel)
with canvas(device) as draw:
text(draw, (0, 0), "None", fill="white", font=proportional(CP437_FONT))
time.sleep(0.5)
device.clear()
else:
# print("Unlocking Door." + travel)
dbConnSecure = mysql.connect(host=dbHost, user=dbUser, passwd=dbPass, db=dbNameSecure)
curSecure = dbConnSecure.cursor()
curSecure.execute("SELECT EntraId,DATE_FORMAT(CreateDate, '%Y%m%d') AS CreateDate FROM entranlog ORDER BY EntraId DESC, CreateDate DESC LIMIT 1")
resultKey = curSecure.fetchone()
KeyDate = time.strftime("%Y%m%d")
if curSecure.rowcount != 1:
KeyId = KeyDate+"0001"
else:
if resultKey[1] == KeyDate:
iSum = int(resultKey[0])
def sum(x, y):
return x + y
KeyId = ('%d' % sum(iSum, 1))
else:
KeyId = KeyDate+"0001"
create_date = time.strftime('%Y-%m-%d %H:%M:%S')
insertSecure = "INSERT INTO entranlog (EntraId,EntraAction,EntraStatus,CreateBy,CreateDate) VALUES (%s,%s,%s,%s,%s)"
valSecure = (KeyId,travel,1,resultRFid[0],create_date)
curSecure.execute(insertSecure, valSecure)
dbConnSecure.commit()
# print("Welcome: " + resultRFid[0])
with canvas(device) as draw:
text(draw, (0, 0), "Hello", fill="white", font=proportional(CP437_FONT))
print(curSecure.rowcount, "record inserted.")
time.sleep(0.8)
device.clear()
rfid_presented = ""
else:
rfid_presented += keys[ event.code ]
def PirSensor(self):
while True:
led_blue.on()
time.sleep(0.1)
current_state = GPIO.input(pir_sensor)
if current_state == 1:
print("GPIO pin %s is %s" % (pir_sensor, current_state))
GPIO.output(relay_alarm,True)
led_blue.off()
led_red.blink(0.1, 0.2)
# buzzer.beep(0.5, 0.5, 3)
time.sleep(5)
GPIO.output(relay_alarm,False)
led_red.off()
led_yellow.blink(0.5, 0.5)
time.sleep(5)
led_yellow.off()
def main(self):
devIn = threading.Thread(target=self.rfid_callback, args=['1', InputDevice('/dev/input/event0')])
devIn.start()
devOut = threading.Thread(target=self.rfid_callback, args=['2', InputDevice('/dev/input/event1')])
devOut.start()
Pir = threading.Thread(target=self.PirSensor)
Pir.start()
Temp = threading.Thread(target=self.Temperature)
Temp.start()
if __name__ == "__main__":
g=Security()
g.main()

Winodow not appearing in Tkinter

this code is in referrence to a cricket scoring program
When a button is pressed in my program, it runs a validation based of the users input and if it goes through, it should open a new window. But every time I run the code, the window.
def team_names(team):
global team_amount
global team_name_input
global team_amount_test
team_name_input = Toplevel(master)
confirm_screen.withdraw()
enter_names = Label(team_name_input, text = "Enter amount of players in " + team).grid(row = 0, column = 1)
enter_names2 = Label(team_name_input, text="(Between 2 and 11)").grid(row=1, column=1)
team_amount_test = Entry(team_name_input, width = 20)
team_amount_test.grid(row = 2, column = 1)
submit_amount = Button(team_name_input, text="Submit", command= lambda:amount_validation(team_1_array)).grid(row=3, column=1) <--- Button to open new winodw
def amount_validation(team_array):
team_num = 1
team_amount = int(team_amount_test.get())
if team_num == 1:
current_team = team_1
elif team_num == 2:
current_team = team_2
#Validation
if team_amount < 2 or team_amount > 11:
error = Label(team_name_input, text = "Invalid amount, try again").grid(row = 4, column = 1)
elif team_amount > 2 or team_amount < 11:
player_num = 1
name_input_win = Toplevel(master) #Should open new winodw here
#name_input_win.geometry("200x150")
team_name_input.withdraw()
first = Label(name_input_win, text = "Enter player " + str(player_num) + " for " + str(current_team)).grid(row = 0, column = 1)
name_input = Entry(name_input_win)
name_input.grid(row = 1, column = 1)
name = str(name_input.get())
for i in range(0, player_num):
p = None
while not p or p in team_array:
#first = Label(name_input, text="Enter player " + str(player_num) + " for " + str(current_team)).grid(row=0,column=1)
if p in team_array:
error = Label(name_input, text = "Player already entered").grid(row = 2, column = 1)
team_array.append(p)
player_num = player_num + 1
Any help will be appriciated ^-^

My python program works on Linux but not on Widows?

So my program compares images and deletes any that are the same, renaming the original to how many were deleted. This program works fine on my Linux (ubuntu) but when used on my Windows 8 laptop I get the error at the bottom, any advice is greatly appreciated.
PIL.UnidentifiedImageError: cannot identify image file 'C:\\Users\\Public\\Pictures\\Sample Pictures/desktop.ini'
(there is more to the error code if you need it, also I import os, send2trash, pil, shutil and tkinter to use with the script)
import os
from PIL import ImageChops, ImageDraw
import PIL.Image
import shutil
from send2trash import send2trash
from tkinter import *
root = Tk()
root.title("Cupcake 3.0")
paths = Entry(root, width = 50, borderwidth = 5)
paths.grid(row = 2, column =2, columnspan =3)
path = paths.get()
def add():
end_image = PIL.Image.new(mode = "RGB",size = (200, 70), color = "red")
end_image.save(paths.get() +"/zzz999.png")
files = os.listdir(paths.get())
files.sort()
image1 =files[0]
counter = 1
im1 = " "
for file in files:
original_file_name, file_ext = (os.path.splitext(file))
if delete == 0:
ofn, fe = (os.path.splitext(image1))
if image1 == file:
pass
elif image1 != file:
im1 = PIL.Image.open(paths.get() + "/" + image1).histogram() #the image to be compared too
im2 = PIL.Image.open(paths.get() + "/" + file).histogram()#file for comparison
if im1 == im2:
send2trash(paths.get() + "/" +file)
counter = counter +1
elif im1 != im2:
os.rename(paths.get() + "/" + image1, paths.get() + "/" + ofn + "_X" +str(counter)+ fe)
counter = 1
image1 = file
else:
print("something went wrong")
else:
addd = input("Enter in the text you wish to be added/removed (can not contain blank spaces): ").strip()
new_name = "{}{}{}".format(original_file_name, addd, file_ext).strip()
os.rename(path + "/" + file, path + "/" + new_name)
print("Job Complete")
send2trash(paths.get() + "/zzz999.png")
welcome = Label(root, text = "Welcome to Cupcake 3.0")
welcome.grid(row = 0, column =2, columnspan =3)
l1 = Label (root, text = "Please enter the path to your folder: ")
l1.grid(row = 1, column =2, columnspan =3)
paths = Entry(root, width = 50, borderwidth = 5)
paths.grid(row = 2, column =2, columnspan =3)
path = paths.get()
d = IntVar()
Radiobutton(root, text = "Add", variable = d, value = 1, anchor = W).grid(row = 3, column = 2, sticky = W)
Radiobutton(root, text = "Remove", variable = d, value = 2,anchor = W).grid(row = 4, column = 2, sticky = W)
def_question = d.get()
l2 = Label (root, text = "Enter text you want removed (leave blank if n/a): ").grid(row = 6, column = 2)
rem = Entry(root, width = 50, borderwidth = 5)
rem.grid(row = 7, column =2, columnspan =3)
remo=rem.get().strip()
de = IntVar()
c = Checkbutton(root, text = "Do you wish to delete duplicate files?", variable = de)
c.grid(row = 8, column =2, sticky = W)
delete = de.get()
def run():
#print(d.get())
#print(def_question)
if d.get() == 1:
add()
elif d.get() == 2:
remove()
else:
print("I don't understand your command")
def remove():
files = os.listdir(paths.get())
files.sort()
for file in files:
original_file_name, file_ext = (os.path.splitext(file))
#print(remo)
new_name = original_file_name.replace(rem.get(), "").strip()
os.rename(paths.get() + "/" + file, paths.get() + "/" + new_name)
print("Job Complete")
submit = Button(root, text = "Run", command =lambda: run())
submit.grid(row = 9, column =2)
root.mainloop()
"
Thats my entire program
Try to filter out the files which are not identified as images by PIL. Something like this might work for you
def image_filter(filename):
file_path = os.path.join(paths.get(), filename)
try:
im = PIL.Image.open(file_path)
im.verify()
im.close()
return True
except: # you can handle PIL.UnidentifiedImageError here
return False
def add():
...
files = os.listdir(path)
# filter out the files which are not images
files = list(filter(image_filter, files))
files.sort()
image1 = files[0]
...

Resources