Unexpected changes to wxDateTime objects

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Unexpected changes to wxDateTime objects

Lori
This post has NOT been accepted by the mailing list yet.
While running this script, strange values appear in the various start_datetime variables.  This happens when executing statements that do not include the variable, such as "print('check').  I would appreciate any insight you can offer.

"""
Observe the variables start_datetime, self.start_date.Value, and cfg_dict[0]['start_datetime'].
These should all synchronize as you progress through the program.
However, if you change the seconds, upon executing the "print('check')" statement
at the end of the onChangeDateTime function, strange dates and times will be introduced.
"""

import wx
import wx.lib.masked as masked
import datetime                         # date and time handling functions

global start_datetime, cfg_dict                 # these variables need to stay synchronized across all related scripts
start_datetime = wx.DateTime_Now()
cfg_dict = [{'start_datetime': start_datetime}]

class my_example(wx.Panel):                  # -----------------------  class that handles date/time input

    def __init__(self, parent):
        wx.Panel.__init__(self, parent, wx.ID_ANY, size=(640,480), name='my_example')

        self.txt_date = wx.StaticText(self, wx.ID_ANY, "Date: ")                # ---------------- start date field
        self.start_date = wx.DatePickerCtrl(self, wx.ID_ANY, dt=start_datetime,
                                            style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY |
                                                     wx.TE_PROCESS_ENTER,
                                            name='start_date')
       

        self.txt_time = wx.StaticText(self, wx.ID_ANY, 'Time (24-hr): ')      # ---------------- start time field
        self.btnSpin = wx.SpinButton(self, wx.ID_ANY, wx.DefaultPosition, (-1, 20), wx.SP_VERTICAL)
        starttime = self.wxdatetime2timestring(start_datetime)
        self.start_time = masked.TimeCtrl(self, wx.ID_ANY, value=starttime,
                                          name='time: \n24 hour control', fmt24hr=True,
                                          spinButton=self.btnSpin, style=wx.TE_PROCESS_ENTER)


        self.start_date.Bind(wx.EVT_KEY_UP, self.whichKey)                 # -------------- bind event handlers
        self.Bind(wx.EVT_NAVIGATION_KEY, self.whichField)

        self.dt_Sizer = wx.FlexGridSizer(3, 2, 2, 2)                         # -------------------------- set up sizers
        self.dt_Sizer.Add(self.txt_date,                                0, wx.ALL, 5)
        self.dt_Sizer.Add(self.start_date,                              0, wx.ALL, 5)

        self.dt_Sizer.Add(self.txt_time,                                0, wx.ALL, 5)
        self.addWidgets(self.dt_Sizer, [self.start_time, self.btnSpin])

        self.SetSizer(self.dt_Sizer)
        self.Layout()


#################################################################
    def onChangeDateTime(self, event, whichCtrl, lastKey):

        # ------------------------------------------------------------------------ get the date from datepickerctrl
        try:                                                         # this fails if month was not changed:  
                                                                      # bug in wxDateTimePickerCtrl: m_date not in sync
            stdate = self.start_date.GetValue()
        except:
            stdate = start_datetime       # if there's a problem getting the date, use the current global value

        # ------------------------------------------------------------------------------- get the time from timectrl
        sttime = self.start_time.GetValue(as_wxTimeSpan=True)

        start_datetime = stdate.AddTS(sttime)               # ------------------------- add the time to the date

        cfg_dict[0]['start_datetime'] = start_datetime      # ------------- save the new datetime in dictionary


        print('check')                                      # --------- place to set breakpoint & examine results


 ############################# Navigation Functions #####################
    def whichKey(self, event):
            code = event.GetKeyCode()
            event.Skip()
            if code == 370 or code == 13:
                lastkey = 'Return'
                self.whichField(event, lastkey)
                return
            if code == 47:
                lastkey = '/'
                self.whichField(event, lastkey)
                return

    def whichField(self, event, lastKey='Nav'):     # ------ distributes control to correct function
                                                                      #           after navigation key is pressed
        whichObject = event.EventObject
        whichObjectstr = str(whichObject)
        whichObjectstr = whichObjectstr[1:9]

        if lastKey == 'Nav':                        # -----------   command event was triggered
            if whichObjectstr == 'maskPane':
                self.onChangeDateTime(event, 'start_date', 'Tab')

            elif whichObjectstr == 'TimeCtrl':
                if event.IsFromTab():
                    self.onChangeDateTime(event, 'start_time', 'Tab')
                else:
                    self.onChangeDateTime(event, 'start_time', 'Return')


        elif lastKey == 'Return':
            if whichObjectstr == 'wx._cont':
                self.onChangeDateTime(event, 'start_date', 'Return')

        elif lastKey == '/':
            self.onChangeDateTime(event, 'start_date', lastKey)

        else:
            self.onChangeDateTime(event, whichObjectstr, lastKey)

        print('check')

    ##########################  TimeCtrl added functions ##################

    def addWidgets(self, mainSizer ,widgets):       # --------------------------------  used for time widgets

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        for widget in widgets:
            if isinstance(widget, wx.StaticText):
                sizer.Add(widget,                           0, wx.ALL | wx.CENTER, 1),
            else:
                sizer.Add(widget,                           0, wx.ALL, 1)
        mainSizer.Add(sizer)

    def wxdatetime2timestring(self, datetime):
        strdt = datetime.FormatISOTime()
        return strdt

######################## Main Program #########################
class mainFrame(wx.Frame):

    def __init__(self, *args, **kwds):

        wx.Frame.__init__(self, *args, **kwds)
        whatever = my_example(self)                      # calls the class
        print('done.')

if __name__ == "__main__":
    app = wx.App()
    wx.InitAllImageHandlers()
    frame_1 = mainFrame(None, 0, "")           # Create the main window.
    app.SetTopWindow(frame_1)                   # Makes this window the main window
    frame_1.Show()                              # Shows the main window
    app.MainLoop()                              # Begin user interactions.