Re: Python documentation too difficult for beginners

2010-11-02 Thread John McMonagle
On 03/11/10 05:04, John Nagle wrote:

Right.  Google does a far better job of organizing Python's
 documentation than the Python community does.  I don't even try
 looking up anything starting at Python.org; I always start
 with a Google search.  Even though Python.org's search is
 powered by Google, it's inferior to a general search.
 
Compare:
 
 http://www.google.com/search?domains=www.python.orgsitesearch=www.python.orgq=open
 
 
 http://www.google.com/search?q=Python+open
 


Even better:


http://www.google.com/search?sitesearch=docs.python.orgq=open


Regards,

John McMonagle
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Display file names in Tkinter Listbox

2010-05-20 Thread John McMonagle
s...@home.com wrote:

 I have made the modifications and it does print inside the listbox,
 however they are all  printed on the same line. 
 

Sorry, I didn't realize askopenfilenames returned the filenames as a
whitespace separated string, on my system they are returned as a tuple
of strings.


 My files are named Name.0 Name.1 Name.2 Name.3 etc so I would like
 them to be printed sorted on a separate line. When I did a 
 type(fileNames) it showed me that it was in unicode and printed
 character per line, so I tried it this way
 
 listFileNames = str(fileNames).split(' ')
 for fileName in listFileNames:
   self.lbox.insert(0, fileName)
   
 it works but does not print sorted.
 
 it prints
 
 name.2
 name.1
 name.0
 name.3
 
 

You obviously need to sort the list before you loop over the items and
add them to your listbox.

listFileNames = sorted(str(filenames).split()


Regards,

John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Display file names in Tkinter Listbox

2010-05-19 Thread John McMonagle
r...@home.com wrote:
 Hello,
 
 My first attenpt at a simple  python Tkinter application. I wanted to
 see how to load file names into a listbox from a menu. This is what I
 got until the part of displaying the file names in a listbox, which I
 could not figfure out how to do?
 
 Any help would be appreciated. Trying to do this as simple as possible
 to understand.
 
 The print fileNames does work but how to display it in listbox?
 
 from Tkinter import *
 from tkFileDialog   import askopenfilenames
 
 class MyCode:
def __init__(self):
   root = Tk()
   
   menubar = Menu(root)
   filemenu = Menu(menubar)
   
   lbox = Listbox(root, width=50).pack()

Your problem is the above line of code.

Here you are assigning the return value of the pack (None if I recall).

Later when you want to put things in the Listbox you don't have the
widget reference anymore.

It's probably a good idea to make the Listbox widget an attribute of
your class so you can use it in class methods without having to pass it
as an argument.

So, change the above line of code to:

self.lbox = Listbox(root, width=50)
self.lbox.pack()

   
   menubar.add_cascade(label='File', menu=filemenu)
   filemenu.add_command(label='New Project')
   filemenu.add_command(label='Load Files...', command=self.OnLoad)
   
 
   filemenu.add_command(label='Exit', command=root.quit)
   
   root.config(menu=menubar)
   
   root.mainloop()
   
   
def OnLoad(self):
   fileNames = askopenfilenames(filetypes=[('Split Files', '*')])
   print fileNames
 

Now that you've got a reference to your Listbox widget that is an
attribute of your class, you should be able to insert the file names
into the Listbox like so.

self.lbox.insert(0, fileNames)

Regards,

John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Programming Challenges for beginners?

2009-11-27 Thread John McMonagle
n00m wrote:
 On Nov 27, 5:24 am, astral orange 457r0...@gmail.com wrote:
 [skip]
 
 How about the next problem:
 you are given string s (len(s) = ~1), in the string only
 letters 'a'..'z'
 Task: to count the number of all *different* substrings of s
 
 Example:
 s = 'abbaz'
 Its different substrings are:
 a
 b
 z
 ab
 bb
 ba
 az
 abb
 bba
 baz
 abbaz
 ==
 Answer: 11

Way to fail dude.

You're missing some sub-strings.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter / Entry widget problem

2009-07-14 Thread John McMonagle
Andras Szabo wrote:
 Hello. I searched the archives but couldn't find a solution to a problem
 related to the Entry widget in Tkinter.
 
 When creating a pop-up window in an app, which contains an Entry widget,
 I want this widget to contain some default string, to have all this
 default string selected (as if the user had manually selected
 everything), and to have the focus transferred to this widget.
 
 (The idea is then that if the window pops up, the user won't have to
 click or press Tab any more before being able to type what is needed in
 the textbox, overwriting what is written there already.)
 
 I thought this might be the way to go:
 
 entrybox=Entry(toplevel_parent_window)
 entrybox.insert(0,Some default string)
 entrybox.select_range(0,END)
 entrybox.focus_set()
 entrybox.pack()
 
 But it doesn't seem to work - the focus is not transferred to the Entry
 widget, and the text does not appear to be selected (even though after
 this entrybox.selection_present() returns True).
 
 What am I doing wrong?
 
 andras

You're probably not updating after the focus_set.

Try the following:

from Tkinter import *
r = Tk()


def click():
t = Toplevel(r)
e = Entry(t)
e.pack()
b = Button(t, text='Close', command=t.destroy)
b.pack()
e.insert(0, 'Default')
e.select_range(0, END)
e.focus_set()
r.update()



b = Button(r, text='Press', command=click)
b.pack()

r.mainloop()



Regards,

John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: rectangles, or cavases, or ... ?

2009-04-20 Thread John McMonagle
Alan G Isaac wrote:
 I need to display many (e.e., 2000) small squares whose colors are udpated
 each time a computation is complete.
 
 One approach is to put rectangles on a single canvas.
 Another approach is to put many canvases in a single frame.
 Another approach is to create an image each iteration,
 which is placed on a canvas.
 Other?
 
 Are there obvious considerations in the choice?
 (Right now I do not need to interact with the squares,
 but in the future I may need to.)
 
 Thanks,
 Alan Isaac

Approach 1: put many rectangles on a single canvas

This is the most flexible approach.  It allows you to take advantage of
Tkinter canvas tag bindings to interact with individual or groups of
canvas items.   It also allows you to use some pretty handy find methods
for the canvas items (find_closest, find_withtag, etc).  You can
configure properties of the item, such as fill colour, without needing
to redraw all the items.

The downside of this approach is, because each rectangle you draw is a
canvas item, it is also an object.  The implications of this is that
your memory usage increases with the more items you draw.



Approach 2: put many canvasses on a frame

This has no advantages.  In fact it has no good points at all.

Memory usage would quickly increase.  You would have to use the place
geometry manager to put the canvasses exactly where you want in the
frame. You would have to write a bunch of custom functions to interact
with all the canvasses.


Approach 3: create an image and draw on a canvas

This approach may be the solution if the number of canvas items becomes
too memory intensive.  You can construct the image object using an image
library like PIL or aggdraw and place it on a Canvas.

However, every time you need to update the image you need to redraw the
whole image.

My advice

as long as your system can handle the memory usage, I would opt for the
draw many rectangles on a single canvas approach.


Regards,

John
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to query object of GUI?

2009-04-14 Thread John McMonagle
Muddy Coder wrote:
 Hi Folks,
 
 I need to query the ID of GUI, in Tkinter, but don't know how to do
 it. This is my code:
 
 calss MyGUI:

def make_menu(self):
   top = Menu(self)
   menObj = Menu(top)
   labels = read_from_database()
   for lab in labels:
  menObj.add_command(label=lab, command=self.do_menu)
def do_menu(self):
   # here I need query which menu item was clicked
 

Pass the name of the label as an argument to the callback.  Below is a
short working example:


from Tkinter import *

root = Tk()

def do_menu(l):
print 'menu pressed is ', l

menubar = Menu(root)
lab = 'test'
menubar.add_command(label=lab, command=lambda l=lab: do_menu(l))
lab = 'quit'
menubar.add_command(label=lab, command=lambda l=lab: do_menu(l))
root.config(menu=menubar)

root.mainloop()



Regards,

John
--
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter: loading file before entering mainloop

2009-03-15 Thread John McMonagle
Peter Billam wrote:
 On 2009-03-14, Peter Otten __pete...@web.de wrote:
 Well, I don't know where the ymid[...] values come from. If you can
 guarantee that ymid[track_num] - ymid[track_num-1]  50 at some point
 you could reschedule loadFile() from within loadFile() and return
 immediately as long as that condition is not met.
 
 They're multiplied up from
   canvas_height = self.canvas.winfo_height()
 so I guess mainloop already think it's idle, while grid is still taking
 10ms to work out what goes where. It's not a specifically canvas thing,
 because to the left of the canvas there is a frame (called trackbar)
 which has the same height, and self.trackbar.winfo_height() gives the
 same effects.
 
 Your suggestion would also defend me against small screens, or midi-
 -files with large numbers of tracks (I'll impose a max_retries)...
 
 Thanks,  Regards,  Peter
 
You need to query the requested width and height for windows which are
not yet realised.

canvas_height = self.canvas.winfo_reqheight()


Regards,

John
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting screen dims platform specific? Say it ain't so!

2009-02-24 Thread John McMonagle
Lionel wrote:
 Yes, it's platform specific. I was just trying anyway to see if it
 would work.
 
 In a nutshell, what I need is a way to acquire the screen dimensions
 (in pixels) and its dpi setting.

This should work on all platforms:

from Tkinter import *
r = Tk()
r.withdraw()
r.winfo_screenheight()
r.winfo_screenwidth()
r.winfo_pixels('1i')


Regards,

John
--
http://mail.python.org/mailman/listinfo/python-list


Re: string[i:j:k]

2008-07-22 Thread John McMonagle
konstantin wrote:

 
 Thanks!
 It seems that negative step leads in reverse direction.
 But logic isn't completely clear for me.
 s = '123456789'
 s[::-2]
 '97531'
 
 but
 s[:-1:-2]
 ''
 though I expected something like '8642'
 What did i missed?
 
 --


You need to *start* at the second from last index:

s[-2::-2]

Regards,

John
--
http://mail.python.org/mailman/listinfo/python-list


Re: a simple 'for' question

2008-07-08 Thread John McMonagle
Ben Keshet wrote:
 Hi fans,
 
 I want to use a 'for' iteration to manipulate files in a set of folders,
 something like:
 
 folders= ['1A28','1A6W','56Y7']
 for x in folders:
print x # print the current folder
f = open('my/path/way/x/my_file.txt', 'r')
...
 

Use os.path.join


import os
folders = ['1A2B', '1A6W', '56Y7']
for x in folders:
f = open(os.path.join('my/path/way', x, 'my_file.txt'), 'r')


--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with a for loop and a list

2008-07-02 Thread John McMonagle
Alexnb wrote:
 well okay, so what can I do?
 
 
 
Firstly, stop top posting.  Replies to a thread flow better if bottom
posted.

Secondly, it sounds like you want to build a list of the results from
your entry.get() calls.

Try this:

self.wordList = []
def getWords(self):
for entry in self.listBuffer:
self.wordList.append(entry.get())

print self.wordList


--
http://mail.python.org/mailman/listinfo/python-list


Re: this worked before...' '.join([`x x` for x in range(1, 6)])

2008-05-19 Thread John McMonagle
[EMAIL PROTECTED] wrote:
 ' '.join([`x  x` for x in range(1, 6)])
 
 anyone can tell me what im doing wrong?
 --
 http://mail.python.org/mailman/listinfo/python-list
 


' '.join(['%s %s' % (str(x), str(x)) for x in range(1,6)])

or

' '.join([str(x)+' '+str(x) for x in range(1,6)])


outputs

'1 1 2 2 3 3 4 4 5 5'


Is that what you were after ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: The stange behaviour of Tkinter.Canvas

2008-03-11 Thread John McMonagle
James Yu wrote:
 I tried to update the rectangle on a canvas to get the visual effect of
 progressbar.
 It works all right if I delete the existing objects (rectangle and text)
 and create a new one.
 However, if I invoke canvas.itemconfig() to update the existing objects'
 options, gui just went nuts.
 I am more than happy to receive any help and advise.
  

Snipped code

 canv.itemconfig(rect, width=width*progress/100)  ##

The width option of a rectangle item does not change the rectangles
width, but changes the width of the rectangle perimiter line.

You need to modify the coordinates of the rectangle item:

canv.coords(rect, 0, 0, width*progress/100, height)

Regards,

John


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter--unexpected behavior with pack_forget()

2007-12-20 Thread John McMonagle
Kevin Walzer wrote:
 I'm trying to toggle the visibility of a Tkinter widget using 
 pack_forget(), and I'm running into unexpected behavior. The widget 
 hides correctly, but does not become visible again. My sample code is 
 below:
 
 
 from Tkinter import *
 
 root = Tk()
 
 label = Label(text=Hello)
 label.pack()
 
 def toggle():
  if label.winfo_ismapped:
  print mapped
  label.pack_forget()
  else:
   label.pack()
 
 button = Button(text=Push me, command=toggle)
 button.pack()
 
 root.mainloop()
 -
 
 The expected behavior is for the label to hide (pack_forget()) if 
 label.winfo_ismapped returns true. That works as . However, I would also 
 expect the widget to be displayed/packed if it is not mapped. What 
 happens instead is that the label is apparently mapped even after I call 
 label.pack_forget().
 
 Can anyone point out what I'm doing wrong? Calling pack forget from 
 Tcl maps/unmaps the widget as expected. In this case, I can't quite 
 figure out where my error is.
 



if label.winfo_ismapped:  always evaluates to True.

Instead, you need,

if label.winfo_ismapped():

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python - why don't this script work?

2007-10-22 Thread John McMonagle
Ohmster wrote:
 I am trying to use this cool script that some MIT guy wrote and it just 
 does not work, I get a stream of errors when I try to run it. It is 
 supposed to visit a URL and snag all of the pictures on the site. Here is 
 the script:
 http://web.mit.edu/pgbovine/www/image-harvester/image-harvester.py
 
 Here is my output when I try to run it on my Fedora 6 machine:
 
 [EMAIL PROTECTED] bench]$ image-harvester.py 
 http://public.fotki.com/DaGennelman/
 /home/ohmster/scripts/image-harvester.py: line 59: from: command not found
 [EMAIL PROTECTED] bench]$
 
 The script is to be folowed up with another one to weed out the small 
 thumbnails and banner images, here is the base URL:
 http://web.mit.edu/pgbovine/www/image-harvester/
 
 Line 59 in image-harvester.py reads as follows:

 59:   from sgmllib import SGMLParser
 60:   import urllib
 70:   from urlparse import urlparse, urljoin
 71:   import re
 72:   import os# Usage: python image-harvester.py url-to-harvest
 
 
 Can anyone tell me what is wrong with this script and why it will not run? 
 It does not like the command from, is there such a command in python? 
 Does this mean that python has the import command but not the from 
 command or do we not know this yet as it hangs right away when it hits the 
 very first word of the script, from? Maybe this is not a Linux script or 
 something? I wonder why it needs the x-server anyway, I tried running it 
 from an ssh term window and it had a fit about no x-server so now I am 
 doing this in a gnome term window. This looked so cool too. :(
 
 Please be patient with me, I do not know python at all, I just want for 
 this script to work and if I see enough working examples of python, I may 
 just take up study on it, but for right now, I do not know the language. 
 Total newbie.
 
 Thanks.
 
 

Your linux shell thinks it is running a shell script (from is not a
valid command in bash).

To execute this script with the python interpreter type (from a shell
prompt):

python image-harvester.py http://some.url.whatever/images_page

Read the comments at the beginning of the script and you will discover
all sorts of important usage information.

Regards,

John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating a tar file with python

2007-08-23 Thread John McMonagle
Brian McCann wrote:
 Hi,
  
 I'm trying to create a tar file of the contents of the current directory
  
 right now there is only one file text.xml in the current dir,  I'm 
 using. current dir as source
 but that gives syntax error
 
 any help would be greatly appreciated
 --Brian
  
  
 #!/usr/bin/python
 import string
 import os
 import sys
 import time
 import errno
 import shutil
 import tarfile
  
 
 tar = tarfile.open(.,test.tar.gz, w:gz)

Contents of current directory in a new gzipped tarfile (includes 
hidden *nix files):


import tarfile, glob
t = tarfile.open('tarfilename.tar.gz', 'w:gz')
for filename in glob.glob('*')+glob.glob('.*'):
 t.add(filename)
t.close()

Note: this includes any subdirectories and their files below the current 
level.

Regards,

John



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error with Tkinter and tkMessageBox

2007-08-02 Thread John McMonagle
Fabio Z Tessitore wrote:
 I've tried to use Twm and SURPRISE! it works!!!
 
 Can you say why? How can I fix the prob with Gnome?
 
 Thanks

I don't know why it doesn't work correctly on the version of gnome which 
you are running (I run KDE).  Perhaps the question needs to be posed to 
a gnome group ?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error with Tkinter and tkMessageBox

2007-08-01 Thread John McMonagle
Fabio Z Tessitore wrote:
 hi all,
 
 this Tkinter very simple code work fine:
 
 ##
 from Tkinter import *
 
 win = Tk()
 win.mainloop()
 ##
 
 but if I try to open a message box, it happens:
 
 Exception in Tkinter callback
 Traceback (most recent call last):
   File lib-tk/Tkinter.py, line 1348, in __call__
 return self.func(*args)
   File /home/fabio/Desktop/prova.py, line 5, in reply
 showinfo(title='ciao', message='hello')
   File lib-tk/tkMessageBox.py, line 84, in showinfo
 return _show(title, message, INFO, OK, **options)
   File lib-tk/tkMessageBox.py, line 75, in _show
 res = Message(**options).show()
   File lib-tk/tkCommonDialog.py, line 52, in show
 s = w.tk.call(self.command, *w._options(self.options))
 TclError: bad pad value 2m: must be positive screen distance
 
 
 ##
 from Tkinter import *
 from tkMessageBox import *
 
 def reply():
   showinfo(title='ciao', message='hello')
 
 win = Tk()
 but = Button(win, text='press me', command=reply)
 but.pack()
 win.mainloop()
 ##
 
 these are versions:
 
 python:   2.4.4 or 2.5.1
 Tkinter.TclVersion:   8.4
 Tkinter.TkVersion:8.4
 
 can anyone help me?
 thanks
 
What window manager are you using ?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter help, please...

2007-05-24 Thread John McMonagle
I've made a couple of minor changes to your code from the Cribbage class 
down:

class Cribbage:
  def __init__(self, win):

  self.parent = win#  make the toplevel Tk window an
   #  attribute of the class
  #Draw the interface
  self.f = Frame(self.parent)
  self.f.grid()
  self.cardpix = [Label(self.f), Label(self.f), Label(self.f), 
Label(self.f), Label(self.f)]
  clr = [red, blue]
  n = 1
  for c in self.cardpix:
  c.configure(width=10, height=10, bg=clr[n%2], text=card 
+str(n))
  c.grid(row=0, column=n-1)
  n += 1
  self.scorebox = Label(self.f)
  self.scorebox.configure(height=5, bg=green, text=Score: 0)
  self.scorebox.grid(row=1, column=0, columnspan=5)

  def play(self):
  d = Deck()
  hand = [d.deal(), d.deal(), d.deal(), d.deal()]
  flipped = d.deal()
  hand.append(flipped)
  hand.sort()
  score = tally(hand, flipped)
  self.scorebox.configure(text= Score:  + str(score))
  #Eventually, display the actual card images, but for now...
  for c, x in zip(hand, self.cardpix):
  x.configure(text = str(c))
  #I've tried both of these, to no avail.
  self.parent.update() update the toplevel window
  return score

def main():
  win = Tk()
  run = Cribbage(win)
  score = 0
  best = 0
  while score  24:
  score = run.play()
  if score = best: best = score
  time.sleep(1)  --- short sleep to see what's happening
  win.mainloop()

main()



Regards,

John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: {Possible_Spam} tkFileDialog.askopenfilename()

2007-05-15 Thread John McMonagle
[EMAIL PROTECTED] wrote:
 Hi,
 When I call tkFileDialog.askopenfilename() , the dialog box opens with
 the current directory as the default directory. Is it possible to open
 the dialog box with a directory other than the current directory. Can
 we pass in  a user defined starting directory.
 Thanks
 Rahul
 

tkFileDialog.askopenfilename() uses the tk command tk_getOpenFile, the 
documentation for which is at:

http://www.tcl.tk/man/tcl8.4/TkCmd/getOpenFile.htm

Regards,

John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where did my post go?

2007-04-25 Thread John McMonagle
[EMAIL PROTECTED] wrote:
 I posted to this newsgroup earlier about my annoyances with python and
 now I can't find the post. What did you do with it?
 

How annoying.

Seriously though,  I saw it - delivered at 8:50 AEST.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, how to get a button's bg color

2007-04-03 Thread John McMonagle
[EMAIL PROTECTED] wrote:
 I am new to Tkinter.  Following an example, I executed the following:
 
 window = Tk()
 b = Button(window)
 b.configure(bg = '#FF00FF')
 b.grid(row = 0, column = 0)
 
 how can I later get the value of this button's background color?
 
 Thanks.
 

b.cget('bg')


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PMW widget - skip tabbing to it

2007-03-26 Thread John McMonagle
jp wrote:

 On Mar 26, 10:51 am, jp [EMAIL PROTECTED] wrote:
 I have multiple PMW widgets (EntryFields, ScrolledField etc), how can
 I skip over these widgets when using the tab key?
 Thank you,
 John

What version of Pmw are you using ?  Tabbing between widgets works fine 
on my system (Pmw 1.2,  tk 8.4, KDE)

I can change the focus behaviour by using the takefocus option.  You 
were on the right track, you just did it wrong (see code below):


from Tkinter import *
import Pmw

root = Tk()
entry = Pmw.EntryField(root, labelpos=W, value=, label_text='Name:')
entry.grid(row=1)
entry.component('entry').configure(takefocus=0)

Button(root,text='test1').grid(row=2)
Button(root,text='test2').grid(row=3)
Button(root,text='test3').grid(row=4)

root.mainloop()
#

Regards,

John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Associate image name with list item

2007-03-26 Thread John McMonagle
Kevin Walzer wrote:
 I'm trying to avoid a *lot* of typing in my Tkinter application by 
 associating image names with items in a list. Here is my sample list:
 
 self.catlist = [
  'all', 'installed', 'base', 'crypto', 'database', 'devel',
  'editors', 'games', 'gnome', 'graphics', 'kde', 'languages', 
 'libs', 'libs_perlmods',
  'libs_pythonmods', 'libs_rubymods', 'net', 'sci', 'shells', 
 'sound', 'text', 'web',
  'x11_system', 'x11-wm', 'x11'
  ]
 
 I've also already created a bunch of images with names that correspond 
 to the list above, i.e. self.all, self.installed, and so on.  Here's the 
 rest of my code:
 
 for item in self.catlist:
  print item
  self.categorytable.insert(END, item)
   self.categorytable.cellconfigure(end,0, image=self.item)
 
 This yields the following error:
 
 AttributeError: item
 
 because, of course, I don't actually have an image called self.item.
 
 What I'm trying to do is get the value of the variable item and plug 
 it into the image name, so that self.item actually corresponds to 
 self.installed, self.base, etc. Trying something like
 
 self.categorytable.cellconfigure(end,0, image=self.%s % item)
 
 just yields a syntax error: SyntaxError: invalid syntax
 
 Can anyone point me in the right direction?



Create a dictionary mapping the name to the image object.  For example:

# Create all your images first

# Map a name to the image object
self.catdict = {'all' : self.all, 'installed' : self.installed, ...}

# Loop over the image names and do your stuff
for item in self.catdict.keys():
   print item
   self.categorytable.insert(END, item)
   self.categorytable.cellconfigure(end,0,image=self.catDict.get(item))

Regards,

John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help with radionbutton

2007-03-26 Thread John McMonagle
Sang Park wrote:
 how do I select radionbutton by default? 
 for my school project, I need to have 10 radio buttons and have half of 
 them selected
 I have
 for i in range(10):
 x = IntVar()
 if i  5:
 rb = Radiobutton(buttonFrame, variable=x, value=1,state=DISABLED)
 else:
 rb = Radiobutton(buttonFrame, variable=x, value=0,state=DISABLED)
 
 I tried x.set(1) or x.set(0) before or after but the all seem to be 
 deselected when displayed on the screen
 I also tried calling rb.select/deselect() but that doesn't seem to work 
 either...
 can anyone help me?
 
 
Sounds like you actually want to use Checkbuttons.  Radiobuttons allow 
unique selections from a group all tied to a single variable whereas 
Checkbuttons act like an on/off toggle.

Regards,

John

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem I have with a while loop/boolean/or

2007-03-13 Thread John McMonagle
[EMAIL PROTECTED] wrote:
 Hi all.
 
 I have a problem with some code :(
 
 ---
 
 hint = raw_input(\nAre you stuck? y/n: )
 hint = hint.lower()
 
 while (hint != 'n') or (hint != 'y'):
 hint = raw_input(Please specify a valid choice: )
 
 -
 
 so everytime I run the program, and enter my choice as y or n, I'm
 told to 'Please Specify a valid Choice Again' and can't get out of the
 loop.
 
 
 
 ---
 
 hint = raw_input(\nAre you stuck? y/n: )
 hint = hint.lower()
 
 while (hint != 'n'):
 hint = raw_input(Please specify a valid choice: )
 
 -
 
 As for here when I enter n, I can leave the while loop.
 
 Anyway I can't put my finger on this, so I'd be real grateful if
 someone could tell me what I've done wrong. Thanks.
 (I have a guy feeling it's something really silly I'm overlooking...)

Try it a different way:

while True:
 hint = raw_input(\nAre you stuck? y/n: )
 hint = hint.lower()
 if hint != 'y' and hint != 'n':
 print Please answer y or n
 continue
 else:
 break
if hint == 'y':
 do_your_hint_stuff()


 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: {Possible_Spam} Re: {Possible_Spam} tkinter text editor

2007-03-09 Thread John McMonagle

-- Original Message ---
From: Gigs [EMAIL PROTECTED]
To: John McMonagle [EMAIL PROTECTED]
Sent: Sat, 10 Mar 2007 15:13:20 +0100
Subject: {Possible_Spam} Re: {Possible_Spam} tkinter text editor

 John McMonagle wrote:
  Gigs_ wrote:
  I'm writing text editor.
 
  How to enable/disable (cut, copy etc.) when text is selected/not 
  selected
 
 
  Bind the Button1-ButtonRelease event to a function which checks the 
  length of the SEL tag of the text widget.  If it is zero length, 
  disable the appropriate menu entries, if it is non-zero, enable the 
  appropriate menu entries.
 
  Simple example:
 
 
  from Tkinter import *
  root = Tk()
 
  textWidget = Text(root)
  textWidget.pack()
 
  def onButton1Release(event):
  if len(textWidget.tag_ranges(SEL)) == 0:
  print 'No text selected.  Disable appropriate menu entries'
  else:
  print 'Some text selected.  Enable appropriate menu entries'
 
  textWidget.bind('Button1-ButtonRelease', onButton1Release)
 
  root.mainloop()
 
 thx, but what i dont know is how to change state on menu item.
 I dont know how to access that menu item later.
 I know on button like
 B = Button(root)
 B.pack()
 
 and later i change with B.config(blabla)
 
 but on menu i have more items like
 M = Menu(root)
 i.add_command(label='one', command=show1)
 i.add_command(label='two', command=show2)
 M.add_cascade(label='File', menu=i)
 
 how to change item: 'two'
 

Use the entry config method of the Menu widget:

i.entryconfig('one', state=DISABLED)

Here is some recommended reading:

http://www.pythonware.com/library/tkinter/introduction/x5841-methods.htm


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: {Possible_Spam} tkinter text editor

2007-03-08 Thread John McMonagle
Gigs_ wrote:
 I'm writing text editor.
 
 How to enable/disable (cut, copy etc.) when text is selected/not selected


Bind the Button1-ButtonRelease event to a function which checks the 
length of the SEL tag of the text widget.  If it is zero length, disable 
the appropriate menu entries, if it is non-zero, enable the appropriate 
menu entries.

Simple example:


from Tkinter import *
root = Tk()

textWidget = Text(root)
textWidget.pack()

def onButton1Release(event):
 if len(textWidget.tag_ranges(SEL)) == 0:
 print 'No text selected.  Disable appropriate menu entries'
 else:
 print 'Some text selected.  Enable appropriate menu entries'

textWidget.bind('Button1-ButtonRelease', onButton1Release)

root.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter __call__

2007-02-15 Thread John McMonagle
Gigs_ wrote:
 from Tkinter import *
 from tkFileDialog   import askopenfilename
 from tkColorChooser import askcolor
 from tkMessageBox   import askquestion, showerror
 from tkSimpleDialog import askfloat
 
 demos = {
  'Open':  askopenfilename,
  'Color': askcolor,
  'Query': lambda: askquestion('Warning', 'You typed
 ...\nConfirm?'),
  'Error': lambda: showerror('Error!', He's dead, Jim),
  'Input': lambda: askfloat('Entry', 'Enter credit card number')
 }
 
 
 class Demo(Frame):
  def __init__(self, parent=None):
  Frame.__init__(self, parent)
  self.pack()
  Label(self, text=Basic demos).pack()
  for (key, value) in demos.items():
  func = (lambda key=key: self.printit(key))
  Button(self, text=key, command=func).pack(side=TOP, fill=BOTH)
  def printit(self, name):
  print name, 'returns =', demos[name]()
 
 
 I have tried but cant get it to work properly.
 I want to instead printit method to put __call__ and call it like that
 Can someone help me, please?

Add the following lines to the end of your script and all should work as 
expected:

root = Tk()
app = Demo(root)
root.mainloop()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Simple Way To Determine If File Is Executable

2006-12-14 Thread John McMonagle
Tim Daneliuk wrote:
 I have a program wherein I want one behavior when a file is set as executable
 and a different behavior if it is not.  Is there a simple way to determine
 whether a given named file is executable that does not resort to all the
 lowlevel ugliness of os.stat() AND that is portable across Win32 and *nix?
 

os.access(pathToFile, os.X_OK)

-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No output from popen in Tkinter text widget

2006-12-11 Thread John McMonagle
Kevin Walzer wrote:
 I'm trying to display the output of an external process (invoked via
 popen) in a Tkinter text widget. I successfully start the process (based
 on what I'm seeing in my terminal output), but I can't get the output to
 display in the Tkinter widget. It seems to block.
 
 Any ideas? My code is below:
 
 def runDump(self):
 
 self.password.destroy()
 
 self.passtext = self.passtext.get()
 
 file = os.popen('echo %s | sudo -S /usr/sbin/tcpdump  -v  -i
 en1' % self.passtext, 'r')
 
 for line in file:
 self.t.insert(END, line)
 

self.t.update()


-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter: Strange behavior using place() and changing cursors

2006-11-14 Thread John McMonagle
Mudcat wrote:
 Is there something I'm supposed to do in order
 to prevent this from happening?

Yes.  Instead of configuring the cursor on the frame, do it on the master:

self.master.configure(cursor='sb_h_double_arrow')




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find out the directory that the py file is in?

2006-10-24 Thread John McMonagle
On Wed, 2006-10-25 at 02:49 +0100, Steve Holden wrote:
 [EMAIL PROTECTED] wrote:
  
  On Oct 24, 7:01 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:
  
 At Tuesday 24/10/2006 20:39, [EMAIL PROTECTED] wrote:
 
 
 I have the following python script and some_command in the same
 directory. I have to call the python script from that directory.
 Otherwise, some_command won't be found. I'm wondering how to make the
 following script working no matter what the working directory is.print
  
  
 os.path.abspath(__file__)
  
  
  How to get the absolute dir name which the file is in? Is there any
  function can be called easily?
  
  Thanks,
  Peng
  
 
 That would be
 
os.path.split(os.path.abspath(__file__))[0]
 
 You *are* planning to read the documentation at some stage, right? ;-)
 

More simple:

os.path.dirname(os.path.abspath(__file__))



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Delete items in nested dictionary based on value.

2006-09-13 Thread John McMonagle

 
 Assuming dict_sweep worked perfectly it would take input like this:
 
 A_in = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None}
 
 B_in = {1: {1: {1: None, 2: {1: None}}, 2: 2, 3: None}
 
 and output this:
 
 A_out = {1: {2: 2, 3: {2: 2}}, 2: 2}
 
 B_out = {2:2}
 
 This dict_sweep above obviously doesn't work and I'm rather afraid of
 hitting python's recursion limit. Does anyone see a way to modify
 dict_sweep in it's current state to perform dictionary sweeps like
 this? What about a non-recursive implementation of dict_sweep?
 

How about this:

A_in = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None}

def dict_sweep(dictin):

for key in dictin.keys():   
if dictin.get(key) == None:
del dictin[key]
elif type(dictin[key]) is dict:
dictin[key] = dict_sweep(dictin[key])
return dictin

A_out = dict_sweep(A_in)
print A_out
 



Running the above returns:

{1: {2: 2, 3: {2: 2}}, 2: 2}

Regards,

John




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython: StaticText Event

2006-09-07 Thread John McMonagle

 Hovering mouse over the StaticText Control should generate an
 EVT_ENTER_WINDOW event like the TextCtrl Control, but it does not happen.
 
 How can I make the StaticText event working?
 

According to the book wxPython In Action, page 186:

One feature that you cannot see from just the figure is that the
wx.StaticText window never receives or responds to mouse events, and
never takes the user focus.



If you want to create static text that responds to mouse events, try
using the wx.lib.stattext.GenStaticText class.  

Add the following import:

import wx.lib.stattext

Then,

self.st = wx.lib.stattext.GenStaticText(self.pnl, -1, 'Static Text
Control', pos=(30,20))

Regards,

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: split string problems

2006-09-07 Thread John McMonagle
On Thu, 2006-09-07 at 16:21 -0700, Tempo wrote:
 [span class=sale
 $14.99
 /span, span class=sale
 $27.99
 /span, span class=sale
 $66.99
 /span, span class=sale
 $129.99
 /span, span class=sale
 $254.99
 /span]

Worked alright for me (see below).  Are you sure p is a string ?

Cut and paste from interactive python shell:

 p = 
... [span class=sale
... $14.99
... /span, span class=sale
... $27.99
... /span, span class=sale
... $66.99
... /span, span class=sale
... $129.99
... /span, span class=sale
... $254.99
... /span]
 p.split()
['[span', 'class=sale', '$14.99', '/span,', 'span',
'class=sale', '$27.99', '/span,', 'span', 'class=sale',
'$66.99', '/span,', 'span', 'class=sale', '$129.99', '/span,',
'span', 'class=sale', '$254.99', '/span]']
 p.split()[2]
'$14.99'


Regards,

John


-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter text Key event

2006-09-06 Thread John McMonagle
On Wed, 2006-09-06 at 17:54 -0700, Jay wrote:
 I'm having trouble with using the Key event with the Text object.
 When I use them together (which is a logical combination), I use this
 code:
 
   textbox = Text(root, wrap=word, height=15, width=50)
   textbox.bind(Key, resolveGlyphs)
 
 def resolveGlyphs(event):
   textBuf = textbox.get(1.0, END)
   print(textBuf)
 
 What it prints out for me is everything except for the last character
 -- the one that triggered the event.  How can I get the entire
 contents?
 

bind the textbox to the KeyRelease event because by then it has been
drawn on the Text widget.  The Key event is equivalent to the
KeyPress event

Regards,

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eval() woes

2006-08-28 Thread John McMonagle
On Mon, 2006-08-28 at 21:13 -0700, rdrink wrote:

 
 (BTW, as a footnote: For each of the above 'equations' the function
 equate() was called 500 times... in some cases with the list 'parts'
 equaling things like ['0',2','3','0'], so I have no reason to believe
 that the problem is with the way the list is being passed in... but I
 could be wrong)
  
 Can anyone see something I can't?

Why don't you simply print parts as the first statement of your equate
function to check what its value is.  Then work out where in your code
parts is being modified (especially parts[1]).

Regards,

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using python at the bash shell?

2006-08-07 Thread John McMonagle
On Mon, 2006-08-07 at 21:03 -0400, John Salerno wrote:
 Hi all. I just installed Ubuntu and I'm learning how to use the bash 
 shell. Aside from the normal commands you can use, I was wondering if 
 it's possible to use Python from the terminal instead of the normal bash 
 commands (e.g. print instead of echo). 

From a terminal window typing, 

python -c print 'testing'

would produce the same results as

echo 'testing'

in bash shell, but obviously not as nice.

 My main reason for asking is that 
 I like using Python for everything, and if I don't need to learn the 
 bash 'language', then I won't just yet.
 

Just type python and do your stuff in the python interpreter.  This
becomes your shell.

This then got me thinking, how about making python your login shell.  So
I modified my shell login entry in /etc/passwd to /usr/bin/python,
logged in and voila, I was presented with my friendly python shell upon
opening a terminal window.

So the answer is Yes.





-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Import module with non-standard file name

2006-08-07 Thread John McMonagle
On Tue, 2006-08-08 at 11:06 +1000, Ben Finney wrote:
 Howdy all,
 
 Question: I have Python modules named without '.py' as the extension,
 and I'd like to be able to import them. How can I do that?
 
 Background:
 
 On Unix, I write programs intended to be run as commands to a file
 with no extension. This allows other programs to use the command as an
 interface, and I can re-write the program in some other language
 without obsoleting the commandline interface.
 
 e.g., I might write 'frobnicate-foo' as a shell program so that other
 programs can 'frobnicate-foo --bar baz'. If I later decide to
 re-implement 'frobnicate-foo' in Python, I'll save the top level
 module to the same file name since it implements the same command-line
 interface.
 
 Now that I've got it written as a Python module, I'd like to write
 unit tests for that module, which of course will need to import the
 program module to test it. The unit test can explicitly add the
 directory where the program module lives to 'sys.path' for the purpose
 of importing that module.
 
 However, the Python reference tells me that 'import' (specifically,
 '__import__()') needs modules to live in files named a particular way:
 with a '.py' suffix. But my module is in a file called
 'frobnicate-foo', with no suffix, and that's part of the definition of
 the program interface.
 
 I don't want symbolic links, or anything else that presents two
 filenames for the same module, because there's no need for that except
 for Python's apparent insistence on a particular naming
 convention. Also, avoiding symbolic links inside the source code tree
 makes version control smoother.
 
 
 What are my options to import a module from a file whose name can't
 change?

Why don't you just create a link to the appropriate script ?

For example, 

[EMAIL PROTECTED] ~]$ ln -s frobnicate-foo.py frobnicate-foo
[EMAIL PROTECTED] ~]$ ll frobnicate*
lrwxrwxrwx  1 me mygroup 17 Aug  8 12:56 frobnicate-foo -
frobnicate-foo.py*
-rwxr-xr-x  1 me mygroup  0 Aug  8 12:55 frobnicate-foo.py*
-rwxr-xr-x  1 me mygroup  0 Aug  8 12:55 frobnicate-foo.sh*
[EMAIL PROTECTED] ~]$

That way you can keep the bash shell script and the python script
independent of one another and you can still import for your unit
testing without any trickery.

Regards,

John




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is it possible to dividing up a class in multiple files?

2006-08-07 Thread John McMonagle
On Mon, 2006-08-07 at 15:41 +0200, Martin Höfling wrote:
 Hi there,
 
 is it possible to put the methods of a class in different files? I just 
 want to order them and try to keep the files small.
 

Here's how I do it:

Firstly, I create a file called imports.py which contains all my import
statements.  These are obviously indented at the zero position.

I then create a classname.py file.  This just has the class statement
(eg: class Foo:)
.

I then create a separate file for each function in the class.  Eg:
init.py, function1.py, etc).  These must be indented by one indent
position.

I then create a main.py file.  This contains statements to be executed
after all the statements in the class.

I create a shell script which concatenates the files in the correct
order

eg:

cat imports.py \
classname.py \
init.py \ 
function1.py \
...
...
..
main.py  module.py

I use the concatenated file, module.py, as the program to run or import.

I find it easier to maintain code in this way - if I need to make a
change to a particular function, I just edit the file in which the
function is defined and re-run the shell script to make the program.  If
I need to add a new function to the class I just need to create a new
file and add its entry to the shell script in the correct place and
re-run the shell script.

Of course you are not limited to a single function per file, but that is
what works best for me.

Regards,

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: two embedded problem. one maybe is python bug.

2006-08-03 Thread John McMonagle
On Fri, 2006-08-04 at 11:10 +0800, yy x wrote:
 hi,all,
  
  
  
 the content of a.py :
 #coding:gb2312
 #/usr/local/bin/python
 import random
 print random.randint(0,10)
  
 the c program:
 #include Python.h
 int main()
 {
 Py_Initialize();
 PyRun_SimpleString(import sys);
 PyRun_SimpleString(sys.path.append('.'));
 
 PyRun_SimpleString(import a);
 Py_Finalize();
 
 return 0;
 }
 
 the gcc cmd line:
 
g++ -o a a.c
 -I/usr/local/include/python /usr/local/lib/libpython -lm -lpthread
 -ldl
 
 First problem:
 
 when i run the a, the error msg is :
 
   Traceback (most recent call last):
   File string, line 1, in ?
   File ./a.py, line 1
 SyntaxError: encoding problem: with BOM
 
  
 
 but if i first import a.py through the python cmd line.  This problem
 disappears.(but second problem appears)(now  I think  the a import
 a.pyc not a.py)
 
 I think  it's python bug, isn't it?
 
 Second problem,
 
Traceback (most recent call last):
   File string, line 1, in ?
   File a.py, line 3, in ?
 import random
   File /usr/local/lib/python2.4/random.py, line 44, in ? 
 from math import log as _log, exp as _exp, pi as _pi, e as _e
 ImportError: /usr/local/lib/python2.4/lib-dynload/math.so: undefined
 symbol: PyExc_OverflowError.
 
  
 
 Pls give me some advice, i am crazy.thanks
 
  
 

Sorry, but both programs work fine on my system (Mandriva Linux 2006
-2.6.12 kernel, python 2.4.1, gcc 4.0.1).

Obviously I had to change a couple of paths to includes and libraries,
but apart from that running a.py and the compiled c program worked fine.

Perhaps it would help if you told us a bit about your particular
configuration.

Regards,

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Working with Widget after Instance loses the reference

2006-07-31 Thread John McMonagle
On Mon, 2006-07-31 at 11:15 -0700, Al in Dallas wrote:
 I made the mistake of creating an instance of a widget and assigning it
 to a name I'd already used. Now, if I use root.children or
 root.slaves(), I can see the lost widget, but can I do anything else
 with the string of numbers that shows up when I use root.children? I'd
 like to destory the widget, for example. it would be even better if I
 could create a new name and have it reference the lost widget.
 
 Of course, I can just kill my toplevel and start over.
 


Consider the following code run in the python shell:

 from Tkinter import *
 r = Tk()
 b1 = Button(r, text='test')
 b1.pack()
 b2 = Button(r, text='test2')
 b2.pack()
 r.children
{'-1210160564': Tkinter.Button instance at 0xb7de6a4c, '-1210225748':
Tkinter.Button instance at 0xb7dd6bac}
 r.slaves()
[Tkinter.Button instance at 0xb7dd6bac, Tkinter.Button instance at
0xb7de6a4c]
 b1 = 'xxx' 
 b1.destroy()
Traceback (most recent call last):
  File stdin, line 1, in ?
AttributeError: 'str' object has no attribute 'destroy'
 b1 = r.slaves()[0]
 b1.destroy()



So, as long as you know what your widget instance is in root.slaves() or
root.children you can assign it to a new name.




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how best to check a value? (if/else or try/except?)

2006-07-27 Thread John McMonagle
On Thu, 2006-07-27 at 20:44 +, 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.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: update a window with tkinter ...

2006-07-27 Thread John McMonagle
On Thu, 2006-07-27 at 19:56 +0200, Laurent Hermann wrote:
 Hi I'm new on this list so let me say hello to everybody.
 
 
 I have a little problem with tkinter but I could not find the solution
 on the net so I ask it here...
 
 
 The thing I want to do is simple but I cannot, I would like to have a
 tkinter window that update itself during the program is running, I
 created a small exemple :
 
 
 
 
 from Tkinter import *
 import time
 
 
 fen1=Tk()
 can1=Canvas(fen1,bg='dark grey',height=100,width=100)
 can1.pack()
 
 
 a=0
 
 
 while(a10):
 time.sleep(1)
 tex1=can1.create_text (10*a,10*a,text=a)
 a=a+1
 
Change the loop to:

while a10:
  time.sleep(1)
  can1.create_text(10*a, 10*a, text=str(a)) # a should be a string
for a canvas text object
  a += 1
  can1.update()

 
 can1.pack()

Don't need to repack canvas widget.

 fen1.mainloop()
 

Regards,

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: webbrowser open failing

2006-07-26 Thread John McMonagle
On Wed, 2006-07-26 at 17:09 +1200, Thomas wrote:
 Hi all,
 
 I am getting an error using webbrowser open on mac 10.3 using python  
 2.3.5
 
   test=open(/Volumes/TINTZ;P3/DT Hot Folder  
 test/Justin_Test.pDF,r)
   type(test)
 type 'file'
   webbrowser.open(/Volumes/TINTZ;P3/DT Hot Folder  
 test/Justin_Test.pDF,r)
 Traceback (most recent call last):
File stdin, line 1, in ?
File  
 /System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
 python2.3/webbrowser.py, line 43, in open
  get().open(url, new, autoraise)
File  
 /System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
 python2.3/webbrowser.py, line 314, in open
  ic.launchurl(url)
File  
 /System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
 python2.3/plat-mac/ic.py, line 235, in launchurl
  return _dft_ic.launchurl(url, hint)
File  
 /System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
 python2.3/plat-mac/ic.py, line 202, in launchurl
  self.ic.ICLaunchURL(hint, url, 0, len(url))
 MacOS.Error: (-673, 'no URL found')

Try opening a file-type URL:

eg:
webbrowser.open(file://Volumes/TINTZ;P3/DT)

No need for the 'r' argument to open.

Syntax is:

 webbrowser.open(url [, new])

If new is True a new browser window is opened.



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function to convert degree (hour), minute, seconds string to integer

2006-07-26 Thread John McMonagle
On Wed, 2006-07-26 at 20:18 -0700, John Machin wrote:
 [EMAIL PROTECTED] wrote:
  I know this is a trivial function, and I've now spent more time
  searching for a surely-already-reinvented wheel than it would take to
  reinvent it again, but just in case... is there a published,
  open-source, function out there that takes a string in the form of
  hh:mm:ss (where hh is 00-23, mm is 00-59, and ss is 00-59) and
  converts it to an integer (ss + 60 * (mm + 60 * hh))?  I'd like
  something that throws an exception if hh, mm, or ss is out of range, or
  perhaps does something reasonable (like convert 01:99 to 159).
  Thanks,
  --dang
  p.s.
  In case this looks like I'm asking for a homework exercise, here's what
  I'm using now.  It returns False or raises a ValueError exception for
  invalid inputs.  I'm just wondering if there's an already-published
  version.
  def dms2int(dms):
  Accepts an 8-character string of three two-digit numbers,
  separated by exactly one non-numeric character, and converts it
  to an integer, representing the number of seconds.  Think of
  degree, minute, second notation, or time marked in hours,
  minutes, and seconds (HH:MM:SS).
  return (
  len(dms) == 8
  and 00 = int(dms[0:2])  24
  and dms[2] not in '0123456789'
  and 00 = int(dms[3:5])  60
  and dms[5] not in '0123456789'
  and 00 = int(dms[6:8])  60
  and int(dms[6:8]) + 60 * (int(dms[3:5]) + 60 * int(dms[0:2]))
  )
 
 Have you considered time.strptime()?
 
 BTW, your function, given 00:00:00 will return 0 -- you may well have
 trouble distinguishing that from False (note that False == 0), without
 resorting to ugliness like:
 
 if result is False ...
 
 Instead of returning False for some errors and letting int() raise an
 exception for others, I would suggest raising ValueError yourself for
 *all* invalid input.
 
 You may wish to put more restrictions on the separators ... I would be
 suspicious of cases where dms[2] != dms[5]. What plausible separators
 are there besides :? Why allow alphabetics? If there's a use case for
 23h59m59s, that would have to be handled separately. Note that
 06-12-31 could be a date, 12,34,56 could be CSV data.
 
 Cheers,
 John
 


You may also want to look at the dateutil module (especially dateutil.parse).




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help in string.digits functions

2006-07-24 Thread John McMonagle
On Mon, 2006-07-24 at 22:19 -0700, Anoop wrote:
 Hi All
 
 I am getting two different outputs when i do an operation using
 string.digits and test.isdigit(). Is there any difference between the
 two. I have given the sample program and the output
 
 Thanks for ur inputs
 
 Anoop
 
 #1:
 ~~
 import string
 
 test='121206'
 
 if test not in string.digits:
 print I am Not Digit
 else:
 print I am Digit
 
 #2:
 ~~
 import string
 
 test='121206'
 
 if not test.isdigit():
 print I am Not Digit
 else:
 print I am Digit
 
 Output
 ~
 #1:I am Not Digit
 #2:I am Digit
 
 Thnks and Rgds 
 
 Anoop
 


string.digits is the string constant '0123456789'

So your test, if test not in string.digits: will evaluate True because
'121206' is not in '0123456789'.

Whereas test.isdigit() returns true if all the characters in test are
digits.

So yes, there is a big difference between the two.

Regards,

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter focus_set use with grid

2006-07-19 Thread John McMonagle
On Thu, 2006-07-20 at 02:53 +, Stan Cook wrote:
 A newbie to Tkinter here. . . . . .
 
 I'm trying to set the focus on an Entry textbox with 
 focus_set.  I am using the grid manager.  I created the same 
 interface before using the  pack() method and the focus_set 
 worked, but now it says
 
 AttributeError: 'NoneType' object has no attribute 'focus_set'
 
 Below is the section of the code:
 
 # CREATES THE GUI FOR DCN INPUT
 def get_dcn():
   master = Tk()
   _dcn = StringVar()
   label1 = Label(text=Enter DCN:,width=10).grid(row=0)
   txtbox = Entry(relief=SUNKEN, width=20, takefocus=1, 
 textvariable=_dcn).grid(row=0, column=1)
   txtbox.focus_set()
   btnOK= 
 Button(text=OK,command=assign_dcn(_dcn)).grid(row=1, column=0)
   btnCancel = Button(text=Cancel, 
 command=killer).grid(row=1, column=1)
   master.mainloop()
   return
 
 Does anyone know where I went wrong?


Yes.  You set txtbox to be the return result of Entry(...).grid(...)
which is None.

What you want to do is is set txtbox to a tkinter instance:


def get_dcn():
master = Tk()
_dcn = StringVar()
label1 = Label(text=Enter DCN:,width=10)
label1.grid(row=0)
txtbox = Entry(relief=SUNKEN, 
   width=20,
   takefocus=1,
   textvariable=_dcn)
txtbox.grid(row=0, column=1)
txtbox.focus_set()
btnOK= Button(text=OK,command=assign_dcn(_dcn))
btnOK.grid(row=1, column=0)
btnCancel = Button(text=Cancel, command=killer)
btnCancel.grid(row=1, column=1)
master.mainloop()
return

Regards,

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter help

2006-07-18 Thread John McMonagle
On Tue, 2006-07-18 at 08:37 -0700, groves wrote:
 hi eveyrbody , i have started working on python tkinter,
 While I was working on one of the tkinter classes..named listbox
 widget. I had a slight problem.
 
 Now let me tell you that i was able to create a simple listbox which
 had 6 options which one can select, but Now what I want is that from
 the available menu, if I select an option it should give me another
 menu associated with that option. Its like digging up that option to do
 advance search.
 
 Please I need help as I am making my project
 Thanks to eveyrbody who will take time to read this and solve it .
 

Perhaps if you posted your code so far we could help - otherwise we
would just be shooting in the dark.



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter StringVar mystery

2006-07-17 Thread John McMonagle
On Mon, 2006-07-17 at 15:00 -0600, Bob Greschke wrote:
 First off I have this class (thanks to whoever came up with this way back 
 when):
 
 ##
 # BEGIN: class Command
 # LIB:Command():2006.110
 #Pass arguments to functions from button presses and menu selections,
 #bind's.  Nice!
 #In your declaration:
 #...command = Command(func, args,...)
 class Command:
 def __init__(self, func, *args, **kw):
 self.func = func
 self.args = args
 self.kw = kw
 def __call__(self, *args, **kw):
 args = self.args+args
 kw.update(self.kw)
 apply(self.func, args, kw)
 # END: class Command
 
 
 Then in the setup part of an entry form I have:
 
 # CHBCBarcodeLastVar is the variable for an Entry() field
 Button(SubFrame, text = Print Barcode, \
 command = Command(test, other, CHBCBarcodeLastVar.get(), \
 CHBC)).pack(side = LEFT)
 
 
 Then this is a/the test function:
 
 def test(What, BC, Where, e = None):
 # Does print the correct value
 print CHBCBarcodeLastVar.get()
 # Does change the field on the form
 CHBCBarcodeLastVar.set(5)
 # BC is 
 print :+What+:, :+BC+:, :+Where+:
 return
 
 Everything works as it should, except when the Button is clicked BC is an 
 empty str in test().  How come?  (I really have NO clue how that Command 
 class works, but I use it like crazy.  Is it the problem?)

The problem is when you are creating the Print Barcode button.  Think
about what the value of CHBCBarcodeLastVar.get() is when you create the
button ?  I bet it is an empty string.  This value will always be passed
to test, regardless of how it changes in the future.  What you probably
want is to pass the StringVar reference and then do a get in test.

Eg:

# CHBCBarcodeLastVar is the variable for an Entry() field
Button(SubFrame, text = Print Barcode, \
command = Command(test, other, CHBCBarcodeLastVar, \
CHBC)).pack(side = LEFT)

def test(What, BC, Where, e = None):
print :+What+:, :+BC.get():, :+Where+:
return

Regards,

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execute a shell script from a python script

2006-07-17 Thread John McMonagle
On Mon, 2006-07-17 at 16:59 -0700, spec wrote:
 Thanks, actually there are no args, is there something even simpler?
 
 Thanks
 Frank
 
 
 Thomas Nelson wrote:
  If your script is foo.sh and takes args:
  import subprocess
  subprocess.call([foo.sh,args],shell=True)
  Should work fine.  check out
  http://www.python.org/dev/doc/maint24/lib/module-subprocess.html
 
  Enjoy,
  THN
 
  spec wrote:
   Hi all, I know nothing about Python. What I need to do is to get a
   Python script to execute a local shell script. I do not need any
   output. What would be th eeasiest way to accomplish this?
   
   Thanks!
 
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 

Check out os.popen4  or the commands module.




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Find and Delete all files with .xxx extension

2006-07-12 Thread John McMonagle
On Wed, 2006-07-12 at 16:12 -1000, normt's subject read:

 Find and Delete all files with .xxx extension


How ?  In the current directory/folder ?  Recursively search through all
the directories/folders from a certain path ?

I suggest you look at the os module (section about Files and
Directories)

http://docs.python.org/lib/os-file-dir.html




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mouse wheel event for Canvas

2006-06-22 Thread John McMonagle
On Thu, 2006-06-22 at 14:24 +1000, John McMonagle wrote:
 I tried binding mouse wheel events (Button-4, Button-5) to a Tkinter
 Canvas widget with the hope of using the event.delta value to
 subsequently scroll the Canvas.
 
 However, it seems that event.delta always returns 0.
 
 For example,
 
 from Tkinter import *
 
 r = Tk()
 c = Canvas(r, scrollregion=(0,0,500,500), height=200, width=200)
 s = Scrollbar(r, command=c.yview)
 c.pack(side=LEFT)
 s.pack(side=RIGHT, fill=Y)
 c.configure(yscrollcommand=s.set)
 c.create_rectangle(10,10,100,100)
 c.create_rectangle(10,200,100,300)
 
 def rollWheel(event):
 print event.delta
 
 c.bind('Button-4', rollWheel)
 c.bind('Button-5', rollWheel)
 
 c.focus_set()
 
 r.mainloop()
 
 
 Has anyone successfully managed to wheel scroll a Tkinter Canvas
 widget ?
 
 Regards,
 
 John
 
 
 

I worked it out.

c.bind('Button-4', lambda event: event.widget.yview_scroll(-1, UNITS))
c.bind('Button-5', lambda event: event.widget.yview_scroll(1, UNITS))

I also changed the yscrollincrement to '5p'.  The default moved a bit
too much.



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Mouse wheel event for Canvas

2006-06-21 Thread John McMonagle
I tried binding mouse wheel events (Button-4, Button-5) to a Tkinter
Canvas widget with the hope of using the event.delta value to
subsequently scroll the Canvas.

However, it seems that event.delta always returns 0.

For example,

from Tkinter import *

r = Tk()
c = Canvas(r, scrollregion=(0,0,500,500), height=200, width=200)
s = Scrollbar(r, command=c.yview)
c.pack(side=LEFT)
s.pack(side=RIGHT, fill=Y)
c.configure(yscrollcommand=s.set)
c.create_rectangle(10,10,100,100)
c.create_rectangle(10,200,100,300)

def rollWheel(event):
print event.delta

c.bind('Button-4', rollWheel)
c.bind('Button-5', rollWheel)

c.focus_set()

r.mainloop()


Has anyone successfully managed to wheel scroll a Tkinter Canvas
widget ?

Regards,

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter: making widgets instance or not?

2006-06-06 Thread John McMonagle
On Tue, 2006-06-06 at 19:42 +, John Salerno wrote:
 Fredrik Lundh wrote:
 
  however, if you need to access a widget later on, it might be a good 
  idea to save a reference to it somewhere...
 
 To follow up on that point, I have the following code now. I have two 
 questions about it:
 
 1. Can I somehow make the passing of 'master' to the draw_entry method 
 automatic, so I don't have to type it each time I call the function?
 
 2. Related to your comment, the obvious problem here is that it doesn't 
 save references to the text box names, so I can't access them later. Is 
 there still a way to automate the process like I've done, but have each 
 entry field have a separate name?
 
 Thanks.
 
 ---
 
 import Tkinter as tk
 
 
 class App:
 
  def __init__(self, master):
  self.draw_entry(master, 'First Name:')
  self.draw_entry(master, 'Last Name:')
 
  def draw_entry(self, master, label_text):
  frame = tk.Frame(master, bd=4)
  frame.pack()
  self.label = tk.Label(frame, text=label_text, width=10)
  self.label.pack(side=tk.LEFT)
  self.entry = tk.Entry(frame)
  self.entry.pack(side=tk.LEFT)
 
 
 root = tk.Tk()
 app = App(root)
 root.resizable(width=False, height=False)
 root.mainloop()
 -- 


Try this:

import Tkinter as tk

class App:

def __init__(self, master):
self.parent = master
self.entry1 = self.draw_entry('First Name:')
self.entry2 = self.draw_entry('Last Name:')

def draw_entry(self, label_text):
frame = tk.Frame(self,parent, bd=4)
frame.pack()
label = tk.Label(frame, text=label_text, width=10)
label.pack(side=tk.LEFT)
entry = tk.Entry(frame)
entry.pack(side=tk.LEFT)
return entry

root = tk.Tk()
app = App(root)
root.resizable(width=False, height=False)
root.mainloop()



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter: making widgets instance or not?

2006-06-06 Thread John McMonagle
On Wed, 2006-06-07 at 09:27 +1000, John McMonagle wrote:
 On Tue, 2006-06-06 at 19:42 +, John Salerno wrote:
  Fredrik Lundh wrote:
  
   however, if you need to access a widget later on, it might be a good 
   idea to save a reference to it somewhere...
  
  To follow up on that point, I have the following code now. I have two 
  questions about it:
  
  1. Can I somehow make the passing of 'master' to the draw_entry method 
  automatic, so I don't have to type it each time I call the function?
  
  2. Related to your comment, the obvious problem here is that it doesn't 
  save references to the text box names, so I can't access them later. Is 
  there still a way to automate the process like I've done, but have each 
  entry field have a separate name?
  
  Thanks.
  
  ---
  
  import Tkinter as tk
  
  
  class App:
  
   def __init__(self, master):
   self.draw_entry(master, 'First Name:')
   self.draw_entry(master, 'Last Name:')
  
   def draw_entry(self, master, label_text):
   frame = tk.Frame(master, bd=4)
   frame.pack()
   self.label = tk.Label(frame, text=label_text, width=10)
   self.label.pack(side=tk.LEFT)
   self.entry = tk.Entry(frame)
   self.entry.pack(side=tk.LEFT)
  
  
  root = tk.Tk()
  app = App(root)
  root.resizable(width=False, height=False)
  root.mainloop()
  -- 
 
 
 Try this:
 
 import Tkinter as tk
 
 class App:
 
 def __init__(self, master):
 self.parent = master
 self.entry1 = self.draw_entry('First Name:')
 self.entry2 = self.draw_entry('Last Name:')
 
 def draw_entry(self, label_text):
 frame = tk.Frame(self,parent, bd=4)

Sorry - typo.  Should reas self.parent  not self,parent

 frame.pack()
 label = tk.Label(frame, text=label_text, width=10)
 label.pack(side=tk.LEFT)
 entry = tk.Entry(frame)
 entry.pack(side=tk.LEFT)
 return entry
 
 root = tk.Tk()
 app = App(root)
 root.resizable(width=False, height=False)
 root.mainloop()
 
 
 
 -- 
 This message has been scanned for viruses and
 dangerous content by MailScanner, and is
 believed to be clean.
 


-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter - changing existing Dialog?

2006-06-01 Thread John McMonagle
On Thu, 2006-06-01 at 08:31 -0400, Michael Yanowitz wrote:
 Hello:
 
 
I have a Tkinter GUI Dialog with many buttons and labels and text
 widgets.
 What I would like to do is, can I:
 
 1) Disable/deactivate/hide a button, text widget that is already drawn (and
of course the opposite enable/activate/show it)?
 
 2) Change the text of a label or button that is already drawn?
 
   based on actions taken by the user. Can it be done without destroying
 the present dialog or the objects in it and creating a new one?
 
   Sorry for what probably is such a trivial and basic question. I just can't
 find the answer or know what the technical term for what I want to do is to
 search for it myself.

To disable/deactivate a button widget, use the keyword 'state'.  For
example, 


import Tkinter as Tk
root = Tk.Tk()
bid = Tk.Button(root, text='test', state=Tk.NORMAL)
bid.pack()
bid.configure(state=Tk.DISABLED)

If you want to hide the button (using Pack geometry manager):

bid.pack_forget()

You can pack it again using bid.pack() but it may be difficult to pack
it back where you originally intended.

If you are using the Grid geometry manager:

bid.grid_forget()

To put it back simply call grid again with the same row, column.



Changing the text of a label or button already drawn is simply done by a
call to the configure method on the button or label's text attribute:

bid.configure(text='Help')

Regards,

John







-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter question

2006-05-31 Thread John McMonagle
On Wed, 2006-05-31 at 11:37 -0400, david brochu jr wrote:
 I am trying to create a GUI that will display a new window with
 information about my program when the user clicks on the info button
 (a green i bitmap). So far all I can get my program to do is show
 the new window (using Toplevel() ) when the program loads, not when
 the user presses the information bitmap. I think it has something to
 do with my command for the information button. Anyone have any ideas
 or have a GOOD resource that they could point me to?
  

Indeed the problem is to do with your command for the information
button.

Keeping it in your coding style, change it to:

self.info_bttn[command] = self.info

Regards,

John

 


-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beginner: using parameter in functions

2006-05-31 Thread John McMonagle
On Wed, 2006-05-31 at 23:24 +, 3rdshiftcoder wrote:
 hi-
 
 i am having trouble using parameter values in my function and to be honest a 
 little trouble with
 member variables.  i am trying to pass in the argument 'd' representing 
 delete.
 what the code will do is if it is 'd' it will make a delete query template 
 string.
 if it is an 'i' then insert query etc.
 
 this is the results of my attempt to print the contents of the parameter 
 values.
 __main__.getQryStr instance at 0x01151D50 ('d',) me mad
 
 
 (and on a side note if i dont include the *args i get an invalid number of 
 parameters supplied message.)
 why is it returning the value in this format ('d',) ?
 i cant get x == d
 i guess that value 'd' is stored in a tuple and i'd like to get it out of 
 there.
 
 so basically the function returns nope as it stands
 
 python is sure different from other languages i have used.
 
 thanks for any help,
 jim
 


Try, the following:

class getQryStr:
def __init__(self,op):
print op
self.x = 'd'
def returnStr(self, *args):

print '%s %s me mad' % (self.x,args)
if self.x == 'd':
s = Template(delete from columndef where tblid = $tblid and
colname = $colname)
else:
return 'nope' #this else is just for illustration and
testing

d = dict(tblid=t.tblid.getText(), colname=t.colName.getText())

print s.substitute(d)

return s


Regards,

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TIming

2006-05-30 Thread John McMonagle
Tue, 2006-05-30 at 00:23 -0500, WIdgeteye wrote:
 On Tue, 30 May 2006 04:34:03 +, Tim Roberts wrote:
 
  WIdgeteye [EMAIL PROTECTED] wrote:
 HI,
 I am trying to write a little program that will run a program on scedule.
 I am having trouble understanding the datetime, time, sched modules. What
 I would like is something like this:
 
 If datetime = 06-13-2006:18:00:00
 Then run this program
 
 I am not sure how to enter a future date in this equation using any of
 the modules mentioned above. I have figured out how to get the date and
 time from the modules above but not the future and then compare the two.
  
  What operating system are you using?  Both Linux and Windows have commands
  that can do this for you.  It's more efficient to use existing operating
  system services than to invent your own.
  
  Also, remember to take into account the possibility that your program
  might not check the time at the exact second.  In your example, you need
  to be prepared to start your app if the time is just PAST 6 PM on June 13.
 
 I am using Linux and could use cron. But I want to be able to 
 schedule and record television shows on her. And yeah I know about 
 freevo but it's way to complicated than it needs to be.
 
 So back to the question: How can I get a 9 position tuple from 
 the time functions in Python based on a future date.

Tim Roberts is right.  As you are on linux, I suggest you investigate
the at command - very user friendly and not at all complicated.






-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tabs versus Spaces in Source Code

2006-05-14 Thread John McMonagle
Personally, I don't think it matters whether you use tabs or spaces for
code indentation.  As long as you are consistent and do not mix the two.



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Image open problem

2006-04-19 Thread John McMonagle
On Thu, 2006-04-20 at 10:29 +1000, John Machin wrote:
 On 20/04/2006 6:55 AM, Aleksandar Cikota wrote:
  Hi all,
  
  I have a problem with openning of an image.
  
  Here is the Code:
  
  from Tkinter import *
  from PIL import Image, ImageTk

Change from PIL import Image, ImageTk to import PIL and change all your
corresponding Image calls to PIL.Image and all your ImageTk calls to
PIL.ImageTk.

If that works, then something else is mangling Image.

Regards,

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create a tear off menu in TKinter. Help Needed

2006-04-06 Thread John McMonagle
On Thu, 2006-04-06 at 12:27 -0700, ishtar2020 wrote:
 Hi everybody
 
 I'd appreciate some help on creating a tear off menu with TkInter. I've
 been reading some documentation but still no luck.
 
 Please don't get confused: when I mean tear off menu I don't mean a
 drop-down or a pop-up menu, but those options which yield to another
 batch of sub-options when scrolled over, (as for example, the File-New
 option from internet explorer).
 
 I'm sure TkInter supports those widgets because the IDLE editor is
 built on it and it's got some tear off options like File-Recent Files.
 
 Thank you all in advance
 

 Are you sure you don't mean a cascading menu ?  A tearoff menu gives the user 
the ability to tear off the menu into a new top level window.

The following example illustrates the difference:

from Tkinter import *
r = Tk()
m = Menu(r)

# Create a cascading Edit menu
editmenu = Menu(m, tearoff=0)
editmenu.add_command(label='copy')
editmenu.add_command(label='cut')
editmenu.add_command(label='paste')

# Create a sub menu of the edit menu and use tearoff option
testmenu = Menu(editmenu, tearoff=1)
testmenu.add_command(label='option1')
testmenu.add_command(label='option2')

# add the sub menu to the editmenu
editmenu.add_cascade(label='test', menu=testmenu)

# Add the edit menu to the menu bar
m.add_cascade(label='Edit', menu=editmenu)


# Display the menu
r.config(menu=m)

r.mainloop()


John McMonagle



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: binding - python

2006-04-06 Thread John McMonagle
On Thu, 2006-04-06 at 16:39 -0700, beta wrote:
 Hi John,
 
 It works! thank you vey much.
 
 I have another question. I would very appreciated if you have any clue.
 
 I want the ball STOP whenever mouse is clicked anywhere, then ball KEEP
 MOVING when next mouse click is applied. Thanks.
 

I do have a clue.  Simply bind a mouse click to the entire canvas widget
rather than the canvas item.

Add the following line after you create the canvas widget:

self.draw.bind('Button-1', self.toggleBallMotion)

where toggleBallMotion stops the ball movement if it is moving and
starts the movement if it is stopped.  It is a function of the form:

def toggleBallMotion(self, event):
if self.speed.get() != 0:
self.oldspeed = self.speed.get()
self.speed.set(0)
else:
self.speed.set(self.oldspeed)

You will also need to initialise the self.oldspeed variable when you
first create the Scale widget.

John McMonagle




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mouse event - binding

2006-04-05 Thread John McMonagle
On Wed, 2006-04-05 at 09:21 -0700, beta wrote:
 Dear John,
 
 Thanks for your help. I don't know how to bind the ball only into a
 program. Would you mind help me on this? I added the changeColour
 function, here is a complete program.

...SNIP code...


Add the following code after you draw the ball item for the first time:

self.draw.tag_bind(self.ball, 'Button-1', changeColour)




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mouse event - binding

2006-04-05 Thread John McMonagle
On Wed, 2006-04-05 at 16:04 -0700, beta wrote:
 Hi John,
 
 It don't work!
 I did what you told me, here is theBall function
 
 def theBall(self):
  self.ball = self.draw.create_oval(0i, 0i, 0.20i,
 0.20i,
   fill=red)
  self.draw.tag_bind(self.ball, 'Button-1', changeColour)
 


Sorry, that should read:

self.draw.tag_bind(self.ball, 'Button-1', self.changeColour)


-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mouse event - binding

2006-04-05 Thread John McMonagle
On Wed, 2006-04-05 at 16:04 -0700, beta wrote:
 Hi John,
 
 It don't work!
 I did what you told me, here is theBall function
 
 def theBall(self):
  self.ball = self.draw.create_oval(0i, 0i, 0.20i,
 0.20i,
   fill=red)
  self.draw.tag_bind(self.ball, 'Button-1', changeColour)
 

Sorry, that should read:

self.draw.tag_bind(self.ball, 'Button-1', self.changeColour)


-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: binding - python

2006-04-05 Thread John McMonagle
Quoc,

the following code, verbatim, works for me:

from Tkinter import *

class Pong(Frame):
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
   command=self.quit)
self.QUIT.pack(side=LEFT, fill=BOTH)

## The playing field
self.draw = Canvas(self, width=5i, height=5i)

## The speed control for the ball
self.speed = Scale(self, orient=HORIZONTAL, label=ball speed,
   from_=-100, to=100)

self.speed.pack(side=BOTTOM, fill=X)

# The ball
self.ball = self.draw.create_oval(0i, 0i, 0.20i,0.20i,
fill=red)
self.draw.tag_bind(self.ball, 'Button-1', self.changeColour)
self.x = 0.05
self.y = 0.05
self.velocity_x = 0.3
self.velocity_y = 0.5

self.draw.pack(side=LEFT)

def changeColour(self, event):
x = self.draw.canvasx(event.x)
y = self.draw.canvasy(event.y)
item = self.draw.find_closest(x,y)
currentColour = self.draw.itemcget(item, 'fill')
if currentColour == 'red':
   self.draw.itemconfigure(item, fill='blue')
else:
   self.draw.itemconfigure(item, fill='red')

def moveBall(self, *args):
if (self.x  5.0) or (self.x  0.0):
self.velocity_x = -1.0 * self.velocity_x
if (self.y  5.0) or (self.y  0.0):
self.velocity_y = -1.0 * self.velocity_y

deltax = (self.velocity_x * self.speed.get() / 100.0)
deltay = (self.velocity_y * self.speed.get() / 100.0)
self.x = self.x + deltax
self.y = self.y + deltay

self.draw.move(self.ball,  %ri % deltax, %ri % deltay)
self.after(10, self.moveBall)

def __init__(self, master=None):
Frame.__init__(self, master)
Pack.config(self)
self.createWidgets()
self.after(10, self.moveBall)

game = Pong()

game.mainloop()

Cut and paste it into a file and try it out.  Make sure you check for
line breaks on long lines.

John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mouse event - binding

2006-04-04 Thread John McMonagle
On Tue, 2006-04-04 at 14:46 -0700, beta wrote:
 Hello All,
 
 I am new with Python, your help would be very appreciated.
 
 I have a simple pinpong applicaiton. I would like make a ball's color
 change when mouse is clicked on it.
 
 Here is my sample code:
 
 from Tkinter import *
 
 import string
 
 
 class Pong(Frame):
 def createWidgets(self):
 self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit)
 self.QUIT.pack(side=LEFT, fill=BOTH)
 
 ## The playing field
 self.draw = Canvas(self, width=5i, height=5i)
 
 ## The speed control for the ball
 self.speed = Scale(self, orient=HORIZONTAL, label=ball speed,
from_=-100, to=100)
 
 self.speed.pack(side=BOTTOM, fill=X)
 
 # The ball
 #self.ball = self.draw.create_oval(0i, 0i, 0.10i,
 0.10i,
 #  fill=red)
 self.theBall()
 self.x = 0.05
 self.y = 0.05
 self.velocity_x = 0.3
 self.velocity_y = 0.5
 
 self.draw.pack(side=LEFT)
 def theBall(self):
  self.ball = self.draw.create_oval(0i, 0i, 0.20i,
 0.20i,
   fill=red)
 
 def moveBall(self, *args):
 if (self.x  5.0) or (self.x  0.0):
 self.velocity_x = -1.0 * self.velocity_x
 if (self.y  5.0) or (self.y  0.0):
 self.velocity_y = -1.0 * self.velocity_y
 
 deltax = (self.velocity_x * self.speed.get() / 100.0)
 deltay = (self.velocity_y * self.speed.get() / 100.0)
 self.x = self.x + deltax
 self.y = self.y + deltay
 
 self.draw.move(self.ball,  %ri % deltax, %ri % deltay)
 self.after(10, self.moveBall)
 
 def __init__(self, master=None):
 Frame.__init__(self, master)
 Pack.config(self)
 self.createWidgets()
 self.after(10, self.moveBall)
 
 
 game = Pong()
 
 game.mainloop()
 
 Thanks,
 
 -- 

You need to bind a button-1 event to the ball tag.  After you initially
create the ball item:

self.draw.tag_bind(self.ball, 'Button-1', changeColour)

where changeColour is a function like so:

def changeColour(self, event):
x = self.draw.canvasx(event.x)
y = self.draw.canvasy(event.y)
item = self.draw.find_closest(x,y)
currentColour = self.draw.itemcget(item, 'fill')
if currentColour == 'red':
self.draw.itemconfigure(item, fill='blue')
else:
self.draw.itemconfigure(item, fill='red')

This will toggle the ball colour between red and blue.

HTH,

John McMonagle



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter canvas

2006-04-04 Thread John McMonagle
On Tue, 2006-04-04 at 14:47 -0700, fxe wrote:
 Hi,
   I am using tkinter and I have a canvas that with several rectangles drawn
 on it. The rectangles need to have bindings to move and resize them. No
 problem here, but I also need to display a grid on the same canvas, for
 which I am using create_line. My problem is I do not want the grid lines to
 be able to move and resize .
 
 Is this doable or any suggestions on an alternative.Maybe another way to
 display my grid on top of the canvas?
 

When you create your canvas items use the tags option to differentiate
items you wish to group together.

For example, 

canvas.create_line(x1,y1,x2,y2,fill='#00',tags='grid')

canvas.create_rectangle(x1,y1,x2,y2,fill='#FF',outline='#FF',tags='rect')

You can ensure that the grid lines are always displayed below the
rectangles by using the tag_lower method:

canvas.tag_lower('grid', 'rect')

You can bind events to the named tags rather than the canvas as a whole:

canvas.tag_bind('rect', 'Button-1', startMove)
canvas.tag_bind('rect', 'Button1-Motion', moveRect)
canvas.tag_bind('rect', 'Button1-ButtonRelease', finishMove)

Now when you click on a canvas item with a 'grid' tag nothing will
happen, but if you click on a canvas item with a 'rect' tag you will
invoke the appropriate function.

HTH,

John McMonagle



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter canvas

2006-04-04 Thread John McMonagle
On Tue, 2006-04-04 at 16:42 -0700, fxe wrote:
 Hi John , thanks a million for the info.Looking at your solution I am sure
 this would work. After struggling with this for the past few hours I found
 another way just before reading your post. Its as simple as :
 
 canvas.create_line(x1,y1,x2,y2,fill='#00',state=DISABLED) 

Tom,

below is some quick and dirty code illustrating the tag_bind concept
similar to your case:

from Tkinter import *

def startMove(event):
global startx, starty, item
widget = event.widget
startx, starty = widget.winfo_pointerxy()
x = widget.canvasx(event.x)
y = widget.canvasy(event.y)
item = widget.find_closest(x,y)

def movingRect(event):
global startx, starty, item
widget = event.widget
newx,newy = widget.winfo_pointerxy()
diffx = newx - startx
diffy = newy - starty
widget.move(item, diffx, diffy)
widget.update_idletasks()
startx = newx
starty = newy

r = Tk()

c = Canvas(r, width=500, height=500)
c.pack(fill=BOTH, expand=YES)

# Draw grid lines every 50 pixels
for x in range (0,500,50):
c.create_line(x,0,x,500,tags='grid')
for y in range(0,500,50):
c.create_line(0,y,500,y,tags='grid')

# Draw some random rectangles on top
c.create_rectangle(124,124,182,190,fill='#FF',outline='#FF',tags='rect')
c.create_rectangle(90,50,100,300,fill='#FF',outline='#FF',tags='rect')
c.create_rectangle(320,210,415,290,fill='#00FF00',outline='#00FF00',tags='rect')
c.create_rectangle(400,50,450,100,fill='#00',outline='#00',tags='rect')

# bind rect tags to move functions
c.tag_bind('rect', 'Button-1', startMove)
c.tag_bind('rect', 'Button1-Motion', movingRect)

r.mainloop()

Cheers,

John McMonagle




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Multiplying all the values in a dictionary

2006-03-23 Thread John McMonagle
Say I have a dictionary like below:

d = {(100,500):[5,5], (100,501):[6,6], (100,502):[7,7]}

Say I want to multiply all the values of the dictionary by 2:

for key in d.keys():
  d[key] = map(lambda x: x*2, d.get(key))

Is there a better/faster/cleaner way to achieve this ?

Thanks,

John


-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with a reverse dictionary lookup

2006-03-09 Thread John McMonagle
On Thu, 2006-03-09 at 15:51 -0800, rh0dium wrote:
 Hi all,
 
 I have a dict which looks like this..
 
 dict={'130nm': {'umc': ['1p6m_1.2-3.3_fsg_ms']},
 '180nm': {'chartered': ['2p6m_1.8-3.3_sal_ms'], 'tsmc':
 ['1p6m_1.8-3.3_sal_log', '1p6m_1.8-3.3_sal_ms']},
 '250nm': {'umc': ['2p6m_1.8-3.3_sal_ms'], 'tsmc':
 ['1p6m_2.2-3.5_sal_log', '1p6m_1.8-3.3_sal_ms']}
 }
 
 For clarification:
 130nm,180nm,250nm refer to Nodes
 tsmc,chartered,umc refer to Foundries
 1p6m..blah, 2p6m..blah refer to Process
 
 I want a function which can do this:
 
 nodes = getNodes()
   should return a list [130nm,180nm,250nm]

I'm not going to write your function for you but the following should
help you get started.

dict.keys()  -- returns a list of the keys in your dictionary

[130nm,180nm,250nm]

 
 nodes = getNodes(Foundry=umc)
   should return a list [130nm,250nm]
 

Here you want to check if the key in the child dictionary matches some
text:

Eg:

Foundry = 'umc'
FoundryList = []
for key in dict.keys:  
  val = dict.get(key)  
  if Foundry in val.keys():
 FoundryList.append(key)

print FoundryList

[130nm,250nm]

 nodes = getNodes(Process=2p6m_1.8-3.3_sal_ms)
   should return a list [180nm,250nm]
 

Same concept here:

Process = ['2p6m_1.8-3.3_sal_ms']
ProcessList = []
for key in dict.keys():
  val = dict.get(key)
  if Process in val.values():
ProcessList.append(key)

print ProcessList

[180nm,250nm]


So key concepts you need are:

 - Get a list of keys from the dictionary -- dict.keys()
 - Get the value matching a key -- dict.get(key)
 - Get a list of values from the dictionary -- dict.values()

This should be enough to get you going.

 nodes = getNodes(Foundry=umc, Process=2p6m_1.8-3.3_sal_ms)
   should return a list [250nm]
 
 nodes = getNodes(Foundry=foo, Process=2p6m_1.8-3.3_sal_ms)
   should return None
 
 Obviously I want to extend this to Each area ( i.e., getFoundry(),
 getProcess() ) but I can do that.  I just don't know how to easily do
 this reverse kind of look up?  Can someone help me on this?
 
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 


-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Password entering system

2006-03-09 Thread John McMonagle
On Thu, 2006-03-09 at 19:42 -0800, Tuvas wrote:
 Thanks, that's exactly what I wanted!
 
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 

You may also want to check out Pmw (Python Megawidgets)

Pmw has a nifty Prompt Dialog.

See http://pmw.sourceforge.net/doc/PromptDialog.html


John



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tix, spinboxes, and 1=5

2006-02-22 Thread John McMonagle
On Wed, 2006-02-22 at 18:37 -0800, [EMAIL PROTECTED] wrote:
 This odd bug has been annoying me for several days now. I finally got
 round to making this, frankly hilarious, testcase:
 
 
 from Tix import *
 
 def sayfive(num):
 if num5: print num, 5
 else: print num,= 5
 
 sayfive(4)
 sayfive(6)
 rootwnd=Tk()
 Control(rootwnd,command=sayfive).pack()
 rootwnd.mainloop()
 
 
 So, our program starts, the first two lines executed write 46 6=5
 as expected. Now the user changes the value in the spinner, and we get
 output like 1=5. What magic is Tix pulling, and more importantly how
 the hell do I stop it?

This should fix your problem:

from Tix import *

def sayfive(num):
num = int(num)
if num5: print num, 5
else: print num,= 5

sayfive(4)
sayfive(6)
rootwnd=Tk()
Control(rootwnd,command=sayfive).pack()
rootwnd.mainloop()


The entry in the spinbox is a string.




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Basic coin flipper program - logical error help

2006-02-21 Thread John McMonagle
On Tue, 2006-02-21 at 16:14 -0800, DannyB wrote:
 I'm just learning Python.  I've created a simple coin flipper program -
 here is the code:
 
 [source]
 #Coin flipper
 import random
 
 heads = 0
 tails = 0
 counter = 0
 
 coin = random.randrange(2)
 
 while (counter  100):
 if (coin == 0):
 heads += 1
 counter += 1
 else:
 tails += 1
 counter += 1
 
 coin = random.randrange(2)
 
 
 print \nThe coin landed on heads, heads, times.
 print \nThe coin landed on tails, tails, times.
 [/source]
 
 I'm sure the [source] tags don't work - I through them in there
 anyway.
 
 The program runs - however - it will give me 100 heads OR 100 tails.
 Can someone spot the logic error?  

Yes.  Put coin = random.randrange(2) inside the while loop.

import random

heads = 0
tails = 0
counter = 0

coin = random.randrange(2)

while (counter  100):
if (coin == 0):
heads += 1
counter += 1
else:
tails += 1
counter += 1

coin = random.randrange(2)

print \nThe coin landed on heads, heads, times.
print \nThe coin landed on tails, tails, times.


-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Natural Language Date Processing.

2006-02-09 Thread John McMonagle
On Thu, 2006-02-09 at 09:47 +0100, Michael Amrhein wrote:
 Andrew Gwozdziewycz schrieb:
  You may take a look at http://labix.org/python-dateutil
  Have fun
  Michael
 
  
  Looks like it does a good job parsing dates, but doesn't seem to do
  english dates. I found a javascript implementation of a few functions
  that will probably be relatively easy to port to python. Whether or
  not it'll perform well is another story... Thanks for the help.
  
  --
  Andrew Gwozdziewycz [EMAIL PROTECTED]
  http://ihadagreatview.org
  http://plasticandroid.org
 
  from dateutil.parser import parse
  parse(April 16th, 2003)
 datetime.datetime(2003, 4, 16, 0, 0)
  parse(4/16/2003)
 datetime.datetime(2003, 4, 16, 0, 0)
 
 Aren't these english dates?

I suspect the OP is referring to english dates as non-US format - to
follow the international convention (DD/MM/).

You can use the dayfirst parameter to the parse function to always
assume international date format:

US Format:
 parse(10/12/2004)
datetime.datetime(2004, 10, 12, 0, 0)

International format:
 parse(10/12/2004, dayfirst=True)
datetime.datetime(2004, 12, 10, 0, 0)


John




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Determining an operating system's default browser

2006-02-09 Thread John McMonagle
Is there a python module which can determine an operating system's
default web browser application.

I would like to use it in the following context:  I have a GUI
application where all the documentation is written as html pages.  I
wish to have these html help pages open in the default browser when
selected from the application's Help menu

If python can determine the path to the default browser, I can then just
spawn it.

Regards,

John McMonagle




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Determining an operating system's default browser

2006-02-09 Thread John McMonagle
On Thu, 2006-02-09 at 17:53 -0600, Larry Bates wrote:
 You don't have to determine it.  Just os.startfile('page1.html')
 and let the OS figure it out.

Works great for Windows - not available on Unix though.



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nDimensional sparse histogram in python.

2006-02-01 Thread John McMonagle
On Wed, 2006-02-01 at 19:06 -0800, KraftDiner wrote:
 Cool.
 Ok so my histogram class had two methods 1) To increment a point and 2)
 to get the point.
 
 def class histo:
def __init__(self):
histo = {}
 def update(point):
'''searches the dictionary for point and if it exists increment the
 value.
 if it doesn't exist set the value to 1'''
 
 def get(point):
return self.histo[point]
 
 I'm not sure how to code up the update routine...
 
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 

def update(point);
  
  if histo.get(point) != None:
histo[point] = histo[point] + 1

Regards,

John


-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to parse structured text file?

2006-01-31 Thread John McMonagle

 I have a file which contains data in the format shown in the sample
 bellow.
 How can I parse it to get following:
 (14,trigger,guard,do_action,15)
 
 Thanks a lot for your postings
 Petr Jakes
 
 type:
 4
 bgrColor:
 255 255 255
 fgrColor:
 0 0 0
 objId:
 16
 Num.Pts:
 2
 177 104
 350 134
 objStartId:
 14
 objEndId:
 15
 eventName:
 trigger
 eventCond:
 guard
 eventAction:
 do_action
 
 
 


Create a dictionary mapping the properties to their values, then print
out the ones you require:

fid = open('xxx', 'r')
lines = fid.readlines()
fid.close()

i = 0
items = {}
for line in lines:
line = line.strip()
if line[-1] == ':':
line = line.split(':')[0]
items[line] = lines[i+1].strip()
i = i + 1
outString = '(' +  items.get('objStartId') + ',' +
items.get('eventName') + ',' + items.get('eventCond') + ',' +
items.get('eventAction') + ',' + items.get('objEndId') + ')\n'

print outString



This code yields the following output:

(14,trigger,guard,do_action,15)

Regards,

John McMonagle



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

-- 
http://mail.python.org/mailman/listinfo/python-list