My code is below. The main focus would be on the OnStart method. I want
to make sure that a positive integer is entered in the input box. At
first I tried an if/else clause, then switched to try/except. Neither is
perfect yet, but I was wondering which I should try for in the first
place. I figure I need to check for an emptry string, non-numeric
strings (maybe these are the same check), 0 and negative numbers (which
might also fall into the category of 'anything but a number' because of
the negative sign).
Thanks.
-------------------------------
import wx
class MyTimer(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, 'Timer',
style=wx.DEFAULT_FRAME_STYLE ^
wx.RESIZE_BORDER ^ wx.MAXIMIZE_BOX)
panel = wx.Panel(self)
mainSizer = wx.BoxSizer(wx.VERTICAL)
inputSizer = wx.BoxSizer(wx.HORIZONTAL)
self.progress = wx.Gauge(panel, wx.ID_ANY, 100, size=(300, 20))
self.status = wx.StaticText(panel, wx.ID_ANY, 'Enter a time.')
prompt = wx.StaticText(panel, wx.ID_ANY, 'Time to wait:')
self.input = wx.TextCtrl(panel, wx.ID_ANY, size=(20, 20))
self.start = wx.Button(panel, wx.ID_ANY, 'Start')
self.reset = wx.Button(panel, wx.ID_ANY, 'Reset')
self.reset.Disable()
self.timer = wx.Timer(self)
mainSizer.Add(self.progress, flag=wx.ALIGN_CENTER | wx.ALL ^
wx.BOTTOM,
border=10)
mainSizer.Add(self.status, flag=wx.ALIGN_CENTER | wx.ALL,
border=10)
mainSizer.Add(inputSizer, flag=wx.ALIGN_CENTER | wx.BOTTOM,
border=10)
inputSizer.Add(prompt, flag=wx.ALIGN_CENTER)
inputSizer.Add(self.input, flag=wx.ALIGN_CENTER | wx.LEFT |
wx.RIGHT,
border=5)
inputSizer.Add(self.start, flag=wx.ALIGN_CENTER)
inputSizer.Add(self.reset, flag=wx.ALIGN_CENTER)
self.Bind(wx.EVT_TEXT_ENTER, self.OnStart, self.input)
self.Bind(wx.EVT_BUTTON, self.OnStart, self.start)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
self.Bind(wx.EVT_BUTTON, self.OnReset, self.reset)
panel.SetSizer(mainSizer)
mainSizer.Fit(self)
def OnStart(self, event):
try:
self.time = int(self.input.GetValue())
self.minutes_passed = 1
self.minutes_remaining = self.time - 1
self.start.Disable()
self.input.Disable()
self.reset.Enable()
self.status.SetLabel('%s minute(s) remaining.' % self.time)
self.timer.Start(1000)
except ValueError:
wx.MessageBox('Enter a valid time.', 'Invalid time entered',
wx.OK | wx.ICON_ERROR)
self.input.Clear()
def OnReset(self, event):
if self.timer.IsRunning():
self.timer.Stop()
self.input.Clear()
self.input.Enable()
self.start.Enable()
self.reset.Disable()
self.status.SetLabel('Enter a new time.')
self.progress.SetValue(0)
self.minutes_passed = 1
def OnTimer(self, event):
if self.minutes_remaining != 0:
self.progress.SetValue(self.minutes_passed * (100.0 /
self.time))
self.status.SetLabel('%s minute(s) remaining.' %
self.minutes_remaining)
self.minutes_passed += 1
self.minutes_remaining -= 1
else:
self.timer.Stop()
self.progress.SetValue(self.minutes_passed * (100.0 /
self.time))
self.status.SetLabel('%s minute(s) have elapsed.' % self.time)
wx.Sound.Play(wx.Sound(r'C:\Windows\Media\notify.w av'))
class MyApp(wx.App):
def OnInit(self):
frame = MyTimer()
self.SetTopWindow(frame)
frame.Show()
return True
if __name__ == '__main__':
app = MyApp(False)
app.MainLoop() 4 3655
John,
The way I do it is, is I ask myself 'is there a more common (basic)
base between the code paths or do they both have about a 50/50 chance
on average?' or 'will one code path be taken during an error and the
other one during the normal processing?'. If there is a clear single
common/usual/basic case or I try to detect an error I use 'try/except',
if it could go either way on average I use 'if'.
In general in Python we follow the 'it is better to ask forgiveness
than to ask permission'. In other words if you don't know if a piece
of data you have is a function and is callable you just call it and if
it raises an exception then you'll know it's not. This is the opposite
of C where you have to spend a good deal of time validating your input
arguments before you can safely continue.
That said, Python is also a practical language and quite often if you
do just one check then an 'if' may take 2 lines (if no need for else)
while a try/except will take 4 lines. So just apply common sense. For
example, I want to find out if I can call f then do some stuff if that
is the case:
try:
f(arg)
#...do stuff because f is callable...
except TypeError:
pass
# ... if f is not callable, then I don't care...
But of course it is much shorter to do:
if callable(f):
#...do stuff because f is callable...
Hope this helps,
Nick Vatamaniuc
John Salerno wrote:
My code is below. The main focus would be on the OnStart method. I want
to make sure that a positive integer is entered in the input box. At
first I tried an if/else clause, then switched to try/except. Neither is
perfect yet, but I was wondering which I should try for in the first
place. I figure I need to check for an emptry string, non-numeric
strings (maybe these are the same check), 0 and negative numbers (which
might also fall into the category of 'anything but a number' because of
the negative sign).
Thanks.
-------------------------------
import wx
class MyTimer(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, 'Timer',
style=wx.DEFAULT_FRAME_STYLE ^
wx.RESIZE_BORDER ^ wx.MAXIMIZE_BOX)
panel = wx.Panel(self)
mainSizer = wx.BoxSizer(wx.VERTICAL)
inputSizer = wx.BoxSizer(wx.HORIZONTAL)
self.progress = wx.Gauge(panel, wx.ID_ANY, 100, size=(300, 20))
self.status = wx.StaticText(panel, wx.ID_ANY, 'Enter a time.')
prompt = wx.StaticText(panel, wx.ID_ANY, 'Time to wait:')
self.input = wx.TextCtrl(panel, wx.ID_ANY, size=(20, 20))
self.start = wx.Button(panel, wx.ID_ANY, 'Start')
self.reset = wx.Button(panel, wx.ID_ANY, 'Reset')
self.reset.Disable()
self.timer = wx.Timer(self)
mainSizer.Add(self.progress, flag=wx.ALIGN_CENTER | wx.ALL ^
wx.BOTTOM,
border=10)
mainSizer.Add(self.status, flag=wx.ALIGN_CENTER | wx.ALL,
border=10)
mainSizer.Add(inputSizer, flag=wx.ALIGN_CENTER | wx.BOTTOM,
border=10)
inputSizer.Add(prompt, flag=wx.ALIGN_CENTER)
inputSizer.Add(self.input, flag=wx.ALIGN_CENTER | wx.LEFT |
wx.RIGHT,
border=5)
inputSizer.Add(self.start, flag=wx.ALIGN_CENTER)
inputSizer.Add(self.reset, flag=wx.ALIGN_CENTER)
self.Bind(wx.EVT_TEXT_ENTER, self.OnStart, self.input)
self.Bind(wx.EVT_BUTTON, self.OnStart, self.start)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
self.Bind(wx.EVT_BUTTON, self.OnReset, self.reset)
panel.SetSizer(mainSizer)
mainSizer.Fit(self)
def OnStart(self, event):
try:
self.time = int(self.input.GetValue())
self.minutes_passed = 1
self.minutes_remaining = self.time - 1
self.start.Disable()
self.input.Disable()
self.reset.Enable()
self.status.SetLabel('%s minute(s) remaining.' % self.time)
self.timer.Start(1000)
except ValueError:
wx.MessageBox('Enter a valid time.', 'Invalid time entered',
wx.OK | wx.ICON_ERROR)
self.input.Clear()
def OnReset(self, event):
if self.timer.IsRunning():
self.timer.Stop()
self.input.Clear()
self.input.Enable()
self.start.Enable()
self.reset.Disable()
self.status.SetLabel('Enter a new time.')
self.progress.SetValue(0)
self.minutes_passed = 1
def OnTimer(self, event):
if self.minutes_remaining != 0:
self.progress.SetValue(self.minutes_passed * (100.0 /
self.time))
self.status.SetLabel('%s minute(s) remaining.' %
self.minutes_remaining)
self.minutes_passed += 1
self.minutes_remaining -= 1
else:
self.timer.Stop()
self.progress.SetValue(self.minutes_passed * (100.0 /
self.time))
self.status.SetLabel('%s minute(s) have elapsed.' % self.time)
wx.Sound.Play(wx.Sound(r'C:\Windows\Media\notify.w av'))
class MyApp(wx.App):
def OnInit(self):
frame = MyTimer()
self.SetTopWindow(frame)
frame.Show()
return True
if __name__ == '__main__':
app = MyApp(False)
app.MainLoop()
On Thu, 2006-07-27 at 20:44 +0000, John Salerno wrote:
My code is below. The main focus would be on the OnStart method. I want
to make sure that a positive integer is entered in the input box. At
first I tried an if/else clause, then switched to try/except. Neither is
perfect yet, but I was wondering which I should try for in the first
place. I figure I need to check for an emptry string, non-numeric
strings (maybe these are the same check), 0 and negative numbers (which
might also fall into the category of 'anything but a number' because of
the negative sign).
Have a look at using a wx.Validator in your wx.TextCtrl.
Syntax for wx.TextCtrl:
wx.TextCtrl(parent, id, value="", pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0, validator=wx.DefaultValidator,
name=wx.TextCtrlNameStr)
This will enable you to automagically check the TextCtrl if it's empty,
has wrong data type, does not meet a prescribed condition (eg: no
negative numbers) and do something if it does not pass validation (eg:
colour the background of the TextCtrl red, initiate a system beep, etc).
Regards,
John
--
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.
John McMonagle wrote:
Have a look at using a wx.Validator in your wx.TextCtrl.
Ah, good thinking! I wasn't even considering another option like that,
which probably makes more sense anyway!
Nick Vatamaniuc wrote:
John,
The way I do it is, is I ask myself 'is there a more common (basic)
base between the code paths or do they both have about a 50/50 chance
on average?' or 'will one code path be taken during an error and the
other one during the normal processing?'. If there is a clear single
common/usual/basic case or I try to detect an error I use 'try/except',
if it could go either way on average I use 'if'.
Thanks, that's something good to think about. This issue came up once
before and I remember someone saying something like "you're using a
try/except statement, but i wouldn't really consider that situation
'exceptional'", so thinking of it in your terms might help a lot. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Nicolas Fleury |
last post by:
Hi everyone,
I'm wondering what is the easiest/cleanest way to look for existence of
available methods/members.
For example, in parsing a xml file, created objects can define a
setXmlFilename...
|
by: Mike Button |
last post by:
Hello all,
I am really really desperate on what I should do, and I am asking for help
from anyone in this newsgroup, here's the situation:
I am creating a form that is being run on a server...
|
by: h7qvnk7q001 |
last post by:
I'm trying to implement a simple server-side form validation (No
Javascript). If the user submits a form with errors, I want to
redisplay the same form with the errors highlighted. Once the form...
|
by: Tom |
last post by:
I'm trying to adapt a function I'd written to insert arrays in MySQL to
the ADOdb_lite class. The best way to do this would probably be to
extend the ADOdb_lite class, but there doesn't seem to be...
|
by: 2005 |
last post by:
Hi
In C++, are the following considered best practices or not?
- passing aguments to functions (ie functions do not take any arguments
)
- returning values using return statement
Anything...
|
by: vizcayno |
last post by:
Hello:
Need your help in the "correct" definition of the next function. If
necessary, I would like to know about a web site or documentation that
tells me about best practices in defining...
|
by: =?Utf-8?B?VGVycmFuY2U=?= |
last post by:
Hello, I was wondering if someone can give me a few pointers in catching an
exception correctly or at least making the code a little more elegant than
what I have. I have a rss reader that I built...
|
by: skanemupp |
last post by:
which is the best way to check if a string is an number or a char?
could the 2nd example be very expensive timewise if i have to check a
lot of strings?
this
value = raw_input()
try:...
|
by: bukzor |
last post by:
Does anyone have a pythonic way to check if a process is dead, given
the pid?
This is the function I'm using is quite OS dependent. A good candidate
might be "try: kill(pid)", since it throws an...
|
by: DolphinDB |
last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation.
Take...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
| |