Stuck on use of Event Handler

Hi,

This may not be a wxPython problem per se, but I'm sure you guys can help me. I overcame problems with sizers and scrollbars by consulting the list archives, but this one baffles me.

Also I want to thank Robin and Noel for their great book!

So what am I trying to achieve?

I have a gridbagsizer that gets filled with instances of BlockWindow objects. I have these instances report back the Window ID they received from wxWidgets and I store them as keys in a dictionary, together with a reference to what they refer to as far as I'm concerned.

Then I create an event handler that gets triggered when somebody presses the right mouse button on the BlockWindow. I can see the ID with print event.GetId() and if I were able to use the dictionary I had created I would have a way to relate them. But the dictionary is not available from within the BlockWindow object and the handler needs to be defined there, otherwise I don't see the ID with GetId().

How can this be solved?

The code:

#!/usr/bin/env python

"""
Module to help with Planning
"""

import sys, os
import wx
from blockwindow import BlockWindow
from timeofdayindicator import TimeOfDayIndicator
import time
from padb import * # module for accessing database
import Registration
from wx.lib.scrolledpanel import ScrolledPanel

weekdays=('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
roomsdict={'11111': {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5,},
           '22222': {'2.21': 1, '2.23': 2, '2.24': 3,},
           }

regsdict={}
IDtoSeNoDict={}

def GetRegistrationNosChronologically(CompID):
    dbconn = OurDB()
    dayduration=3600*24
    i=0
    while 1:
        if time.localtime(time.time()-dayduration*i)[6]==0:
            break
        i+=1

    monday = time.strftime('%Y-%m-%d',time.localtime(time.time()-dayduration*i))
    nextsunday = time.strftime('%Y-%m-%d',time.localtime(time.time()-dayduration*i+dayduration*7))

    sql = """SELECT date, time, ID
             FROM tpvregistrations
             WHERE date BETWEEN DATE('%s')
                              AND DATE('%s')
              AND loc_CompID = %d
              AND type = 'A'
             ORDER BY date, time, ID""" % (monday, nextsunday, CompID)
   
    if reginfolist == []:
        print "ID not found"
    else:
        newlist=[]
        for rgnodict in reginfolist:
            rgno=rgnodict['rgno']
            newlist.append(rgno)
            reg=Registration.Registration(RgNo=rgno)
            reg.fetchFromDB()
            regsdict[rgno] = reg
        return newlist

def MsgDlg(window, string, caption='wxProject', style=wx.YES_NO|wx.CANCEL):
    """Common MessageDialog."""
    dlg = wx.MessageDialog(window, string, caption, style)
    result = dlg.ShowModal()
    dlg.Destroy()
    return result

class main_window(wx.Frame):
    def __init__(self, parent, title):
        fullsize=wx.Size(1200,900)
        scrollpanelsize=wx.Size(9000,4000)
        wx.Frame.__init__(self, parent, title=title, size=fullsize,
                          style=wx.DEFAULT_FRAME_STYLE)
        self.scroll = ScrolledPanel(self, -1, size=scrollpanelsize, style = wx.HSCROLL | wx.VSCROLL) #
        self.scroll.SetScrollbars(1, 1, 2000, 1000)
               self.weekoverviewSizer = wx.GridBagSizer(hgap=4, vgap=1)

        rowsperhour=2
        timedaybegins=9
        timedayends=22
        rowsperday=(timedayends-timedaybegins)*rowsperhour
        minutesperrow=60/rowsperhour
        hoursperblock=1

        lastcol=0
        something=0
        colsdict={}
        for CompID in [11111,22222]:
            # Put legends in the header and left column
            OffsetCol = lastcol+something
            something=7
            for weekday in range(6):
                srow=weekday*rowsperday+1
                erow=rowsperday
                weekdayname=''
                i=1
                for letter in weekdays[weekday].upper():
                    weekdayname = weekdayname + letter + '\n'
                    bw=TimeOfDayIndicator(self.scroll, label=letter, size=(8,2), backgroundcolor='white')
                    self.weekoverviewSizer.Add(bw, pos=(srow+i,OffsetCol), span=(1,1), flag=wx.EXPAND)
                    i+=1
                               for block in range(timedayends-timedaybegins):
                    srow=block*hoursperblock*rowsperhour+weekday*rowsperday+1
                    erow=rowsperhour
                    bw=TimeOfDayIndicator(self.scroll, label='%d:00' % (block*hoursperblock+timedaybegins), size=(30,2))
                    self.weekoverviewSizer.Add(bw, pos=(srow,OffsetCol+1), span=(erow,1), flag=wx.EXPAND)

            registrationslist=GetRegistrationNosChronologically(CompID)
            roomscount=0
            for room in roomsdict[str(CompID)]:
                col=roomsdict[str(CompID)][str(room)]
                bw=BlockWindow(self.scroll, label=str(room))
                self.weekoverviewSizer.Add(bw, pos=(0,OffsetCol+col+1), flag=wx.EXPAND)
                roomscount+=1

            for rgno in registrationslist:
                rg=regsdict[rgno]
                srow=(reg.RgTime-540)/minutesperrow+(time.strptime(reg.RgDate,"%Y-%m-%d")[6])*rowsperday+1
                erow=reg.RgDur/minutesperrow
                firsttime=True
                if roomsdict[str(CompID).strip()].has_key(reg.RgRoom): # Is a room already assigned?
                    col=roomsdict[str(CompID)][reg.RgRoom]+OffsetCol # Put it in the corresponding column
                elif colsdict.has_key(reg.Rg_SeID): # Did we see this session before?
                    col=colsdict[reg.Rg_SeID] # Put it in the same column
                else: # Otherwise
                    if firsttime:
                        col=lastcol+roomscount
                    else:
                        col=lastcol
                    colsdict[reg.Rg_SeID]=col # Remember which column we assigned for a given session
                    lastcol=lastcol+1
                # print 'reg.RgRoom:', reg.RgRoom, reg.Rg_SeID, reg.RgTime, reg.RgDur, 'col, srow, erow: ', col, srow, erow
                bw=BlockWindow(self.scroll, label=str(reg.Rg_SeID), IDtoSeNoDict=IDtoSeNoDict)
                IDtoSeNoDict[bw.ID]=reg.Rg_SeID
                self.weekoverviewSizer.Add(bw, pos=(srow,OffsetCol+col+2), span=(erow,1), flag=wx.EXPAND)
               self.scroll.SetSizer(self.weekoverviewSizer)
        self.scroll.SetupScrolling(self, rate_x=20, rate_y=20)
               self.Centre()

        self.Show(True)

        self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightMouseButtonDownOnRegistration)

    def OnRightMouseButtonDownOnRegistration(self, event):
        print event.GetId(), self.IDtoSeNoDict[event.GetId()]

class App(wx.App):
    """wxProject Application."""
    def OnInit(self):
        """Create the wxProject Application."""
        frame = main_window(None, 'Planning Assistant')
        return True

if __name__ == '__main__':
    app = App(0)
    app.MainLoop()

import wx

class BlockWindow(wx.Panel):
    def __init__(self, parent, ID=-1, label="",
                 pos=wx.DefaultPosition, size=(60,2), IDtoSeNoDict=None):
        wx.Panel.__init__(self, parent, ID, pos, size, wx.RAISED_BORDER, label)
        self.label = label
        self.SetBackgroundColour("white")
        self.SetMinSize(size)
        self.SetSize(size)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

        self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightMouseButtonDownOnRegistration)
        self.ID=self.GetId()

    def OnPaint(self, evt):
        sz = self.GetClientSize()
        dc = wx.PaintDC(self)
        w, h = dc.GetTextExtent(self.label)
# print 'width %d, height %d' % (w, h)
        dc.SetFont(self.GetFont())

        dc.DrawText(self.label, (sz.width-w)/2, (sz.height-h)/2)

    def OnRightMouseButtonDownOnRegistration(self, event):
        print event.GetId(), IDtoSeNoDict[event.GetId()] # this dictionary does not exist in this namespace

I hope somebody can help me out.

Many thanks,

Jo

Jo wrote:

Hi,

This may not be a wxPython problem per se, but I'm sure you guys can help me. I overcame problems with sizers and scrollbars by consulting the list archives, but this one baffles me.

Also I want to thank Robin and Noel for their great book!

So what am I trying to achieve?

I have a gridbagsizer that gets filled with instances of BlockWindow objects. I have these instances report back the Window ID they received from wxWidgets and I store them as keys in a dictionary, together with a reference to what they refer to as far as I'm concerned.

Then I create an event handler that gets triggered when somebody presses the right mouse button on the BlockWindow. I can see the ID with print event.GetId() and if I were able to use the dictionary I had created I would have a way to relate them. But the dictionary is not available from within the BlockWindow object and the handler needs to be defined there, otherwise I don't see the ID with GetId().

How can this be solved?

After a good night's rest I realized that I can pass the primary keys of those rows in the database. They will be unique and they shouldn't clash, since the assigned IDs from wxPython are negative, whereas my IDs are positive numbers > 100000. I tried it and it seems to work. No need to try mapping these IDs and my primary keys.

Cheers,

Jo