I have been trying to figure out how to associate data with the event of checkbox being checked. The problem is that my data is stuck in a 5 keys deep dictionary (dict{dict{dict{dict{dict{}}}}}). I have tried crawling through the parents and getting their labels since they are created from the keys, but havent had much luck because of how I nested the notebooks. The code looks a follows:

#!/usr/bin/env python
import os
import sys
import datetime
import numpy as np
from readmonifile import MonitorFile
from sortmonifile import sort
import wx

class NestedPanelOne(wx.Panel):
    #----------------------------------------------------------------------
    # First notebook that creates the tab to select the component number
    #----------------------------------------------------------------------
    def __init__(self, parent, label, data):

        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)

        sizer = wx.BoxSizer(wx.VERTICAL)

        #Loop creating the tabs according to the component name
        nestedNotebook = wx.Notebook(self, wx.ID_ANY)
        for slabel in sorted(data[label].keys()):
            tab = NestedPanelTwo(nestedNotebook, label, slabel, data)
            nestedNotebook.AddPage(tab,slabel)


        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(nestedNotebook, 1, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(sizer)

class NestedPanelTwo(wx.Panel):
    #------------------------------------------------------------------------------
    # Second notebook that creates the tab to select the main monitoring variables 
    #------------------------------------------------------------------------------
    def __init__(self, parent, label, slabel, data):

        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)

        sizer = wx.BoxSizer(wx.VERTICAL)

        nestedNotebook = wx.Notebook(self, wx.ID_ANY)

        for sslabel in sorted(data[label][slabel].keys()):
            tab = NestedPanelThree(nestedNotebook, label, slabel, sslabel, data)
            nestedNotebook.AddPage(tab, sslabel)

        sizer.Add(nestedNotebook, 1, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(sizer)

    def GetPage(self):
        return nestedNotebook.GetPage()

class NestedPanelThree(wx.Panel):
    #-------------------------------------------------------------------------------
    # Third notebook that creates checkboxes to select the monitoring sub-variables
    #-------------------------------------------------------------------------------
    def __init__(self, parent, label, slabel, sslabel, data):


        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)

        self.labels=[]
        self.chbox=[]

        if label not in chboxdict.keys():
            chboxdict[label]={}
            chboxvaldict[label]={}
        if slabel not in chboxdict[label].keys():
            chboxdict[label][slabel]={}
            chboxvaldict[label][slabel]={}
        if sslabel not in chboxdict[label][slabel].keys():
            chboxdict[label][slabel][sslabel]={}
            chboxvaldict[label][slabel][sslabel]={}

        for ssslabel in sorted(data[label][slabel][sslabel].keys()):
            self.cb=wx.CheckBox(self, -1, ssslabel)
            chboxdict[label][slabel][sslabel][ssslabel]=self.cb
            chboxvaldict[label][slabel][sslabel][ssslabel]=self.cb.GetValue()
            wx.EVT_CHECKBOX(self, self.cb.GetId(), self.OnTimer)
            self.chbox.append(self.cb)
            self.labels.append(ssslabel)


        gridSizer = wx.GridSizer(np.shape(list(set(self.labels)))[0],3, 5, 5)

        gridSizer.AddMany(self.chbox)

        self.SetSizer(gridSizer)



    def OnTimer(self, event):

        #print "OnTimer Update..."                                                                                                  

        # before we get data, do we have to bother?                                                                                 
        isVisible = self.IsShown()
        child = self
        parent = self.GetParent()
        while(parent!=None and not parent.IsTopLevel()):

            if(parent.IsShown() and isinstance(parent, wx.BookCtrlBase)):
                if(parent.IsShown()):
                    selectionPage = parent.GetPage(parent.GetSelection())
                    pageselected = parent.GetParent().GetPage()
                    print selectionPage, pageselected, 'test2'
                if(selectionPage!=child):                                                                                            
                    isVisible=False
                    break
            else:
                if(not parent.IsShown()):
                    isVisible=False
                    break


            child = parent
            parent = parent.GetParent()

    def ShowParents(self, event):
        if self.cb.GetValue():
            print label, slabel, sslabel, self.cb.GetLabel()
        else:
            print 'Please select'

########################################################################
class NestedNotebook(wx.Notebook):
    #---------------------------------------------------------------------------------
    # Main notebook creating tabs for the monitored components
    #---------------------------------------------------------------------------------
    def __init__(self, parent, data):
        wx.Notebook.__init__(self, parent, id=wx.ID_ANY, style=
                             wx.BK_DEFAULT
                            )

        for label in sorted(data.keys()):
            tab = NestedPanelOne(self,label, data)
            self.AddPage(tab, label)

########################################################################
class mainFrame(wx.Frame):
    #----------------------------------------------------------------------
    # Putting it all together
    #----------------------------------------------------------------------
    def __init__(self,data):

        wx.Frame.__init__(self, None, wx.ID_ANY,
                          "pDAQ monitoring plotting tool",
                          size=(800,400)
                          )

        panel = wx.Panel(self)
        notebook = NestedNotebook(panel, data)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(notebook, 1, wx.ALL|wx.EXPAND, 5)
        panel.SetSizer(sizer)
        self.Layout()

        #Menu Bar to be added later
        '''
        menubar = wx.MenuBar()
        file = wx.Menu()
        file.Append(1, '&Quit', 'Exit Tool')
        menubar.Append(file, '&File')
        self.SetMenuBar(menubar)
        self.Bind(wx.EVT_MENU, self.OnClose, id=1)
        '''
        self.Show()
#----------------------------------------------------------------------
if __name__ == "__main__":

    if len(sys.argv) == 1:
        raise SystemExit("Please specify a file to process")

    for f in sys.argv[1:]:
        data=sort.sorting(f)


    print 'test'
    chboxdict={}
    chboxvaldict={}
    app = wx.PySimpleApp()
    frame = mainFrame(data)
    app.MainLoop()
    print 'testend'

The NestedPanelThree class is where I associate the checkboxes with the data and tried to crawl up through the panels.

Is there a way to associate the checkbox with data, such that if the checkbox is checked, the keys that were being used to create it are retrieved? Or is there a way to update the values of chboxvaldict[label][slabel][sslabel][ssslabel] without having to loop through all the keys?

Thanks a bunch in advance

Recommended Answers

All 3 Replies

There are not any answers presumably because no one uses 5 nested dictionaries. State what you are trying to do and why a 5-deep dictionary is necessary, along with a simple example, 184 lines of code is more than someone wants to wade through for a question like this, so something like

#10 or so dictionary entries is enough
sample_dictionary={"a":{"b":{"c":{"d":{"e":}}}}}
#
# create one panel and menu
class NestedPanelOne(wx.Panel):
    #----------------------------------------------------------------------
    # First notebook that creates the tab to select the component number
    #----------------------------------------------------------------------
    def __init__(self, parent, label, data):
        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
#
# and then the function called when the menu is clicked

Simply put, it is one way to organize the data in such a way that I can use the keys to dynamically create pages in my notebooks and because the data structure within the files i am trying to parse can have 5 different associations (main component, main component number, monitored component name, monitored variables, timestamp). With the dictionary i can easily get to the necessary information with a couple for loops and dont have to try to keep track of things in lists or some other data structure.

I am trying to basically create a plotting routine for files for the variables within them. So that if you check box A, B and C, it will plot A vs. Time, B vs. Time, C vs. Time, but given the large number of unique identifiers this becomes a little cumbersome

Is there a reason you are not storing the data in an in-memory SQLite database where you can easily select ("main component"=x and "main component number"=y and "timestamp"=z) or ("monitored component name"=a and "monitored variables"=b) etc.? An example usage from somewhere on the internet:

import sqlite3 as sqlite

##----------------------------------------------------------------------
def add_rec(cur, con, add_tuple):
   cur.execute("insert into test_it values (?, ?, ?, ?, ?, ?, ?, ?, ?)", add_tuple)
   con.commit()

##----------------------------------------------------------------------
def print_all_recs(cur):
   # Execute the SELECT statement:
   print "Printing all recs"
   cur.execute("select * from test_it")

   # Retrieve all rows as a sequence and print that sequence:
   recs_list = cur.fetchall()
   for rec in recs_list:
      print rec
      print "     stage=%s, REAC_W=%s" % (rec[1], rec[5])

##----------------------------------------------------------------------
def add_test_data(cur, con):
   #                   Stage     REAC_PS  WR(T)/P    TTO       REAC_W    W0       0wR(THCR)E/D  PTO
   data_list=[ ('2.0', 'Stage1', '0.509',  '4.3010', '1602.30', '0.515', '3.191',   '2.8191',   '29.7010'), \
               ('2.0', 'Stage2', '0.488',  '6.0074', '1470.43', '0.500', '3.200',   '3.9309',   '20.4275'), \
               ('2.0', 'Stage1', '0.524',  '4.4623', '1602.30', '0.560', '3.311',   '2.9243',   '29.7010'), \
               ('2.0', 'Stage2', '0.579',  '6.6682', '1444.78', '0.700', '3.320',   '4.3593',   '18.9262'), \
               ('3.0', 'Stage1', '0.524',  '4.4623', '1602.30', '0.560', '3.311',   '2.9243',   '29.7010'), \
               ('3.0', 'Stage2', '0.579',  '6.6682', '1444.78', '0.700', '3.320',   '4.3593',   '18.9262'), \
               ('3.5', 'Stage1', '0.525',  '4.4695', '1602.30', '0.563', '3.316',   '2.9290',   '29.7010') ]

   for data_tuple in data_list :
      add_rec(cur, con, data_tuple)

##----------------------------------------------------------------------
def del_recs_test(cur, con):
   num = "2.0"
   st = "Stage1"
   cur.execute("DELETE from test_it where number==:dic_num \
                          and stage==:dic_st", \
                         {"dic_num": num, "dic_st": st})
   con.commit()

   print "-" * 30, "AFTER Delete --- Should not find any recs"
   lookup_dic={"dic_num":"2.0", "dic_st":"Stage1"}
   recs_list=cur.execute('SELECT * FROM test_it where number=:dic_num \
                          and stage=:dic_st', \
	                  lookup_dic)

   print cur.fetchall()
   print

##----------------------------------------------------------------------
if __name__ == "__main__":
   # Create a connection to the (memory) database file
   con = sqlite.connect(':memory:')

   # Get a Cursor object that operates in the context of Connection con
   cur = con.cursor()

   cur.execute("CREATE TABLE test_it (number varchar, stage varchar, REAC_PS varchar, WR_T_P varchar, TTO varchar, REAC_W varchar, W0 varchar, wR_THCR_E_D varchar, PTO varchar)")

   add_test_data(cur, con)
   print_all_recs(cur)

   ##----------------------------------------------------------------------
   print '\n-----SELECT * FROM test_it where number="2.0"-------'
   recs_list=cur.execute('SELECT * FROM test_it where number="2.0"')
   ctr=0
   for row in recs_list:
      print row
      ctr += 1
   print ctr, "recs found"

   print '\n-----SELECT * FROM test_it where number="2.0" and stage="Stage1"'
   lookup_dic={"dic_num":"2.0", "dic_st":"Stage1"}
   recs_list=cur.execute('SELECT * FROM test_it where number=:dic_num \
                          and stage=:dic_st', \
	                  lookup_dic)
   ctr=0
   for row in recs_list:
      print row
      ctr += 1
   print ctr, "recs found"

   print "\n------DELETE test"
   del_recs_test( cur, con)

   print '\n----- PRAGMA for tablename  -----------------------'
   cur.execute("PRAGMA table_info(test_it)")
   print cur.fetchall()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.