Python-Tk Inter Object Oriented Programming inheriting attributes - python

So my program is a quiz where there is a main class that is an overall reaction pathway with sub reaction pathways in other classes. How do I inherit the buttons and labels defined in one page like QUESTIONSTARTER and can be displayed on another class which is STAGE 2. This is a big problem for me i hope you can help me. These are examples of the 2 classes: (I couldnt add one more method in question starter) so I want buttons and labels from question starter to be inherited to stage 2 where i can grid the buttons into stage 2.
class SETOFQUESTIONS(QUESTIONSTARTER):
def __init__ (self):
self.NumberOfStages = NumberOfStages
self.StartingReactant = StartingReactant
def SetStages(self, NumberOfStages):
#If the quiz type is default and customised set number of stages to a minimum of 3 stages and a max of 5 stages for aliphatic reaction
#for aromatic -set min stages 2 and max stages 5
if "Default" == True:
self.NumberOfStages = 5
print ("Number Of Stages = ",NumberOfStages)
return NumberOfStages
else:
self.NumberOfStages = CustomisedNumberOfStages
print ("Number Of Stages = ",CustomisedNumberOfStages)
#Sets Max Number of Stages
def SetNonCompulsoryReagents(self):
SetCompulsoryReagentOptionList(self)
ReagentsList = []
while ReagentsList == True:
for count in range (len(ReagentsList)):
try:
sql = ("""SELECT ReagentName FROM NonCompulsoryReagentDatabase \
ORDER BY RAND() \
LIMIT 1""")
conn.execute(sql)
NonCompulsoryReagents = conn.fetchone()
except:
conn.rollback()
if NonCompulsoryReagents[0] != ReagentsList[count]:
ReagentsList.append(NonCompulsoryReagents[0])
ReagentsList = False
elif NonCompulsoryReagents[1] != ReagentsList[count]:
ReagentsList.append(NonCompulsoryReagents[1])
ReagentsList = False
elif NonCompulsoryReagents[2] != ReagentsList[count]:
ReagentsList.append(NonCompulsoryReagents[2])
ReagentsList = False
else:
ReagentsList = True
for Reagent in ReagentsList:
RandomReagent = random.choice(ReagentsList)
ReagentOption1 = tk.Button(bottomFrame, text = RandomReagent, command=lambda: self.AllocatePoints(1))
ReagentOption2 = tk.Button(bottomFrame, text = RandomReagent, command=lambda: self.AllocatePoints(2))
ReagentOption3 = tk.Button(bottomFrame, text = RandomReagent, command=lambda: self.AllocatePoints(3))
ReagentOption4 = tk.Button(bottomFrame, text = RandomReagent, command=lambda: self.AllocatePoints(4))
def SetNonCompulsoryConditions(self):
SetCompulsoryConditionOptionList(self)
sql = ("""SELECT ConditionName FROM NonCompulsoryConditionsDatabase \
ORDER BY RAND () \
LIMIT 1""")
try:
conn.execute(sql)
NonCompulsoryConditions = conn.fetchone()
except:
conn.rollback()
while ConditionsList == True:
for count in range (len(ConditionsList)):
sql = ("""SELECT ConditionName FROM NonCompulsoryConditionsDatabase \
ORDER BY RAND() \
LIMIT 1""")
conn.execute(sql)
NonCompulsoryReagents = conn.fetchone()
if NonCompulsoryConditions[0] != ConditionsList[count]:
ConditionsList.append(NonCompulsoryReagents[0])
ConditionsList = False
elif NonCompulsoryConditions[1] != ConditionsList[count]:
ConditionsList.append(NonCompulsoryConditions[1])
ConditionsList = False
elif NonCompulsoryConditions[2] != ConditionsList[count]:
ConditionsList.append(NonCompulsoryConditions[2])
ConditionsList = False
else:
ConditionsList = True
for Condition in ConditionsList:
RandomCondition = random.choice(ConditionsList)
ConditionOption1 = tk.Button(bottomFrame, text = RandomCondition, command=lambda: self.AllocatePoints(5))
ConditionOption2 = tk.Button(bottomFrame, text = RandomCondition, command=lambda: self.AllocatePoints(6))
ConditionOption3 = tk.Button(bottomFrame, text = RandomCondition, command=lambda: self.AllocatePoints(7))
ConditionOption4 = tk.Button(bottomFrame, text = RandomCondition, command=lambda: self.AllocatePoints(8))
#call at random the specific products from product database
#depending on class run
def ButtonPressed(self,ReagentsList):
ReagentsList[0] = CorrectReagent
self.CorrectReagent.configure(bg = 'green')
IncorrectReagentsList = []
IncorrectReagentsList.append(ReagentsList[1])
IncorrectReagentsList.append(ReagentsList[2])
IncorrectReagentsList.append(ReagentsList[3])
for Reagents in IncorrectReagentsList:
tk.Button[Reagents].configure(bg = "red")
ConditionsList[0] = CorrectCondition
self.CorrectCondition.configure(bg = "green")
IncorrectConditionsList = []
IncorrectConditionsList.append(ReagentsList[1])
IncorrectConditionsList.append(ReagentsList[2])
IncorrectConditionsList.append(ReagentsList[3])
for Reagents in IncorrectReagentsList:
tk.Button[Reagents].configure(bg = "red")
class STAGE2(SETOFQUESTIONS):
def __init__(self,parent, controller):
tk.Frame.__init__(self, parent)
QuestionFrame.tkraise()
controller.show_frame(QuestionFrame)
Question.pack(side = "top")
Question.grid()
ReagentOption1.grid(column = 0,row = 0)
ReagentOption2.grid(column = 0,row = 1)
ReagentOption3.grid(column = 0,row = 2)
ReagentOption4.grid(column = 0,row = 3)
ConditionOption1.grid(column = 0,row = 0)
ConditionOption2.grid(column = 0,row = 1)
ConditionOption3.grid(column = 0,row = 2)
ConditionOption4.grid(column = 0,row = 3)
Continue = tk.Button(StageFrame, text = "Continue", command=lambda: controller.show_frame(Stage2))
Continue.grid(column = 6)
PointsLabel.grid(row=0,column=6)
AttemptsDisplayed.grid(row=1,column=7)

Related

in tkinter.entry using in for loop but when value changed that effect all entery

Here is the code of my application
problem
I have used tkinter Entry() method in for loop in ShowOpeanFile() function and I have make One global list variable where I stored the return value of Entry() but when I enter value in that Entry field it effect on all Entry. But I don't want that.
#importing Required library
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
import pandas as pd
from functools import reduce
#Global Variables to Store FilePath That OPEAN
Opean_file_path = []
#Making gloabl datagram object store variable
datgramoffileVariable = []
datagram_list = []
finaldatagram_list = []
#get Filename and qauntity
def getvalue(i):
if Opean_file_path[i][2].get().isnumeric():
return Opean_file_path[i][1],Opean_file_path[i][2].get(),Opean_file_path[i][0]
else:
return -1
#variable making function for file that map each open file during converxlsx function
def variablemaking(size):
temp = []
for number in range(size):
temp.append(str(number))
temp = (list(set(temp)))
datgramoffileVariable.clear()
for i in range(len(temp)):
datgramoffileVariable.append(temp[i])
#conevrting all file to dataGram using pandas library
def Converxlsx():
#makingVariable functioncall
variablemaking(len(Opean_file_path))
#Now variable Making function Done
#Go for the convert datagram to file
for i in range(len(datgramoffileVariable)):
datgramoffileVariable[i] = pd.DataFrame(pd.read_excel(Opean_file_path[i][0]))
for i in range(len(datgramoffileVariable)):
print(datgramoffileVariable[i])
#subpart of Compute function find in list return filepath
def find(target):
for i in range(len(Opean_file_path)):
if(Opean_file_path[i][1] == target):
return Opean_file_path[i][0]
return -1
def findindex(tar):
for i in range(len(Opean_file_path)):
print(Opean_file_path[i][0])
if(Opean_file_path[i][0] == tar):
return i
#ComputeFile function
def compute():
for i in range(len(Opean_file_path)):
v = getvalue(i)
if v == -1:
pass
else:
answerOffind = v[0]
if( answerOffind == -1):
if(label_for_error.cget('text') == "enter right file name"):
label_for_error.config(text="")
else:
label_for_error.config(text="enter right file name", fg='red')
else:
label_for_error.config(text="")
if(len(v[1]) == 0 or v[1].isalpha() or v[1] == ' '):
label_for_error.config(text="enter right Qauntity", fg='red')
pass
else:
if v[1].isnumeric():
if(label_for_error.cget('text') == "enter right Qauntity"):
label_for_error.config(text='')
indexofmaniuplation = findindex(v[2])
print(indexofmaniuplation)
datgramoffileVariable[indexofmaniuplation].qauntity = datgramoffileVariable[indexofmaniuplation].qauntity * int(v[1])
# opeanfile function
def ShowOpeanFile():
col = 0
ro = 0
for i in range(len(Opean_file_path)):
ro = ro + 1
for j in range(len(Opean_file_path[i])):
if j > 1:
Opean_file_path[i][j] = tk.Entry(window,width=20,textvariable=1)
Opean_file_path[i][j].grid(row=ro,column=col)
else:
e = tk.Entry(window, width=20, fg='blue')
e.grid(row=ro,column=col)
e.insert(tk.END,Opean_file_path[i][j])
col = col + 1
col = col - 2
for i in range(len(Opean_file_path)):
for j in range(len(Opean_file_path[i])):
print(Opean_file_path[i][j])
#browsefile function
def browseFiles():
#opeanFile only allow Excel file
'''
askopenfile return file path of selected file
it return type is String
'''
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a File",
filetypes = [("Excel file","*.xlsx"),("Excel file", "*.xls")]
)
#After getting filepath storing into Opean_file_path list
if(filename in Opean_file_path):
pass
else:
tmp = []
tmp.append(filename)
f=filename.split('/')
tmp.append(f[-1])
tmp.append('qauntitybox')
Opean_file_path.append(tmp)
print(tmp)
Converxlsx()
ShowOpeanFile()
# print(Opean_file_path)
#making final CSV File function.
def csv_making():
datagram_list.clear()
finaldatagram_list.clear()
#convert dataframe into list
for i in range(len(datgramoffileVariable)):
datagram_list.extend(datgramoffileVariable[i].values.tolist())
#find repted element and compute all at one single
repted_element = []
datagram_index_to_be_removed=[]
for i in range(len(datagram_list)):
temp_id = datagram_list[i][0]
temp_Qauntity = datagram_list[i][1]
for j in range(i+1,len(datagram_list)):
if datagram_list[j][0] == temp_id:
temp_Qauntity = temp_Qauntity + datagram_list[j][1]
datagram_index_to_be_removed.append(j)
datagram_index_to_be_removed.append(i)
if [temp_id,temp_Qauntity] not in repted_element and datagram_list[j][0] == temp_id:
repted_element.append([temp_id,temp_Qauntity])
datagram_index_to_be_removed = list(tuple(datagram_index_to_be_removed))
#remove repeted element
datagram_index_to_be_removed.sort()
for i in range(len(datagram_list)):
if i in datagram_index_to_be_removed:
pass
else:
finaldatagram_list.append(datagram_list[i])
#add repted_element
for i in repted_element:
finaldatagram_list.append(i)
#print final data
# print(finaldatagram_list)
#convert final list to csv
id = []
qauntityto = []
for i in range(len(finaldatagram_list)):
id.append(finaldatagram_list[i][0])
qauntityto.append(finaldatagram_list[i][1])
dict = {'id':id,'qauntity':qauntityto}
df = pd.DataFrame(data=dict)
pathofnewfile = df.to_csv('/home/vegg/Desktop/out.csv',index=False)
print(pathofnewfile)
label_for_error.config(text='file save at /home/vegg/Desktop/out.csv',fg='blue')
#UI
window = tk.Tk()
scrollbar = tk.Scrollbar()
frame = tk.Frame(window)
window.geometry("750x400")
label_for_qautity = tk.Label(window ,text="Enter the Qauntity",
width=50,height=3)
label_for_qautity.grid(column=2,row=0)
# Qauntity = tk.Entry()
# Qauntity.grid(column=2,row=1)
label_for_fileNamepath = tk.Label(window ,text="File Name path",
width=20,height=3)
label_for_fileNamepath.grid(column=0,row=0)
label_for_fileName = tk.Label(window ,text="File Name",
width=20,height=3)
label_for_fileName.grid(column=1,row=0)
label_for_error = tk.Label(window ,text="",
width=20,height=3)
label_for_error.grid(column=4,row=3)
button_explore = tk.Button(window,
text = "Browse Files here",
command=lambda :[browseFiles()] )
button_Compute = tk.Button(window,
text = "Compute File Data",
command=lambda :[compute()] )
button_CSV = tk.Button(window,
text = "Create CSV Here",
command=lambda :[csv_making()] )
button_explore.grid(column=4,row=0)
button_Compute.grid(column=4,row=1)
button_CSV.grid(column=4, row=2)
window.mainloop()
Image
I want to add different value for entry not same value effect to all entry.

VTK textactor not showing

I'm using VTK to show textactor with info 'ID' added to the actors. When my mouse is over an actor, the MouseEvent will call an 'add_text' function. The function was called and printed the correct 'ID' but there's no textactor adding to the window, is there any problem with my program?
class MouseInteractorHighLightActor(vtk.vtkInteractorStyleTrackballCamera):
def __init__(self, parent=None):
self.AddObserver("MouseMoveEvent", self.MouseMove)
self.LastPickedActor = None
self.LastPickedProperty = vtk.vtkProperty()
self.new = vtkTextActor()
self.old = vtkTextActor()
self.on_actor = False
def add_text(self,renderer,ID):
self.new.SetInput(ID)
txtprop = self.new.GetTextProperty()
txtprop.SetFontSize(36)
self.new.SetDisplayPosition(0,0)
# renderer.RemoveActor(self.old)
self.old = self.new
if self.on_actor:
renderer.AddActor(self.new)
print("add_text called , ID : ",ID)
else:
pass
# renderer.RemoveActor(self.old)
# renderer.RemoveActor(self.new)
def MouseMove(self,obj,event):
Mousepos = self.GetInteractor().GetEventPosition()
picker = vtk.vtkPropPicker()
picker.Pick(Mousepos[0], Mousepos[1], 0, self.GetDefaultRenderer())
self.NewPickedActor = picker.GetActor()
if self.NewPickedActor:
if not self.on_actor:
self.on_actor = True
print("on actor")
info = self.NewPickedActor.GetProperty().GetInformation()
info = str(info)
pattern_1 = re.compile(r"ID.*\d+")
pattern_2 = re.compile(r"\d+")
string = pattern_1.findall(info)[0]
ID = pattern_2.findall(string)[0]
# print("ID : ",ID)
self.add_text(self.GetDefaultRenderer() , ID)
if self.LastPickedActor:
self.LastPickedActor.GetProperty().DeepCopy(self.LastPickedProperty)
self.LastPickedProperty.DeepCopy(self.NewPickedActor.GetProperty())
self.NewPickedActor.GetProperty().SetDiffuse(1.0)
self.NewPickedActor.GetProperty().SetSpecular(0.0)
self.LastPickedActor = self.NewPickedActor
else:
pass
else:
print("not on actor")
self.on_actor = False
Update , the problem is solved, source code :
class MouseInteractorHighLightActor(vtk.vtkInteractorStyleTrackballCamera):
def __init__(self, parent=None):
self.AddObserver("LeftButtonPressEvent", self.leftButtonPressEvent)
self.AddObserver("LeftButtonReleaseEvent", self.leftButtonReleaseEvent)
self.AddObserver("MouseMoveEvent", self.MouseMove)
self.LastPickedActor = None
self.LastPickedProperty = vtk.vtkProperty()
self.new = vtkTextActor()
self.old = vtkTextActor()
self.on_actor = False
self.picker = vtk.vtkPropPicker()
def add_text(self,renderer,ID):
self.new.SetInput(ID)
txtprop = self.new.GetTextProperty()
txtprop.SetFontSize(72)
self.new.SetDisplayPosition(0,0)
self.old = self.new
if self.on_actor:
renderer.AddActor(self.new)
# print("ID : ",ID)
def MouseMove(self,obj,event):
Mousepos = self.GetInteractor().GetEventPosition()
picker = vtk.vtkPropPicker()
picker.Pick(Mousepos[0], Mousepos[1], 0, self.GetDefaultRenderer())
self.NewPickedActor = picker.GetActor()
if self.NewPickedActor:
self.on_actor = True
# print("on actor")
info = self.NewPickedActor.GetProperty().GetInformation()
info = str(info)
pattern_1 = re.compile(r"ID.*\d+")
pattern_2 = re.compile(r"\d+")
string = pattern_1.findall(info)[0]
ID = pattern_2.findall(string)[0]
# print("ID : ",ID)
self.add_text(self.GetDefaultRenderer() , ID)
if self.LastPickedActor:
self.LastPickedActor.GetProperty().DeepCopy(self.LastPickedProperty)
self.LastPickedProperty.DeepCopy(self.NewPickedActor.GetProperty())
self.NewPickedActor.GetProperty().SetDiffuse(1.0)
self.NewPickedActor.GetProperty().SetSpecular(0.0)
self.LastPickedActor = self.NewPickedActor
self.OnLeftButtonDown()
self.OnLeftButtonUp()
else:
if self.LastPickedActor:
self.LastPickedActor.GetProperty().DeepCopy(self.LastPickedProperty)
self.on_actor = False
self.GetDefaultRenderer().RemoveActor(self.new)
self.GetDefaultRenderer().RemoveActor(self.old)
self.OnLeftButtonDown()
self.OnLeftButtonUp()
def leftButtonPressEvent(self, obj, event):
self.RemoveObservers("MouseMoveEvent")
self.OnLeftButtonDown()
def leftButtonReleaseEvent(self, obj, event):
self.AddObserver("MouseMoveEvent",self.MouseMove)
self.OnLeftButtonUp()

Trying to get the validate command to work with multiple inputs

I'm not at all familiar with Tkinter's validatecommands, but I have done some research and would like to implement it in a widget that creates a tree graph from a bunch of entries. I want to restrict each entry so that the user can create lists of numbers from 0 to the highest row, not including the same row. So, for example, Row 0 entry can't have 0 in it or 12. So far I have only attempted to restrict the input from being the same value as the row, but I haven't been able to get that to work. I must be implementing the validate command incorrectly.
Any help would be much appreciated.
import tkinter as tk
class widget:
def __init__(self,master):
# vcmd = (master.register(self.validate),
# '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
self.master = master
self.entryNumbers = tk.Entry(master,justify = tk.CENTER)
self.entryNumbers.insert(0, "5")
self.entryNumbers.grid(row = 0,column = 0,columnspan =2,sticky="EW")
self.createEntriesButton = tk.Button(master,text = "Create Entries",command = self.createEntries)
self.createEntriesButton.grid(row = 1, column = 0,columnspan = 2,sticky="EW")
def createEntries(self):
self.entryNumbers.grid_forget()
self.createEntriesButton.grid_forget()
self.entries = []
self.entryLabels = []
vcmd = self.master.register(self.validateEntry)
for i in range(int(self.entryNumbers.get())):
self.entryLabels.append(tk.Label(self.master,text = "Row {}".format(i)))
self.entryLabels[-1].grid(row = i,column = 0)
self.entries.append(tk.Entry(self.master, validatecommand=(vcmd,'%P',i)))
self.entries[-1].grid(row = i,column = 1)
self.addEntriesButton = tk.Button(self.master,text = "Add Entries",command = self.addEntry)
self.addEntriesButton.grid(row = i+1, column = 0,columnspan = 2,sticky="EW")
def addEntry(self):
count = len(self.entries)
vcmd = self.master.register(self.validateEntry)
self.entryLabels.append(tk.Label(self.master,text = "Row {}".format(count)))
self.entryLabels[-1].grid(row = count+1,column = 0)
self.entries.append(tk.Entry(self.master, validatecommand=(vcmd,'%P',count)))
self.entries[-1].grid(row = count+1,column = 1)
self.addEntriesButton.grid(row = count+2, column = 0,columnspan = 2,sticky="EW")
def validateEntry(self,P,row):
if P != row:
return True
else:
return False
root1=tk.Tk()
widget(root1)
root1.mainloop()
Also, can vcmd be a member variable? I would like to only initialize it once?
I figured it out using a lambda function:
vcmd = lambda row:(self.master.register(self.validateEntry),'%P',row)
for i in range(int(self.entryNumbers.get())):
self.entryLabels.append(tk.Label(self.master,text = "Row {}".format(i)))
self.entryLabels[-1].grid(row = i,column = 0)
self.entries.append(tk.Entry(self.master, validate = "all", validatecommand=vcmd(i)))

Let the GUI continue working after crashing without having to reset device

My current GUI is to show target tracking from a TI processor to PC via UART. Sometimes, GUI crashes due to UART performance. But everytime I want to reset GUI, I also have to reset my TI device. So I want to modify python code so as to only re-open GUI, enter COM port without having to reset device whenever GUI crashes.
Currently, each time GUI crashes, even though I re-opened GUI but didn't reset device (power off & on), I can not continue tracking.
I put python code for GUI below.In this GUI python program, we have 2 blanks & button to enter UART COM port, 2 buttons to select & send configuration to device. Then it can begin tracking.
I'm considering to modify the part of sendCfg(self), but still not sure how to make it work as my purpose due to my lack of experience in Python & GUI design. Please help me with sample code for this task.
class Window(QDialog):
def __init__(self, parent=None, size=[]):
super(Window, self).__init__(parent)
#when running Gree Demo
self.Gree = 1
# set window toolbar options, and title. #deb_gp
self.setWindowFlags(
Qt.Window |
Qt.CustomizeWindowHint |
Qt.WindowTitleHint |
Qt.WindowMinimizeButtonHint |
Qt.WindowMaximizeButtonHint |
Qt.WindowCloseButtonHint
)
self.setWindowTitle("mmWave People Counting")
print('Python is ', struct.calcsize("P")*8, ' bit')
print('Python version: ', sys.version_info)
gridlay = QGridLayout()
gridlay.addWidget(self.comBox, 0,0,1,1)
gridlay.addWidget(self.statBox, 1,0,1,1)
gridlay.addWidget(self.configBox,2,0,1,1)
gridlay.addWidget(self.plotControlBox,3,0,1,1)
gridlay.addWidget(self.boxTab,4,0,1,1)
gridlay.addWidget(self.spBox,5,0,1,1)
gridlay.addWidget(self.graphTabs,0,1,6,1)
gridlay.addWidget(self.gw, 0, 2, 6, 1)
#gridlay.addWidget(self.demoData, 0,3,1,2)
#gridlay.addWidget(self.hPlot,1,3,4,2)
gridlay.setColumnStretch(0,1)
gridlay.setColumnStretch(1,3)
self.setLayout(gridlay)
#
# left side pane layout
#
def setConnectionLayout(self):
self.comBox = QGroupBox('Connect to Com Ports')
self.uartCom = QLineEdit('') #deb_gp
self.dataCom = QLineEdit('') #deb_gp
self.uartLabel = QLabel('UART COM:')
self.dataLabel = QLabel('DATA COM:')
self.connectStatus = QLabel('Not Connected')
self.connectButton = QPushButton('Connect')
self.connectButton.clicked.connect(self.connectCom)
self.configLabel = QLabel('Config Type:')
self.configType = QComboBox()
self.configType.addItems(["3D People Counting", "SDK Out of Box Demo", "Long Range People Detection", "Indoor False Detection Mitigation", "(Legacy) 2D People Counting", "(Legacy): Overhead People Counting"])
self.comLayout = QGridLayout()
self.comLayout.addWidget(self.uartLabel,0,0)
self.comLayout.addWidget(self.uartCom,0,1)
self.comLayout.addWidget(self.dataLabel,1,0)
self.comLayout.addWidget(self.dataCom,1,1)
self.comLayout.addWidget(self.configLabel,2,0)
self.comLayout.addWidget(self.configType,2,1)
self.comLayout.addWidget(self.connectButton,3,0)
self.comLayout.addWidget(self.connectStatus,3,1)
self.comBox.setLayout(self.comLayout)
def setConfigLayout(self):
self.configBox = QGroupBox('Configuration')
self.selectConfig = QPushButton('Select Configuration')
self.sendConfig = QPushButton('Send Configuration')
self.selectConfig.clicked.connect(self.selectCfg)
self.sendConfig.clicked.connect(self.sendCfg)
self.configTable = QTableWidget(5,2)
#set parameter names
self.configTable.setItem(0,0,QTableWidgetItem('Radar Parameter'))
self.configTable.setItem(0,1,QTableWidgetItem('Value'))
self.configTable.setItem(1,0,QTableWidgetItem('Max Range'))
self.configTable.setItem(2,0,QTableWidgetItem('Range Resolution'))
self.configTable.setItem(3,0,QTableWidgetItem('Max Velocity'))
self.configTable.setItem(4,0,QTableWidgetItem('Velcoity Resolution'))
self.configLayout = QVBoxLayout()
self.configLayout.addWidget(self.selectConfig)
self.configLayout.addWidget(self.sendConfig)
self.configLayout.addWidget(self.configTable)
#self.configLayout.addStretch(1)
self.configBox.setLayout(self.configLayout)
def updateGraph(self, parsedData):
updateStart = int(round(time.time()*1000))
self.useFilter = 0
classifierOutput = []
pointCloud = parsedData[0]
targets = parsedData[1]
indexes = parsedData[2]
numPoints = parsedData[3]
numTargets = parsedData[4]
self.frameNum = parsedData[5]
fail = parsedData[6]
classifierOutput = parsedData[7]
fallDetEn = 0
indicesIn = []
if (fail != 1):
#left side
pointstr = 'Points: '+str(numPoints)
targetstr = 'Targets: '+str(numTargets)
self.numPointsDisplay.setText(pointstr)
self.numTargetsDisplay.setText(targetstr)
#right side fall detection
peopleStr = 'Number of Detected People: '+str(numTargets)
if (numTargets == 0):
fdestr = 'Fall Detection Disabled - No People Detected'
elif (numTargets == 1):
fdestr = 'Fall Detection Enabled'
fallDetEn = 1
elif (numTargets > 1):
fdestr = 'Fall Detected Disabled - Too Many People'
#self.numDetPeople.setText(peopleStr)
#self.fallDetEnabled.setText(fdestr)
if (len(targets) < 13):
targets = []
classifierOutput = []
if (fail):
return
#remove static points
if (self.configType.currentText() == '3D People Counting'):
if (not self.staticclutter.isChecked()):
statics = np.where(pointCloud[3,:] == 0)
try:
firstZ = statics[0][0]
numPoints = firstZ
pointCloud = pointCloud[:,:firstZ]
indexes = indexes[:,:self.previousFirstZ]
self.previousFirstZ = firstZ
except:
firstZ = -1
#point cloud persistence
fNum = self.frameNum%10
if (numPoints):
self.previousCloud[:5,:numPoints,fNum] = pointCloud[:5,:numPoints]
self.previousCloud[5,:len(indexes),fNum] = indexes
self.previousPointCount[fNum]=numPoints
#plotting 3D - get correct point cloud (persistent points and synchronize the frame)
if (self.configType.currentText() == 'SDK3xPeopleCount'):
pointIn = pointCloud
else:
totalPoints = 0
persistentFrames = int(self.persistentFramesInput.currentText())
#allocate new array for all the points
for i in range(1,persistentFrames+1):
totalPoints += self.previousPointCount[fNum-i]
pointIn = np.zeros((5,int(totalPoints)))
indicesIn = np.ones((1, int(totalPoints)))*255
totalPoints = 0
#fill array
for i in range(1,persistentFrames+1):
prevCount = int(self.previousPointCount[fNum-i])
pointIn[:,totalPoints:totalPoints+prevCount] = self.previousCloud[:5,:prevCount,fNum-i]
if (numTargets > 0):
indicesIn[0,totalPoints:totalPoints+prevCount] = self.previousCloud[5,:prevCount,fNum-i]
totalPoints+=prevCount
if (self.graphFin):
self.plotstart = int(round(time.time()*1000))
self.graphFin = 0
if (self.threeD):
try:
indicesIn = indicesIn[0,:]
except:
indicesIn = []
self.get_thread = updateQTTargetThread3D(pointIn, targets, indicesIn, self.scatter, self.pcplot, numTargets, self.ellipsoids, self.coordStr, classifierOutput, self.zRange, self.gw, self.plotByIndex.isChecked(), self.plotTracks.isChecked(), self.bbox,self.boundaryBoxes[0]['checkEnable'].isChecked())
self.get_thread.done.connect(self.graphDone)
self.get_thread.start(priority=QThread.HighestPriority-1)
else:
npc = pointIn[0:2,:]
print (np.shape(npc))
self.legacyThread = update2DQTGraphThread(npc, targets, numTargets, indexes, numPoints, self.trailData, self.activeTrail, self.trails, self.scatter2D, self.gatingScatter)
self.legacyThread.done.connect(self.graphDone)
self.legacyThread.start(priority=QThread.HighestPriority-1)
else:
return
#pointIn = self.previousCloud[:,:int(self.previousPointCount[fNum-1]),fNum-1]
#state tracking
if (numTargets > 0):
self.lastFrameHadTargets = True
else:
self.lastFrameHadTargets = False
if (numTargets):
self.lastTID = targets[0,:]
else:
self.lastTID = []
def graphDone(self):
plotend = int(round(time.time()*1000))
plotime = plotend - self.plotstart
try:
if (self.frameNum > 1):
self.averagePlot = (plotime*1/self.frameNum) + (self.averagePlot*(self.frameNum-1)/(self.frameNum))
else:
self.averagePlot = plotime
except:
self.averagePlot = plotime
self.graphFin = 1
pltstr = 'Average Plot time: '+str(plotime)[:5] + ' ms'
fnstr = 'Frame: '+str(self.frameNum)
self.frameNumDisplay.setText(fnstr)
self.plotTimeDisplay.setText(pltstr)
def resetFallText(self):
self.fallAlert.setText('Standing')
self.fallPic.setPixmap(self.standingPicture)
self.fallResetTimerOn = 0
def updateFallThresh(self):
try:
newThresh = float(self.fallThreshInput.text())
self.fallThresh = newThresh
self.fallThreshMarker.setPos(self.fallThresh)
except:
print('No numberical threshold')
def connectCom(self):
#get parser
self.parser = uartParserSDK(type=self.configType.currentText())
self.parser.frameTime = self.frameTime
print('Parser type: ',self.configType.currentText())
#init threads and timers
self.uart_thread = parseUartThread(self.parser)
if (self.configType.currentText() != 'Replay'):
self.uart_thread.fin.connect(self.parseData)
self.uart_thread.fin.connect(self.updateGraph)
self.parseTimer = QTimer()
self.parseTimer.setSingleShot(False)
self.parseTimer.timeout.connect(self.parseData)
try:
uart = "COM"+ self.uartCom.text() #deb_gp
data = "COM"+ self.dataCom.text() #deb_gp
#TODO: find the serial ports automatically.
self.parser.connectComPorts(uart, data)
self.connectStatus.setText('Connected') #deb_gp
self.connectButton.setText('Disconnect') #deb_gp
#TODO: create the disconnect button action
except:
self.connectStatus.setText('Unable to Connect')
if (self.configType.currentText() == "Replay"):
self.connectStatus.setText('Replay')
if (self.configType.currentText() == "Long Range People Detection"):
self.frameTime = 400
#
# Select and parse the configuration file
# TODO select the cfgfile automatically based on the profile.
def selectCfg(self):
try:
self.parseCfg(self.selectFile())
except:
print('No cfg file selected!')
def selectFile(self):
fd = QFileDialog()
filt = "cfg(*.cfg)"
filename = fd.getOpenFileName(directory='./../chirp_configs',filter=filt) #deb_gp - added folder name
return filename[0]
def parseCfg(self, fname):
cfg_file = open(fname, 'r')
self.cfg = cfg_file.readlines()
counter = 0
chirpCount = 0
for line in self.cfg:
args = line.split()
if (len(args) > 0):
if (args[0] == 'cfarCfg'):
zy = 4
#self.cfarConfig = {args[10], args[11], '1'}
elif (args[0] == 'AllocationParam'):
zy=3
#self.allocConfig = tuple(args[1:6])
elif (args[0] == 'GatingParam'):
zy=2
#self.gatingConfig = tuple(args[1:4])
elif (args[0] == 'SceneryParam' or args[0] == 'boundaryBox'):
self.boundaryLine = counter
self.profile['leftX'] = float(args[1])
self.profile['rightX'] = float(args[2])
self.profile['nearY'] = float(args[3])
self.profile['farY'] = float(args[4])
self.setBoundaryTextVals(self.profile)
self.boundaryBoxes[0]['checkEnable'].setChecked(True)
elif (args[0] == 'staticBoundaryBox'):
self.staticLine = counter
elif (args[0] == 'profileCfg'):
self.profile['startFreq'] = float(args[2])
self.profile['idle'] = float(args[3])
self.profile['adcStart'] = float(args[4])
self.profile['rampEnd'] = float(args[5])
self.profile['slope'] = float(args[8])
self.profile['samples'] = float(args[10])
self.profile['sampleRate'] = float(args[11])
print(self.profile)
elif (args[0] == 'frameCfg'):
self.profile['numLoops'] = float(args[3])
self.profile['numTx'] = float(args[2])+1
elif (args[0] == 'chirpCfg'):
chirpCount += 1
elif (args[0] == 'sensorPosition'):
self.profile['sensorHeight'] = float(args[1])
self.profile['az_tilt'] = float(args[2])
self.profile['elev_tilt'] = float(args[3])
counter += 1
maxRange = self.profile['sampleRate']*1e3*0.9*3e8/(2*self.profile['slope']*1e12)
#update boundary box
self.drawBoundaryGrid(maxRange)
#update chirp table values
bw = self.profile['samples']/(self.profile['sampleRate']*1e3)*self.profile['slope']*1e12
rangeRes = 3e8/(2*bw)
Tc = (self.profile['idle']*1e-6 + self.profile['rampEnd']*1e-6)*chirpCount
lda = 3e8/(self.profile['startFreq']*1e9)
maxVelocity = lda/(4*Tc)
velocityRes = lda/(2*Tc*self.profile['numLoops']*self.profile['numTx'])
self.configTable.setItem(1,1,QTableWidgetItem(str(maxRange)[:5]))
self.configTable.setItem(2,1,QTableWidgetItem(str(rangeRes)[:5]))
self.configTable.setItem(3,1,QTableWidgetItem(str(maxVelocity)[:5]))
self.configTable.setItem(4,1,QTableWidgetItem(str(velocityRes)[:5]))
#update sensor position
self.az_tilt.setText(str(self.profile['az_tilt']))
self.elev_tilt.setText(str(self.profile['elev_tilt']))
self.s_height.setText(str(self.profile['sensorHeight']))
def sendCfg(self):
try:
if (self.configType.currentText() != "Replay"):
self.parser.sendCfg(self.cfg)
self.configSent = 1
self.parseTimer.start(self.frameTime)
except:
print ('No cfg file selected!')
# Needed ?? deb_gp
# def setParser(self, uParser):
# self.parser = uParser
def parseData(self):
self.uart_thread.start(priority=QThread.HighestPriority)
def whoVisible(self):
if (self.threeD):
self.threeD = 0
else:
self.threeD = 1
print('3d: ', self.threeD)
if __name__ == '__main__':
if (compileGui):
appctxt = ApplicationContext()
app = QApplication(sys.argv)
screen = app.primaryScreen()
size = screen.size()
main = Window(size=size)
main.show()
exit_code = appctxt.app.exec_()
sys.exit(exit_code)
else:
app = QApplication(sys.argv)
screen = app.primaryScreen()
size = screen.size()
main = Window(size=size)
main.show()
sys.exit(app.exec_())

PyQT table update crash easyly

i first use PyQT4 .
i'm create a QTableWidget to show runing message...
when my program run, it ill crash Within ten minutes.
i try diable my TableUpdate function , and it's don't crash again.
there is my code please help me
class table_work(QThread):
TableDataSignal = pyqtSignal()
def __init__(self,main_self):
# QThread.__init__(self)
super(table_work, self).__init__(main_self)
self.main_self = main_self
self.table_update_list = list()
#pyqtSlot(dict)
def update_table_thread_o(self,work):
try:
row_pos = work['row_position']
data = work['data']
table_key_sort = work['key_sort']
this_table = work['table']
k = 0
for table_key in table_key_sort:
this_table.setItem(row_pos, k, QTableWidgetItem(unicode(data[table_key])))
k += 1
del work
except:
pass
def update_table_thread(self):
main_self = self.main_self
table_work_list = self.table_update_list
while 1:
for work in self.table_update_list:
row_pos = work['row_position']
data = work['data']
table_key_sort = work['key_sort']
this_table = work['table']
k = 0
for table_key in table_key_sort:
this_table.setItem(row_pos, k, QTableWidgetItem(unicode(data[table_key])))
k += 1
time.sleep(0.5)
def run(self):
self.update_table_thread()
this's update table message
def update_table(self,address,change_obj=None,tabe_name='auto_card'):
sample_dict = dict()
table_key_sort = list()
now_table_sort = 0
if tabe_name == "auto_bot":
this_table = self.auto_bot_procc_table
table_data_list = self.auto_bot_procc_table_list
now_table_sort = self.auto_bot_now_table_sort
sample_dict['address'] = address
sample_dict['money'] = 0
sample_dict['run_time'] = 0
sample_dict['item_cd'] = u"60分鐘後"
sample_dict['stat'] = "Ready..."
sample_dict['sort'] = now_table_sort
table_key_sort.append('address')
table_key_sort.append('money')
table_key_sort.append('run_time')
table_key_sort.append('item_cd')
table_key_sort.append('stat')
if tabe_name == "auto_card":
this_table = self.process_table
table_data_list = self.now_procc_table_list
now_table_sort = self.now_table_sort
sample_dict['address'] = address
sample_dict['done_num'] = 0
sample_dict['pre_item'] = ""
sample_dict['procc'] = "Ready"
sample_dict['mission_procc'] = u"待命.."
sample_dict['mission_num'] = 0
sample_dict['mission_line'] = 0
sample_dict['update_time'] = db.get_time()
sample_dict['sort'] = now_table_sort
sample_dict['option'] = ""
table_key_sort.append('address')
table_key_sort.append('done_num')
table_key_sort.append('pre_item')
table_key_sort.append('mission_procc')
table_key_sort.append('procc')
table_key_sort.append('mission_num')
table_key_sort.append('mission_line')
table_key_sort.append('update_time')
if address not in table_data_list:
this_table.insertRow(sample_dict['sort'])
table_data_list[address] = sample_dict
sample_dict['sort'] = self.auto_bot_now_table_sort
self.auto_bot_now_table_sort += 1
acc_data = table_data_list[address]
if change_obj != None:
key = change_obj['key']
val = change_obj['val']
if key in acc_data:
acc_data[key] = val
acc_data['update_time'] = db.get_time()
rowPosition = acc_data['sort']
temp = dict()
temp['row_position'] = rowPosition
temp['data'] = acc_data
temp['key_sort'] = table_key_sort
temp['table'] = this_table
self.TableDataSignal.emit(temp)
del temp
Some time i get a ANS.
i'm a PYQT newbie , After this period of various projects experience.
I understand if you don't use Main Thread to Change UI, Always use sign/emit
even your code is worked,but always use sign/emit, Otherwise there will be a series of disasters.
you just like
class sample(QtCore.QThread):
table_data_change = QtCore.pyqtSignal(dict)
def __init__(self,main_win):
self.main = main_win
self.table_data_change.connect(self.main.change_fn)
def test(self):
data = dict()
data['btn'] = .....
data['val'] = .....
self.table_data_change.emit(data)
Save your time !

Categories

Resources