I have a notebook that I load data from a text file into.
The text file is read at the start of the program.
I set up preferences to change the loaded file.
However, when I load the new file the values do not change on the
notebook.
I thought I could load the main_window instance into my preferences
class and then call the necessary subroutines and then display the new
instance.
I have placed some print statements in various places to check that
the data is being loaded. My print statements confirm the new file is
loaded but I don't see the new values.
Somehow I am doing something wrong or thinking about the problem
incorrectly.
Below is a shortened working version of what I am trying to do.
Could someone help or show me how my logic is incorrect?
textfile.txt
Tue 01/03/2012 08:46:00.00 01 start work day
Tue 01/03/2012 09:00:00.00 05 start meeting
Tue 01/03/2012 12:30:00.00 06 end meeting
Tue 01/03/2012 12:30:00.00 03 start lunch
Tue 01/03/2012 13:30:00.00 04 end lunch
Tue 01/03/2012 15:42:00.00 13 start activity1
Tue 01/03/2012 17:29:09.97 11 start activity2
Tue 01/03/2012 17:46:01.55 12 end activity2
Tue 01/03/2012 18:15:00.00 02 end work day
Wed 01/04/2012 08:24:12.17 01 start work day
Wed 01/04/2012 11:33:45.75 13 start activity1
Wed 01/04/2012 12:35:00.00 03 start lunch
Wed 01/04/2012 13:42:00.00 04 end lunch
Wed 01/04/2012 14:29:09.97 11 start activity2
Wed 01/04/2012 14:46:01.55 12 end activity2
Wed 01/04/2012 16:42:00.00 13 start activity1
Wed 01/04/2012 18:19:51.49 02 end work day
<code>
import wx
import datetime #for logging the date and time
import calendar #for checking leap year
import os #for checking path and file location
···
################################################################################
### Page One - Location of buttons and current times
################################################################################
class PageOne(wx.Panel):
def __init__(self, parent,data,myfile):
wx.Panel.__init__(self, parent)
self.data = data
self.myfile = myfile
print data[1][1], "page1"
sizer = wx.GridBagSizer(5,10)
self.start_time = wx.StaticText(self,-1,label = "")
self.elapsed_time = wx.StaticText(self,-1,label = "")
sizer.Add( item = self.start_time, pos = ( 1, 1), flag =
wx.ALIGN_CENTER )
sizer.Add( item = self.elapsed_time, pos = ( 1, 2), flag =
wx.ALIGN_CENTER )
self.previous_entries()
self.SetSizerAndFit(sizer)
def previous_entries(self):
self.previous = self.data[0][0]
self.previous2 = self.myfile
self.start_time.SetLabel(str(self.previous))
self.elapsed_time.SetLabel(str(self.previous2))
################################################################################
### Edit the log file window
################################################################################
class EditLog(wx.Frame):
title = "Edit the log file"
def __init__(self,myfile):
wx.Frame.__init__(self, wx.GetApp().TopWindow,
title=self.title, size=(600,700))
sizer = wx.BoxSizer()
self.statusbar = self.CreateStatusBar()
panel = wx.Panel(self, wx.ID_ANY)
self.myfile = myfile
self.texteditor = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE)
file = open(self.myfile, 'r')
self.texteditor.WriteText(file.read())
file.close()
self.texteditor.SetInsertionPointEnd()
self.texteditor.SetFocus()
sizer.Add( item=self.texteditor, proportion=1, flag=wx.EXPAND)
self.SetSizer(sizer)
menubar = wx.MenuBar()
file = wx.Menu()
save = wx.MenuItem(file, wx.ID_SAVE, '&Save\tCtrl+S', 'Save
the document')
file.AppendItem(save)
file.AppendSeparator()
quit = wx.MenuItem(file, wx.ID_EXIT, '&Quit\tCtrl+Q', 'Quit
the Editor')
file.AppendItem(quit)
self.Bind(wx.EVT_MENU, self.OnClose, quit)
self.Bind(wx.EVT_MENU, self.OnSave, save)
self.Bind(wx.EVT_CLOSE,self.OnClose)
help = wx.Menu()
about_prog = wx.MenuItem(help, wx.ID_ABOUT, '&About', 'About
this program')
help.AppendItem(about_prog)
self.Bind(wx.EVT_MENU, self.OnAbout, about_prog)
menubar.Append(file, '&File')
menubar.Append(help, '&Help')
self.SetMenuBar(menubar)
def OnClose(self, event):
# self.reload = main_window(None, -1, 'WorkStats.py')
# self.reload.test_for_log_file()
# self.reload.open_file()
self.Destroy()
def OnAbout(self, event):
self.Destroy()
def OnSave(self, event):
try:
file = open(self.myfile, 'w')
text = self.texteditor.GetValue()
file.write(text)
file.close()
self.statusbar.SetStatusText(os.path.basename(self.myfile)
+ ' saved', 0)
except IOError, error:
dlg = wx.MessageDialog(self, 'Error saving file\n' +
str(error))
dlg.ShowModal()
################################################################################
### Preferences window
################################################################################
class PreferenceDialog(wx.Frame):
title = "Preferences"
def __init__(self,myfile,config,arrays):
wx.Frame.__init__(self, wx.GetApp().TopWindow,
title=self.title, size=wx.Size(500,500))
self.arrays = arrays
self.array_size = 15
self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
self.panel = wx.Panel(self, wx.ID_ANY)
self.myfile = myfile
self.myfile_old = myfile
self.config = config
self.button_title = [0]*self.array_size
self.date_pref = 1
if self.config.Exists('date_format'):
self.date_pref = self.config.Read('date_format')
self.Centre()
self.statusbar = self.CreateStatusBar()
self.radio_date1 = wx.RadioButton(self.panel, -1, "DD-MMM-
YYYY")
self.radio_date2 = wx.RadioButton(self.panel, -1, "MMM-DD-
YYYY")
self.file_display = wx.TextCtrl(self.panel, -1, "",
style=wx.TE_LEFT)
self.button_open = wx.Button(self.panel, -1, "...")
self.Bind( wx.EVT_BUTTON, self.OnChoose, self.button_open)
sizer1 = wx.GridBagSizer()
sizer1.Add( item = wx.StaticText(self.panel,-1,label='Choose a
date format for display'), pos=(0,0))
sizer1.Add( item = self.radio_date1, pos = (1,0) )
sizer1.Add( item = self.radio_date2, pos = (1,1) )
sizer1.Add( item = wx.StaticText(self.panel,-1,label='Choose a
location to save logged date and time'), pos = ( 2, 0))
sizer1.Add( item = self.file_display, pos = (3,0),
flag=wx.EXPAND)
sizer1.Add( item = self.button_open, pos = (3,1))
sizer1.Add( item = wx.StaticText(self.panel,-1,label='Set the
button descriptions'), pos=(4,0))
counter = 5
for i in self.arrays[1]:
self.button_title[i] = wx.TextCtrl(self.panel, -1, "",
style=wx.TE_LEFT)
sizer1.Add( item =
wx.StaticText(self.panel,-1,label="Button "+str(counter-4)),
pos=(counter,1))
sizer1.Add( item = self.button_title[i], pos = (counter,
0), flag=wx.EXPAND)
if self.config.Exists('button'+str(i)):
title = self.config.Read('button'+str(i))
self.button_title[i].Clear()
self.button_title[i].AppendText(title)
counter += 1
self.SetSizerAndFit(sizer1)
if self.date_pref == "MMM-DD-YYYY":
self.radio_date2.SetValue(True)
if self.config.Exists('logfile'):
self.myfile = self.config.Read('logfile')
self.file_display.Clear()
self.file_display.AppendText(self.myfile)
menubar = wx.MenuBar()
file = wx.Menu()
quit = wx.MenuItem(file, wx.ID_EXIT, '&Quit\tCtrl+Q', 'Exit
Preferences')
file.AppendItem(quit)
self.Bind(wx.EVT_MENU, self.OnClose, quit)
menubar.Append(file, '&File')
self.SetMenuBar(menubar)
self.Bind(wx.EVT_CLOSE,self.OnClose)
def OnClose(self, event):
self.reload = main_window(None, -1, 'WorkStats.py')
self.reload.test_for_log_file()
data = self.reload.open_file(self.myfile)
descriptions = self.reload.FindDescriptions()
self.reload.DestroyNotebookPages()
self.reload.SetupNotebook(data,descriptions,self.myfile)
self.reload.Destroy()
if self.radio_date1.GetValue():
self.config.Write('date_format',"DD-MMM-YYYY")
if self.radio_date2.GetValue():
self.config.Write('date_format',"MMM-DD-YYYY")
for i in self.arrays[1]:
self.config.Write('button'+str(i),self.button_title[i].GetValue())
self.Destroy()
def OnChoose(self, event):
wcd = 'Text files (*.txt)|*.txt|All files (*.*)|*'
dir = os.getcwd()
open_dlg = wx.FileDialog(self, message='Choose a file',
defaultDir=dir, defaultFile='worklog.txt',
wildcard=wcd, style=wx.OPEN|wx.CHANGE_DIR)
if open_dlg.ShowModal() == wx.ID_OK:
path = open_dlg.GetPath()
self.myfile = path
else:
if self.config.Exists('logfile'):
self.myfile = self.config.Read('logfile')
else:
self.myfile = "worklog.txt"
self.config.Write('logfile', self.myfile)
self.file_display.Clear()
self.file_display.AppendText(self.myfile)
open_dlg.Destroy()
def OnKeyDown(self, event):
keycode = event.GetKeyCode()
if keycode == wx.WXK_ESCAPE:
self.OnClose()
################################################################################
### Main Window
################################################################################
class main_window(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition,
size=(800,590)) #size=(w,l)
self.parent = parent
self.Centre()
appPath =
os.path.abspath(os.path.dirname(os.path.join(__file__)))
inifile = os.path.join(appPath, "workstats.ini")
self.config =
wx.FileConfig(appName='WorkStats',vendorName='Work
Statistics',localFilename=inifile,style=wx.CONFIG_USE_LOCAL_FILE)
self.arrays = (
[1,3,5,11], # 0 - start activities that have
end times
[1,3,5,11,13], # 1 - all start activities
[2,4,6,12], # 2 - all end activities
[1,2,3,4,5,6,11,12], # 3 - all activities with starts
and ends
[1,2,3,4,5,6,11,12,13], # 4 - all activities
)
if self.config.Exists('logfile'):
self.myfile = self.config.Read('logfile')
else:
self.config.Write('logfile','worklog.txt')
self.myfile = self.config.Read('logfile')
descriptions = self.FindDescriptions()
self.test_for_log_file()
self.data =
self.open_file(self.myfile) #call to
test opening file and saving data
self.SetupNotebook(self.data,descriptions,self.myfile)
menubar = wx.MenuBar()
file = wx.Menu()
file.AppendSeparator()
quit = wx.MenuItem(file, wx.ID_EXIT, '&Quit\tCtrl+Q', 'Quit
the Application')
file.AppendItem(quit)
self.Bind(wx.EVT_MENU, self.OnClose, quit)
self.Bind(wx.EVT_CLOSE,self.OnClose)
edit = wx.Menu()
edit_log = wx.MenuItem(edit,wx.ID_EDIT, '&Edit Log\tCtrl+E',
'Edit the log file')
edit.AppendItem(edit_log)
self.Bind(wx.EVT_MENU, self.OnEditLogFile, edit_log)
preferences = wx.MenuItem(edit,wx.ID_PREFERENCES, 'P&references
\tCtrl+R', 'Set user preferences')
edit.AppendItem(preferences)
self.Bind(wx.EVT_MENU, self.OnPreferences, preferences)
menubar.Append(file, '&File')
menubar.Append(edit, '&Edit')
self.SetMenuBar(menubar)
self.statusbar = self.CreateStatusBar()
def DestroyNotebookPages(self):
self.page1.Destroy()
def SetupNotebook(self,data,descriptions,myfile):
panel = wx.Panel(self, wx.ID_ANY)
nb = wx.Notebook(panel)
# create the page windows as children of the notebook
print data[1][1], "setup"
self.page1 = PageOne(nb,data,myfile)
# add the pages to the notebook with the label to show on the
tab
nb.AddPage(self.page1, "Main")
# finally, put the notebook in a sizer for the panel to manage
# the layout
sizer = wx.BoxSizer()
sizer.Add(nb, 1, wx.EXPAND)
panel.SetSizer(sizer)
def FindDescriptions(self):
# read the configuration file for set activity descriptions. If not
set yet then set the values to default
descriptions = ['place holder']*15
for i in self.arrays[1]:
if self.config.Exists('button'+str(i)):
descriptions[i] = "Start
"+self.config.Read('button'+str(i))
if i != 13:
descriptions[i+1] = "End "
+self.config.Read('button'+str(i))
else:
descriptions[i+1] = "Start
"+self.config.Read('button'+str(i))
else:
if i == 1:
self.config.Write('button'+str(i),"Work Day")
descriptions[i] = "Start Work Day"
descriptions[i+1] = "End Work Day"
if i == 3:
self.config.Write('button'+str(i),"Lunch")
descriptions[i] = "Start Lunch"
descriptions[i+1] = "End Lunch"
if i == 5:
self.config.Write('button'+str(i),"Meeting")
descriptions[i] = "Start Meeting"
descriptions[i+1] = "End Meeting"
if i == 11:
self.config.Write('button'+str(i),"Activity2")
descriptions[i] = "Start Activity2"
descriptions[i+1] = "End Activity2"
if i == 13:
self.config.Write('button'+str(i),"Activity1")
descriptions[i] = "Start Activity1"
descriptions[i+1] = "Start Activity1"
return descriptions
def OnPreferences(self,event):
PreferenceDialog(self.myfile,self.config,self.arrays).Show()
def OnEditLogFile(self, event):
EditLog(self.myfile).Show()
def OnClose(self, event):
self.Destroy()
def test_for_log_file(self):
try:
open(self.myfile)
except IOError as e:
print "Can not open file: "+self.myfile
self.myfile = "worklog.txt"
try:
open(self.myfile)
except IOError as e:
fd = os.open(self.myfile, os.O_WRONLY | os.O_CREAT |
os.O_EXCL) # this creates a new file
f = os.fdopen(fd,'w') # I think converts to
something
f.close() # close file
self.config.Write('logfile', self.myfile)
print "Instead using "+self.myfile
def open_file(self,myfile):
"""Test that we can open the log file and once open store the
data."""
self.myfile = myfile
data=[]
self.file_size = os.path.getsize(self.myfile)
if self.file_size == 0:
time_tup = datetime.datetime(1900,1,1,0,0,0)
millis = 0
data.append([1,time_tup,millis])
else:
try:
## Either of these two lines could throw an IOError,
say
## if the file does not exist or the read() encounters
a low level error.
f = open(self.myfile, 'r')
for line in f:
#delimit and split
line = line.replace(':',' ').replace('/','
').replace('.',' ').split()
month = int(line[1])
day = int(line[2])
year = int(line[3])
hour = int(line[4])
minute = int(line[5])
second = int(line[6])
millis = int(line[7])
time_tup =
datetime.datetime(year,month,day,hour,minute,second)
#store in array as activity, time tuple,
milliseconds
data.append([int(line[8]),time_tup,millis])
f.close()
except ValueError:
print "This file does not seem to be a correct log
file."
self.OnPreferences(True)
except IOError:
## Control jumps directly to here if any of the above
lines throws IOError.
self.statusbar.SetStatusText("Can not read from
"+os.path.basename(self.myfile), 0)
sys.stderr.write('problem reading:' + filename)
self.OnPreferences(True)
sys.exit(2)
## In any case, the code then continues with the line
after the try/except
return data
class MyApp(wx.App):
def OnInit(self):
frame = main_window(None, -1, 'WorkStats.py')
frame.Show(True)
self.SetTopWindow(frame)
return True
if __name__ == '__main__':
app = MyApp(0)
app.MainLoop()
</code>