Re: [Tutor] Tix NoteBook programming problem

2004-12-21 Thread Michael Lange
On Tue, 21 Dec 2004 14:16:56 +0900
Guillermo Fernandez Castellanos <[EMAIL PROTECTED]> wrote:

Hi Guille,

thats a classic case of geometry manager conflicts.
You dont need to pack the notebook pages explicitely, tix does this
automagically for you and *tix does not use pack()*, so when
you try to pack() the pages with

> hd.pack()
> gf.pack()

tix doesnt know what to do; by the way, instead of writing

> nb.add('hd',label="hard disk",underline=0)
> hd = nb.subwidget('hd')

you can simply do:

hd = nb.add('hd',label="hard disk",underline=0)

I hope this helps

Michael
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Tix Select programming problem

2004-12-22 Thread Michael Lange
On Wed, 22 Dec 2004 11:37:57 +0900
Guillermo Fernandez Castellanos <[EMAIL PROTECTED]> wrote:

Hi Guille,

> 
> I'm playing now with the Select buttons:
> 
> import Tix
> 
> def prtS():
> print fruits.cget('value')
> 
> def prtC(val):
> print val
> print sel.cget('value')
> 
> root = Tix.Tk()
> fruits=Tix.Select(root,label="Fruits:", orientation='horizontal')
> fruits.add('orange',text="Orange",width=6,command=prtS)
> fruits.add('lemon',text="Lemon",width=6,command=prtS)
> fruits.add('apple',text="Apple",width=6,command=prtS)
> fruits.pack()
> 
> sel=Tix.Control(root, label="X Coordinates", max=10, min=3,
> integer=True,command=prtC)
> sel.pack()
> 
> root.mainloop()
> 

The "command" option should be assigned to the Select widget itself, not to the 
added buttons.
It takes two arguments then (from the tixSelect man page):

   Command-Line Name:-command
   Database Name:  command
   Database Class: Command

  Specifies the TCL command to be executed when the -value of  the
  Select  widget is changed. This command will be invoked with two
  arguments. The first is the name of the  button  subwidget  that
  has  toggled.  The  second is a boolean value indicating whether
  the button subwidget is selected. This command is executed  only
  when the -disableCallback option is set to false.

So I changed your code a little to make it work:

import Tix

def prtS(*args):
print args
print fruits.cget('value')

def prtC(val):
print val
print sel.cget('value')

root = Tix.Tk()
fruits=Tix.Select(root,label="Fruits:", orientation='horizontal',command=prtS)
fruits.add('orange',text="Orange",width=6)
fruits.add('lemon',text="Lemon",width=6)
fruits.add('apple',text="Apple",width=6)
fruits.pack()

sel=Tix.Control(root, label="X Coordinates", max=10, min=3,
integer=True,command=prtC)
sel.pack()

root.mainloop()

Hope this helped

Michael
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] O.T.

2004-12-31 Thread Michael Lange
> * Jacob S. <[EMAIL PROTECTED]> [041228 01:42]:
> > But who are you all, what are you're ages, what do you do, marriage status,
> > etc?

37, no kids but a girlfriend with a cat. I work at a clinical laboratory in a 
hospital in germany.
I'm just a hobby programmer and started with python about 2 years ago; I chose 
python as my first
(and yet only) language because I happened to find a cheap german version of 
Ivan van Laningham's
"Teach yourself python in 24 hours" in a local bookstore when I was looking for 
something to
start with. The book had a sticker on it that said something like "No 
programming knowledge required!"
which looked very promising to me back then.

A happy new year to all of you

Michael 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tix and Table printing

2005-01-14 Thread Michael Lange
On Fri, 14 Jan 2005 08:47:49 -
"Alan Gauld" <[EMAIL PROTECTED]> wrote:


>  Tk was written in the 80's so given 
> its origins was not likely to have a table. 
> 
> Of course it would be nice if they added one now!!!
> 

It looks like they are already working on it: 

http://wiki.tcl.tk/12753

Regards

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter questions

2005-02-02 Thread Michael Lange
On Tue, 1 Feb 2005 19:08:41 +0200
Mark Kels <[EMAIL PROTECTED]> wrote:

Hi Mark,

> Hello,
> I got some Tkinter questions that I need the answer for to complete a
> little project of mine:
> 1. How can I make the program to open in a X*Y sized window ?

from Tkinter import *
root = Tk()
root.geometry('600x400+0+0')

This makes a window of 600x400 pixels placed in the upper left corner of the 
screen (+0+0 is the x- and y- offset;
both of the window size and the offset may be omitted, so you can use '600x400' 
or '+0+0' as arguments for geometry()
as well).

> 2. How can I open another window from the first one (without closing it) ?

Use instances of Toplevel() to create new windows as children of the root 
(Tk()) window.

> 3. How can I add a file browser for my app (like the one you get when
> you press "Save as..." in windows apps) ?

import tkFileDialog
filename = tkFileDialog.asksaveasfilename()
if filename:
# save the file...; if the user presses the 'Cancel' button, filename 
should be set to an empty string.

> 4. How do I configure the font size on the Text widget (its realy
> huge, and I would like to change it to somthing like 12).

text = Text(parent, font=('helvetica', '-12', 'normal'))# "negative" size -> 
pixel size
or:
text.configure(font=('helvetica', '12', 'normal'))# "positive" size -> point 
size

You can use any 3-tuple of the form (family, size, weight) as font descriptor; 
if the requested font is not
found, the widget should fall back to some (probably ugly) default; tk 
guarantees that at least 'times',
'helvetica' and 'courier' font families are available, the availability of 
other fonts depends on your system.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with .get in Tkinter

2005-02-20 Thread Michael Lange
On Sun, 20 Feb 2005 17:12:54 +0200
Mark Kels <[EMAIL PROTECTED]> wrote:

> Hi all.
> First, here is the code I have a problem with (I got same problem in
> my project) :
> from Tkinter import *
> def go():
> e.get()
> print e
> 
> main=Tk()
> e=Entry(main)
> e.pack()
> b=Button(main,text='OK',command=go()).pack()
> main.mainloop()
> 
> For some reason the function is called before I click the button, and
> I get .10037088 before I have done a thing.
> How do I do it right ???
> -- 

Hi Mark,

First problem:

you need to assign the command for the button without parenthesis:

b = Button(main, text='OK', command=go)
b.pack()

I split the line you used into two lines, because pack() returns None , so you 
don't have a reference
to the button once you created it. Of course you can do it the way you did if 
you don't need to reference
the button anymore, however there's not much use in assigning a new variable to 
it, just write:

Button(main,text='OK',command=go()).pack()

Second problem:

your go() function does just what you told it to: it prints the "window name" 
(or however this is called) of
the entry widget. You surely meant something like this:

def go():
contents = e.get()
print contents

or simply:

def go():
print e.get()

I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] UnicodeDecodeError

2005-02-22 Thread Michael Lange
Hello list,

I've encountered an (at least for me) weird error in the project I'm working on 
(see the traceback below).
Unfortunately there are several of my application's modules involved, so I 
cannot post all of my code here.
I hope I can explain in plain words what I'm doing.

The line in the traceback that seems to cause the problems:

if self.nextfile == _('No destination file selected'):

"self.nextfile" is a variable that contains either the path to a file (the 
destination file for sound recording)
or the gettext string you see above.
For some reason I get the error below when "self.nextfile" contains a special 
character *and* the gettext string
holds the german translation, which contains a special character, too (of 
course '\xe4' as 23rd character).
It looks like there are no problems when I remove the german translation or 
when there are no special characters
in the filename, but as soon as I have special characters on both sides of the 
equation the error occurs.

##
Error: 1
UnicodeDecodeError Exception in Tk callback
  Function: > (type: )
  Args: ()
Traceback (innermost last):
  File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line 
1747, in __call__
return apply(self.func, args)
  File "/usr/local/share/phonoripper/snackrecorder.py", line 305, in start
if self.nextfile == _('No destination file selected'):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 22: 
ordinal not in range(128)

##

I've looked into PmwBase.py, but I couldn't figure out what's going on, so I 
hope that someone
here can give me a hint.

Thanks in advance and best regards

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] UnicodeDecodeError

2005-02-23 Thread Michael Lange
On Tue, 22 Feb 2005 19:17:40 -0500
"Isr Gish" <[EMAIL PROTECTED]> wrote:

 
> This part of the error is saying what the problem is.
> 
>>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 22: 
> ordinal not in range(128)
>   
> Thatthe ascii codec that's being used can't decode any ascii code above 128. 
> And the code 0xe4 is higher then that.
> You would have to use a different encoding, like msbc.
> If i remmeber correctly you should do something like the following.
> 
> self.nextfile = self.nextfile.encode('msbc')
> Then it should work.
> 
> If it doesn't work try posting what error you get.
> 
> All the best
> Irr 
> 
> 
Thanks for the reply,

it looks to me however that the problem is rather the gettext part; once I 
discovered this problem
I can produce similar errors at other points in my app that *seem* to only 
occur when a gettext string
gets combined with a string that is returned by user input from some Tkinter 
widget. The final
complaint in the traceback is always about a (german) special character in the 
translated gettext string:

##
UnicodeDecodeError Exception in Tk callback
  Function:  at 0xb72ec304> (type: )
  Args: ()
Traceback (innermost last):
  File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line 
1747, in __call__
return apply(self.func, args)
  File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwDialog.py", line 
153, in 
command=lambda self=self, name=name: self._doCommand(name))
  File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwDialog.py", line 
132, in _doCommand
return command(name)
  File "/usr/local/share/phonoripper-0.6.2/widgets/FileSelectDialog.py", line 
206, in go
if not self.ok():
  File "/usr/local/share/phonoripper-0.6.2/widgets/FileSelectDialog.py", line 
201, in ok
return self.fo_handler.create_ok(self.full_path)
  File "/usr/local/share/phonoripper-0.6.2/FileOperationHandler.py", line 43, 
in create_ok
message=_('File already exists:\n"%s"\nDo you want to overwrite it?') % 
filename)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 19: 
ordinal not in range(128)

##

The german translation of 'File already exists:\n"%s"\nDo you want to overwrite 
it?' contains a special
character ('\xfc'), filename is of course simply the complete path to a file as 
it is returned by a "Save as..."
dialog box. I get this error for some reason if I choose '\xe4.wav' as basename 
for "filename" but not
if I choose 'A\xe4.wav' . Like I said in my first post, there are no errors if 
I remove the german .mo file,
so gettext uses the english strings. 

What seems really weird to me here is that it looks like both the translated 
gettext string and the special
characters in my "filename" variable *can* be decoded, but not both at a time - 
but only under (rare) circumstances
( setting "filename" to "/somepath/A\xe4.wav" works but "/somepath/\xe4.wav" 
not).

I'm really lost here, so any further hints are very appreciated.

Thanks and best regards

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] UnicodeDecodeError

2005-02-23 Thread Michael Lange
On Wed, 23 Feb 2005 07:21:40 -0500
Kent Johnson <[EMAIL PROTECTED]> wrote:

> 
> This is a part of Python that still confuses me. I think what is happening is
> - self.nextfile is a Unicode string sometimes (when it includes special 
> characters)
> - the gettext string is a byte string
> - to compare the two, the byte string is promoted to Unicode by decoding it 
> with the system default 
> encoding, which is generally 'ascii'.
> - the gettext string includes non-ascii characters and the codec raises an 
> exception.
> 
Thanks Kent,

now it looks like the total confusion seems to clear up (at least partially). 
After some googling it
seems to me that the best bet is to use unicode strings exclusively. When I set 
the unicode flag
in gettext.install() to 1 the gettext strings are unicode, however there's 
still a problem with the
user input. As you guessed, "self.nextfile" is unicode only *sometimes*; I 
tried and changed the line
from the old traceback into:

if unicode(self.nextfile, 'iso8859-1') == _('No destination file selected'):

Now when self.nextfile is an existing file "\xe4.wav" that was clicked on in 
the file dialog's file list this works,
however when I type "\xe4.wav" into the file dialog's entry field I get:

TypeError Exception in Tk callback
  Function: > (type: )
  Args: ()
Traceback (innermost last):
  File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line 
1747, in __call__
return apply(self.func, args)
  File "/usr/local/share/phonoripper-0.6.2/snackrecorder.py", line 304, in start
if unicode(self.nextfile, 'iso8859-1') == _('No destination file selected'):
TypeError: decoding Unicode is not supported

At least this might explain why "A\xe4" worked and "\xe4" not as I mentioned in 
a previous post.
Now the problem arises how to determine if self.nextfile is unicode or a byte 
string?
Or maybe even better, make sure that self.nextfile is always a byte string so I 
can safely convert
it to unicode later on. But how to convert unicode user input into byte strings 
when I don't even
know the user's encoding ? I guess this will require some further research.

> I don't know what the best solution is. Two possibilities (substitute your 
> favorite encoding for 
> latin-1):
> - decode the gettext string, e.g.
>if self.nextfile == _('No destination file selected').decode('latin-1'):
> 
> - set your default encoding to latin-1. (This solution is frowned on by the 
> Python-Unicode 
> cognoscenti and it makes your programs non-portable). Do this by creating a 
> file 
> site-packages/sitecustomize.py containing the lines
> import sys
> sys.setdefaultencoding('latin-1')
> 
> Kent
> 

Unfortunately the latter is no option, because I definitely need portability. I 
guess I should probably use
utf-8. 

Thanks and best regards

Michael


> > 
> > ##
> > Error: 1
> > UnicodeDecodeError Exception in Tk callback
> >   Function:  > > (type:  > 'instancemethod'>)
> >   Args: ()
> > Traceback (innermost last):
> >   File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line 
> > 1747, in __call__
> > return apply(self.func, args)
> >   File "/usr/local/share/phonoripper/snackrecorder.py", line 305, in start
> > if self.nextfile == _('No destination file selected'):
> > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 22: 
> > ordinal not in range(128)
> > 
> > ##
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Unicode issues (was: UnicodeDecodeError)

2005-02-24 Thread Michael Lange
On Wed, 23 Feb 2005 23:16:20 -0500
Kent Johnson <[EMAIL PROTECTED]> wrote:

> How about
>n = self.nextfile
>if not isinstance(n, unicode):
>  n = unicode(n, 'iso8859-1')
> ?
> 
> > At least this might explain why "A\xe4" worked and "\xe4" not as I 
> > mentioned in a previous post.
> > Now the problem arises how to determine if self.nextfile is unicode or a 
> > byte string?
> > Or maybe even better, make sure that self.nextfile is always a byte string 
> > so I can safely convert
> > it to unicode later on. But how to convert unicode user input into byte 
> > strings when I don't even
> > know the user's encoding ? I guess this will require some further research.
> 
> Why do you need to convert back to byte strings?
> 
> You can find out the console encoding from sys.stdin and stdout:
>   >>> import sys
>   >>> sys.stdout.encoding
> 'cp437'
>   >>> sys.stdin.encoding
> 'cp437'
> 

I *thought* I would have to convert the user input which might be any encoding 
back into
byte string first (remember, I got heavily confused, because user input was 
sometimes unicode and
sometimes byte string), so I can convert it to "standard" unicode (utf-8) later 
on.
I've added this test to the file selection method, where "result" holds the 
filename the user chose:

if isinstance(result, unicode):
result = result.encode('iso8859-1')
return result

later on self.nextfile is set to "result" .

The idea was, if I could catch the user's encoding, I could do something like:

if isinstance(result, unicode):
result = result.encode(sys.stdin.encoding)
result = unicode(result, 'utf-8')

to avoid problems with unicode objects that have different encodings - or isn't 
this necessary at all ?

I'm sorry if this is a dumb question, but I'm afraid I'm a complete 
encoding-idiot.

Thanks and best regards

Michael




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unicode issues

2005-02-24 Thread Michael Lange
On Thu, 24 Feb 2005 07:51:04 -0500
Kent Johnson <[EMAIL PROTECTED]> wrote:

> Michael Lange wrote:
> > I *thought* I would have to convert the user input which might be any 
> > encoding back into
> > byte string first 
> 
> How are you getting the user input? Is it from the console or from a GUI?
> 

It's a (Tkinter) gui, but anyway, I think I now understand why this idea is 
total nonsense.

> If your intent is to create a unicode string, try this:
>  if not isinstance(result, unicode):
>  result = result.decode(sys.stdin.encoding)
> 
Ok, user input must be checked whether it's unicode or not and if necessary be 
decoded to
unicode with system encoding. For internal operations I should then use only 
unicode strings
and if I need to print something to stdout I must encode it again with system 
encoding, right?

> This article gives a lot of good background:
> http://www.joelonsoftware.com/articles/Unicode.html
> 
> I have written an essay about console encoding issues. At the end there is a 
> collection of links to 
> more general Python and Unicode articles.
> http://www.pycs.net/users/323/stories/14.html
> 
> Kent
> 
That's great! Exactly the kind of articles I've been looking for but couldn't 
find.

Thanks!!!

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Recursive Tkinter buttons

2005-02-25 Thread Michael Lange
On Fri, 25 Feb 2005 20:19:15 +1300
Liam Clarke <[EMAIL PROTECTED]> wrote:

> >
> > for i in range(0,10):
> > print i
> > buttonlabel = "field " +str(i)
> > button[i].append = Button (text=buttonlabel)
> > button[i].grid(column=3, row = i+3)
> > 
> > The current error is:
> > 
> >   File "report.py", line 80, in createWidgets
> > button[i].append = Button (text=buttonlabel)
> > IndexError: list index out of range
> > 
>  button = []
> for i in range(0,10):
>  print i
>  print button[i]
> 
> 
> Will cause the exact same error as button[i].append. Why? button=[],
> it has no index.
> Perhaps you just mean button[i] = Button (text=buttonlabel)?
> 
> Regards,
> 
> 
Or :

buttonlist = []
for i in range(0, 10):
print i
buttonlabel = "field" + str(i)
b = Button(text=buttonlabel)
b.grid(column=3, row=i+3)
buttonlist.append(b)

Remember what you are doing when you call "button[i].append = 
Button(text=buttonlabel)":
button is a list of Tkinter.Button objects, so button[i] is the "i-th" item in 
this list
and that's exactly one more than the list actually contains, so you get an 
IndexError .
However, if this IndexError wouldn't occur, it didn't help much, because you 
would
probably get an AttributeError, saying something like "Tkinter.Button instance 
has no attribute 'append'".
Even without this AttributeError nothing would be won, because the list's 
append() method returns None,
so you would have:  None = Button(text=buttonlabel) which is probably not what 
you intended.

You see, in my example above I called the list "buttonlist" instead of 
"button"; maybe this naming
helps avoid confusion .

Best regards

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Recursive Tkinter buttons

2005-02-27 Thread Michael Lange
On Sat, 26 Feb 2005 19:48:25 +
Adam Cripps <[EMAIL PROTECTED]> wrote:

> On Fri, 25 Feb 2005 12:21:18 +0100, Michael Lange 
> 
> > 
> > You see, in my example above I called the list "buttonlist" instead of 
> > "button"; maybe this naming
> > helps avoid confusion .
> > 
> > Best regards
> > 
> > Michael
> 
> Many thanks for the help here. 
> 
> I got all my buttons displayed and stored in the list with: 
> 
> for i in range (1, 11):
>   submittext = ">>> "
>   self.s = Button(text=submittext, command = 
> self.showButton)
>   self.s.grid(column=4, row=i+4)
>   submitlist.append(self.s)
> 
Hi Adam,

note that there's no use in making the button an attribute of its parent class 
with

self.s = Button(text=submittext, command = self.showButton)

because self.s gets overridden on every iteration in the for-loop; it's not a 
bug, but
might be a source of confusion, when you try to access self.s later in your 
code; you don't
need the reference anyway, because you keep the references to all buttons in 
the list.

> 
>  - however, when I click the button, I want self.showButton to know
> which one of them was pressed. I've seen in other gui programming the
> idea of an id or identifier - I can't see that here. Ideally, I would
> like to know the value of i in self.showButtons - but when I use
> self.showButtons(i) showButtons gets called straight at run time.
> 
> Any ideas? 

You have two options here:

1. use a lambda expression as button command, lambda allows you to pass an 
argument to the callback:

s = Button(text=submittext, command = lambda index=i: 
self.showButton(index))

2. if you don't like lambdas, you can use the button's bind() method instead of 
the command option:

s = Button(text=submittext)
s.bind('', self.showButton)
s.bind('', self.showButton)

bind() passes an event to the callback which allows you to find out which 
widget sent the event via the
event's widget attribute:

def showButton(self, event):
button = event.widget
print button['text']

I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Saving Entry fields in Tkinter

2005-03-01 Thread Michael Lange
On Tue, 1 Mar 2005 12:52:57 +0100
Ewald Ertl <[EMAIL PROTECTED]> wrote:

> Hi!
> 
> Perhaps this could help you: 
> 
> fileContent=open( "my/file/to/read", "r").readlines()
> 
> for line in fileContent:
>   print line.strip()   # remove leading and trailing whitspace's incl. \n
> 
> 
> In the loop you could perhaps populate the entry-widgets. 
> 
> HTH  
> 
> Ewald 

Or use the fileinput module:

var_list = []
for line in fileinput.input(filename):
var = Tkinter.StringVar()
var.set(line)
var_list.append(var)

Best regards

Michael

> 
> on Tue, 1 Mar 2005 09:22:06 +  Adam Cripps <[EMAIL PROTECTED]> wrote :
> -
> 
> Adam Cripps > I'm writing an application which has rows of Entry fields 
> (created in
> Adam Cripps > a loop - see previous thread; and thanks guys!). All the 
> content of
> Adam Cripps > the Entry fields are accessed through self.contentlist[i].get()
> Adam Cripps > 
> Adam Cripps > Now I'm trying to save the content of those fields in a friendly
> Adam Cripps > format. I've used pickle in the past, but experienced problems 
> with
> Adam Cripps > pickling Tkinter widgets.
> Adam Cripps > 
> Adam Cripps > I'm saving using this method :- 
> Adam Cripps > 
> Adam Cripps > for i in self.contentlist:
> Adam Cripps > saving = i.get() + "\n"
> Adam Cripps > f.write(saving)
> Adam Cripps > f.close()
> Adam Cripps > 
> Adam Cripps > which creates a text file with each entry field separated with 
> a "\n". 
> Adam Cripps > 
> Adam Cripps > What would be a good way to open this file and re-populate the 
> entry
> Adam Cripps > fields with the content?  I'm not sure how to parse the text 
> according
> Adam Cripps > to the \n separator.
> Adam Cripps > 
> Adam Cripps > Am I going down the right path here? 
> Adam Cripps > 
> Adam Cripps > TIA
> Adam Cripps > Adam
> 
> 
> --- end --
> 
> 
> -- 
> Ing. Ewald Ertl HartterGruppe   Phone : 
> +43-3352-33085-558
> trinomic Projektmanagement & Informationstechnik GmbH   Fax   : 
> +43-3352-33085-600
> Wiener Straße 41mailto:[EMAIL 
> PROTECTED]
> A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL 
> PROTECTED]
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help

2005-03-07 Thread Michael Lange
On Mon, 07 Mar 2005 11:46:42 -0500
Kent Johnson <[EMAIL PROTECTED]> wrote:

> Gregory Sexton wrote:
> > Thanks for the help! Sorry for the trivial questions, but I guess we all 
> > have to start somewhere.  Beginning python student, OS Windows XP,using 
> > Python 2.4.  Also novice to programming.  I cant get the "/a" command to 
> > work.  
> 
> I don't know what the "/a" command is, please give more details.
> 
> I get an elongated 0 in my Python interpreter, but no sound.
> 

Sound? Maybe you meant 

print "\a"

?

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Using signal handlers

2005-03-08 Thread Michael Lange
Hello tutors,

I experience problems with signal handlers, and the explanatzions in the docs 
don't
seem to help me much.

The code I try to handle basically comes down to this (it's supposed to run on 
linux only, btw):

from Tkinter import *
import tkSnack

root = Tk()
tkSnack.initializeSnack(root)
root.mainloop()

initializeSnack() tries to access the sound device, however if this fails it 
tries forever and doesn't return.
I *thought* a signal handler might be what I need, and in fact it partially 
works, at least
initializeSnack() is stopped when I add this:

from Tkinter import *
import tkSnack, signal

root = Tk()
signal.signal(signal.SIGALRM, signal.getsignal(signal.SIGALRM))
signal.alarm(5)
tkSnack.initializeSnack(root)
signal.alarm(0)
root.mainloop()

Now when the audio device is busy, after 5 seconds the app prints "Alarm clock" 
and exits.
However I would prefer to have a more controlled exit, but as soon as I define 
a custom
signal handler it's the same as before - it never gets called.

Any help is much appreciated

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing Keyboard output

2005-03-20 Thread Michael Lange
On Sun, 20 Mar 2005 19:38:40 -
"Igor Riabtchuk" <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> I am totally new to Python and still learning.
> 
> I am looking for a way to change keyboard output within Tkinter widget - for 
> example, say I press "p" and I want it to come out as "t".
> 
> Could anyone possibly point me in the right direction?
> 
> Igor 

You can use the widget's bind() method to replace the standard callback with a 
new one:

from Tkinter import *
root = Tk()
e = Entry(r)
e.pack()

def PtoT(event):
e.insert('insert', 't')
return 'break'

e.bind('', PtoT)

the "return 'break'" statement prevents the event from being propagated to Tk's 
standard event handler;
without it both "p" and "t" would be inserted into the Entry.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter and keyboard output

2005-03-25 Thread Michael Lange
On Thu, 24 Mar 2005 18:05:25 -
"Igor Riabtchuk" <[EMAIL PROTECTED]> wrote:

> Hi, 
> 
> I was playing around with Tkinter bindings and I got a question which is 
> probably not particularly bright.
> 
> If I have the following code, it works because I specifically code a function 
> for  keypress:
> 
> from Tkinter import *
> 
> class CRED(Frame):
> def __init__(self):
> Frame.__init__(self)
> self.txt=Text(self)
> self.txt.bind('', self.conv)
> self.txt.pack()
> self.pack()
> self.txt.focus()
> 
> def conv(self,event):
> self.txt.insert(END,'t')
> return 'break'
> 
> app=CRED()
> app.mainloop()
> 
> What if instead of coding , I coded   - how would I implement 
> the function which would allow the code to determine which 'Key' was pressed 
> after Alt?
> 
> Thank you.
> Igor

Do you mean something like this:

>>> from Tkinter import *
>>> r=Tk()
>>> t=Text(r)
>>> t.pack()
>>> 
>>> def  test(event):
... print event.keysym
... 
>>> t.bind('', test)
'1077686180test'
>>> x # Alt-x was pressed

?

Michael


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] wxPython / Tkinter Grid

2005-04-01 Thread Michael Lange
On Fri, 1 Apr 2005 09:11:20 +0100
"Alan Gauld" <[EMAIL PROTECTED]> wrote:

> > I know a wxPython grid is totally different to a Tkinter grid, but
> is
> > there a Tkinter equivalent of a wxPython grid? I'm finding wxPython
> to
> > be fiddly and restrictive...
> 
> Then Tkinter will be more so. Tk is a fairly basic toolkit, fine for
> wrapping a command line app in a glossy front end but not for
> sophisticated GUI work.
> 
> There is no grid component in Tk out of the box, but some add on
> toolkits
> supply one. Try searching on the Vaults of Parnassus or on the
> ActiveState site if you are determined to try Tkinter...
> 
> Alan G.
> 

Or look here:

http://tkinter.unpythonic.net/wiki/Widgets

There is a number of links to table widget implementations in Tkinter o nthe 
wiki page.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] using the enter key

2005-04-05 Thread Michael Lange
On Tue, 5 Apr 2005 06:28:54 +1000
"Diana Hawksworth" <[EMAIL PROTECTED]> wrote:

> Hello list!
> 
> At the moment I have some user input tied to a button that allows the input 
> to be "submitted" and then an answer is supplied.  How can I get rid of this 
> submit button, and have the user just press the "enter" key and have the same 
> result happen?
> 
> TIA.  Diana

You need to create an event handler for the Entry widget that is called each 
time the Enter key is pressed over the widget:

entry.bind('', submit)

where "entry" is of course your Entry widget and "submit" the function to be 
called.

Please note that the "enter" key's event descriptor is "''" in Tk 
(there's an '' event, too, which is when the mouse
pointer enters the widget) and that the callback gets an event instance passed, 
so the function definition
has to look like this:

def submit(event):
(...)

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] using the enter key

2005-04-07 Thread Michael Lange
On Thu, 07 Apr 2005 10:06:46 +1000
"Nova Nova" <[EMAIL PROTECTED]> wrote:

>   def create_widgets(self):
>self.a_lbl=Label(self,text="",fg="Red")
>self.a_lbl.grid(row=0,column=0,columnspan=2,sticky=W)
>self.inst_lbl=Label(self,text="Enter A Number Between 1 and 
> 100.",fg="blue")
>self.inst_lbl.grid(row=1,column=0,columnspan=2,sticky=W)
>self.pw_lbl=Label(self,text="Number: ")
>self.pw_lbl.grid(row=2,column=0,sticky=W)
>self.pw_ent=Entry(self)
>self.pw_ent.grid(row=2,column=1,sticky=W)
>self.submit_bttn=Button(self,text=str(self.g)+" Turns  
> Left",command=self.reveal,fg="red",bg="black")
>self.submit_bttn.grid(row=3,column=0,sticky=W)
>self.win_txt=Text(self,width=35,height=5,wrap=WORD)
>self.win_txt.grid(row=4,column=0,columnspan=2,sticky=W)
> 
> 
>   def submit(self):
>self.reveal
>entry.bind('',self.submit)
> 
> this is what im doing and i get an error, IT DOES NOT WORK
> 

The problematic part is your submit() method:

def submit(self):
self.reveal# you forgot the parentheses here to call your reveal() 
method
   ^^  
entry.bind('',self.submit)

this only binds the event handler to the Entry when the submit button was 
pressed before;
you better apply this binding in your create_widgets() method immediately after 
creating the Entry
widget. Please note that if you want to use the submit() method both as 
button-command and as
event handler for the entry, it needs an optional event instance as argument:

def submit(self, event=None):
(...)

because the button's "command" doesn't pass an event to the callback, but the 
entry's event handler does.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Entry widgets

2005-04-10 Thread Michael Lange
On Sun, 10 Apr 2005 18:07:48 +1000
"Diana Hawksworth" <[EMAIL PROTECTED]> wrote:

> Hello list,
> 
> Is it possible to change the width of an Entry widget - or not?  I am using 
> Tkinter, GUI - and have an Entry widget that accepts a number. I just don't 
> want it to extend the width of the column.  I have tried width =  - but get 
> an error.
> 

You should be able to use the width option as for any other widget:

e = Entry(parent, width=5)
or
e.configure(width=5)

What exactly did you write, and what was the error? 


> Maybe a text widget would be preferable?
> 

If you just want one line to enter a number, I don't think so.

> Also - how do I set the insertion symbol there already, so I don't need to 
> click there to enter the number?
> 

You can use focus_set():

e = Entry(parent)
e.focus_set()

> TIA. Diana

I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problems with encodings

2005-04-18 Thread Michael Lange
On Mon, 18 Apr 2005 09:22:28 +0300
Olli Rajala <[EMAIL PROTECTED]> wrote:

> Hi!
> Been offlist for a while, but now I started to code an administration
> tool for my own photo gallery and have some troubles, so thought to
> write and ask some help. :)
> 
> So, I'm from Finland and I'm using ISO-8859-15 -encoding but Python
> don't "understand" letters outside ASCII. I've read PEP-0263 and tried
> to add the encoding line to my sources, but it doesn't help. Here's a
> little example:
> 
> #!/usr/bin/python2.4
> # -*- coding:  -*- 
> def printHeader():
> print ""   
> 
> Don't know how you see the 4th line, but that's not my "problem", is it? ;)
> 
> And I got this error message:
> "sys:1: DeprecationWarning: Non-ASCII character '\xe4' in file
> generalHtml.py on line 11, but no encoding declared; see
> http://www.python.org/peps/pep-0263.html for details"
> 
> I code with Kate (2.4, KDE 3.4.0) and everything else works well when
> speaking about this encoding thing. I really hope that someone would
> know a solution. I don't mind if I have to write only ASCII but I'm
> not the only user for that tool, so...
> 

Hi Olli,

does it help if you change the second line into:

# -*- coding: iso-8859-15 -*-

?

I *think* that is the correct syntax (at least it works for me).

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] TKinter and things over Linux

2005-04-18 Thread Michael Lange
On Mon, 18 Apr 2005 13:24:03 +
"Alberto Troiano" <[EMAIL PROTECTED]> wrote:

Hi Alberto,

> Hey
> Let me know if this format is better (I use Hotmail in the web so...)
> 

Looks pretty much ok to me :-)

> Sadly I'm not in the linux machine so I can't run the command you sent me 
> but I shall explain the version just so you know
> 
> The fullname version is Red Hat Advanced Server 3.0. This is a commercial 
> version of Linux
> But it has so many problems and so few documentation that I switched to Red 
> Hat 9.0 (I think that you're familiar with this version)
> 
> I have installed tcl and tk support and I will download and install the 
> anthony's RPMs
> What can I do to make Tkinter work on Linux Red Hat 9.0??
> 

First you should make sure that all necessary RPMs are installed; the basic 
python
RPM will be installed by default on RedHat 9 but probably not Tkinter ( I'm not 
sure
how the RPM is called on RedHat, maybe python-tkinter or python-tk or tkinter 
or... ).

Best regards

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] using TK to view an image and then close the window

2005-04-25 Thread Michael Lange
On Mon, 25 Apr 2005 10:24:08 -0700
"Ertl, John" <[EMAIL PROTECTED]> wrote:


Hi John,

> I can get the image to show
> up and minimize and maximize but I can not get the window to close and then
> display the next image.  
> 
> I have tired several things but no luck. 
> 
> Any help on getting the TK window to shutdown cleanly would be appreciated.
> Thanks
> 
> John Ertl 
> 
>  # this is supposed to display an image in a TK window but the close
> (X) does not work.
> import Image
> import Tkinter,ImageTk
> 
> def TKview(img,mainTitle="image"):
> 
> app = Tkinter.Tk()
> app.withdraw()
> 
> top = Tkinter.Toplevel(app,visual="truecolor",colormap="new")
> top.title(mainTitle)
> top.protocol("WM_DELETE_WINDOW", quit)
> top.bind("",quit)
> top.bind("",quit)
> 
> canvas = Tkinter.Canvas(top)
> canvas.pack()
> 
> p = ImageTk.PhotoImage(img)
> 
> canvas['width'] = img.size[0]
> canvas['height'] = img.size[1]
> 
> canvas.create_image(0,0,anchor='nw',image=p)
> 
> top.mainloop()
> 
> def quit(event=None):
> top.destroy()
> top.quit()
> 

If that's all of the code, "top" is created as a local variable inside your 
TKview() function,
so your quit() function doesn't know about it.
Second, I don't see much use for using a second Toplevel window at all, why not 
just pack the
canvas onto the main Tk() window?


> 
> # this code gets the images opens them and calls the TK code above to
> display them
> 
> import glob
> import thread
> import Image
> 
> import TKviewTest # the module to view the images
> 
>
> gifList = glob.glob("./*.gif")
> print gifList
> for image in gifList:
>image = image[2:] # glob leaves ./ in file name
> 
>newIm= Image.open(image)
> 
>TK = TKviewTest
>thread.start_new_thread(TK.TKview(newIm,mainTitle="image"))
> 
> 

I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Tkinter and Animation

2005-04-27 Thread Michael Lange
On Wed, 27 Apr 2005 09:35:47 -0700
Jeremiah Rushton <[EMAIL PROTECTED]> wrote:

> 
> I wanted them to visually shrink and visually move to a corner on the frame. 
> I did not know how to do it the way you explained, thanks for that. But is 
> there any way to do it visually?
> 

I guess so, if you use the "place" geometry manager. With place() you can 
determine
things like x- and y-coordinates on the parent widget and relative width / 
height,
so if you start a loop that moves the button 2 pixels up and one pixel to the 
left
every 50ms for example it might come close to the kind of animation you want.
It's probably tricky, but I think it's possible.

Best regards

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter and Animation

2005-05-02 Thread Michael Lange
On Wed, 27 Apr 2005 19:31:06 -0700
Jeremiah Rushton <[EMAIL PROTECTED]> wrote:

> 
> I tried your idea and it doesn't animate it. I made a for loop and told it 
> to mover 1 pixel downward every .3 seconds for 25 times. It just waits till 
> the for loop is completed and then displays the result of the loop ending. I 
> also tried it without the for loop by writing each one of the steps out 
> repetively and I had the same result. The only thing that has kind of got 
> close to the visual is that I wrote a program that everytime the user 
> clicked the button it moved down one pixel, but I want it to move 100 
> pixels, one by one, with only one click from the user. Here's the code that 
> I wrote:
> 
> from Tkinter import *
> from time import sleep
> 
> class Main:
> 
> def __init__(self,master):
> button = Button(master,text='button')
> button.place(x=1,y=1)
> y=3
> for x in range(1,25):
> sleep(.3)
> button.place_forget()
> button.place(x=1,y=y)
> y+=2
> 
> 
> root = Tk()
> Main(root)
> root.title('test')
> root.mainloop()
> 
> Thanks for all the help so far.
> 
> Jeremiah
> 

Hi Jeremiah,

you should call update_idletasks() to make the changed geometry visible. I've 
written a (very quick and dirty)
demo that shows how to animate a Label with place() :

###

from Tkinter import *

class AnimatedFrame(Frame):
def __init__(self, master, **kw):
Frame.__init__(self, master, **kw)
self.labelx = 100
self.labely = 100
self.label = Label(self, text='Look at me!')
self.label.place(x=self.labelx, y=self.labely)
self.button = Button(self, text='Start', command=self.start)
self.button.place(x=100, y=200)

def start(self):
if self.labelx > 20:
self.labelx -= 1
self.labely -= 1
self.label.place(x=self.labelx, y=self.labely)
self.update_idletasks()
self.start()

def test():
root = Tk()
f = AnimatedFrame(root, width=300, height=300)
f.pack()
root.mainloop()

if __name__ == '__main__':
test()

#

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help me on python + snack

2005-05-18 Thread Michael Lange
On Tue, 17 May 2005 21:18:09 -0700 (PDT)
Mahmad Sadique Hannure <[EMAIL PROTECTED]> wrote:

Hi Mahmad,

> Hello friends,
> I m currently working on sound stuff. I have installed
> all stuff related to Snack. My code for playing mp3
> song is like this
> 
> #!/usr/bin/python2.3
> 
> from Tkinter import *
> import tkSnack
> 
> def main():
>   root = Tk()
>   tkSnack.initializeSnack(root)
>   mysound = tkSnack.Sound('xyz.mp3')

I believe the last line is the problematic one.
Try to change it into:

mysound = tkSnack.Sound(file='xyz.mp3')

>   #mysound.read()
>   mysound.play()
> if __name__=='__main__':
>   main()
> I works fine without any error but can't get any
> sound.
> 
> So friend help me, I don't know whats wroung with my
> code.
> 

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] finding path to resource files in a GUI application

2005-06-09 Thread Michael Lange
On Thu, 9 Jun 2005 08:52:59 +0200
Christian Meesters <[EMAIL PROTECTED]> wrote:

> Hi
> 
> Currently I'm writing a GUI application with wxPython (on OS X, but I  
> guess the problem is the same, regardless of the UNIX derivative one is  
> using). When I start the main script where it is located the  
> application finds all resource files (non-Python files like images and  
> html files for html windows) without any problem. However, if a put a  
> link in /usr/local/bin and start the script using the link the  
> application cannot find those resource files - unless, of course, I  
> will use full absolute paths to point to those files. One brief example  
> to illustrate the problem:
> 
> The class Goals is in a file called Help.py, located in '/gui_lib/' as  
> seen from my main script.
> 
> class Goals(wx.Frame):
>   def __init__(self,parent,frame,title,size,pos=wx.DefaultPosition):
>   wx.Frame.__init__(self,parent, 
> -1,title,size,style=wx.DEFAULT_FRAME_STYLE)
>   self.frame = frame
>   self.cwd = os.getcwd()  
>   
>   self.html = HtmlWindow(self,-1)
>   self.html.LoadPage(os.path.join(self.cwd,'gui_lib/Goals.html')) 
>  
> #this, of course, won't work
>   #if the main script is called from somewhere else and not the  
> directory where the main script
>   #is located
> 
> Any ideas what I could use instead of os.getcwd to construct a relative  
> path which will work even if I port the script to an other machine?
> 
> Cheers
> Christian
> 

Hi Christian,

try

self.cwd = os.path.abspath(sys.path[0])

sys.path[0] is the directory of your main program file, with os.path.abspath() 
you can
get rid of the "../../" stuff at the beginning of the path if the program is 
called from a link.

I hope this helps

Michael


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Buttons automatically executing

2005-06-15 Thread Michael Lange
On Wed, 15 Jun 2005 14:31:55 -0500
Phillip Hart <[EMAIL PROTECTED]> wrote:


Hi Phillip,

> #!usr/bin/python
> 
> from Tkinter import *
> 
> def location(x,y):
> print "I am in row ",x," and column ",y
> 
> 
> root=Tk()
> root.geometry('300x300')
> can=Canvas(root,width=250, height=250)
> 
> bimage=PhotoImage(file='sq1.gif')
> 
> b1=Button(can,bg="black",image=bimage,command=location(0,0)).grid(row=0,column=0)

That's an error which frequently happens to Tkinter beginners.
When you assign the button's command like this the command is executed 
immediately
after button creation, the correct usage is:

b1 = Button(can, command=location)

without the parentheses; however if you need to pass arguments to the callback,
you can use a lambda expression like this:

b1 = Button(can, command = lambda x=0, y=0 : location(x, y))

Another problem in this line that doesn't matter here, but might cause 
confusion later on
is the use of grid() ; note that grid() returns None, so actually you set your 
variable
b1 to None which is probably not what you intended; if you need to keep a 
reference to
the Button object you need to split the above into two statements:

b1 = Button(can, )
b1.grid()

If you don't need a reference you can simply do:

Button(can,).grid(row=0,column=0)

without creating a (quite useless) variable.

I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Process problem

2005-06-16 Thread Michael Lange
On Wed, 15 Jun 2005 22:04:48 +
"Alberto Troiano" <[EMAIL PROTECTED]> wrote:

Hi Alberto,

> Hey
> 
> Let me make you understand
> 
> I need that levantamuertos.py run cotascamon.py (every script with it 
> differents arguments that are passed) and then die letting the cotascamon.py 
> scripts running independently
> 
> Now, I don't know if my code is right, and thinking now you're right, 
> levantamuertos.py waits until cotascamon.py finish.
> What can I do since cotascamon will never die (and it doesn't have to die)?
> 
> Maybe a different approach will be the solution but I can't find a way to do 
> it
> 
> Best Regards
> 
> Alberto
> 

I didn't follow the thread completely, so maybe I missed something, but if the 
problem
is that python waits until the os.system() calls are finished, I think adding a 
"&" to
the command to make it run in the background should do the trick.

Best regards

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Adding attributes to imported class

2005-07-06 Thread Michael Lange
Hello list,

I'm trying to write a python wrapper for the tkDnD Tk extension to add drag and 
drop support
to Tkinter. Looking for a way to give all widgets access to the newly defined 
dnd methods
I came to create a subclass of Tkinter.Tk() and pass the dnd methods to 
Tkinter.BaseWidget() 
(all Tkinter widgets except Tk() inherit from BaseWidget()), like this:

## file TkinterDnD.py  #

import Tkinter

class Tk(Tkinter.Tk):
def __init__(self, *args, **kw):
Tkinter.Tk.__init__(self, *args, **kw)
self.tk.eval('package require tkdnd')

def dnd_clearsource(self):
'''Unregister widget as drag source.'''
return self.tk.call('dnd', 'clearsource', self)
Tkinter.BaseWidget.dnd_clearsource = dnd_clearsource

< etc. >

###

This is nice, because now I can simply do:

from Tkinter import *
import TkinterDnD

root = TkinterDnD.Tk()

to magically add dnd methods to all Tkinter widgets.

However, I can't help that this trick somehow reminds me of a do-it-yourself 
lobotomy,
so now my question, is this a common way to add new attributes to existing 
classes
or is it possible that this causes problems that I don't see at the moment?

Thanks in advance

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding attributes to imported class

2005-07-07 Thread Michael Lange
On Thu, 07 Jul 2005 11:03:00 +1200 (NZST)
[EMAIL PROTECTED] wrote:

> Quoting Michael Lange <[EMAIL PROTECTED]>:
> 
> > I'm trying to write a python wrapper for the tkDnD Tk extension to add
> > drag and drop support
> 
> Hi Michael,
> 
> Just a side issue --- tkDnD seems to be broken in python 2.4: see bug 1164742,
> http://sourceforge.net/tracker/index.php?func=detail&aid=1164742&group_id=5470&atid=105470
> 
> -- 

Hi John,

thanks for the pointer , but of course I did not mean the python module but the 
Tk extension library
( http://sourceforge.net/projects/tkdnd ), which adds "real" dnd support to Tk.

As far as I have tested (not very much however) it seems to work now, but I'm 
still not sure if the on-the-fly adding of attributes
to classes of an imported module is proper programming style or "do-it-yourself 
lobotomy" .
It is the first time for me to try wrapping a Tk extension for python, so I am 
not sure of the way to go.

Anyway, it's a cool new feature for Tkinter, so I thought I should share it 
with the community;
anyone who is interested can find it at 
http://www.8ung.at/klappnase/TkinterDnD/TkinterDnD.html .

Any feedback is much appreciated.

Best regards

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter Q's

2005-07-12 Thread Michael Lange
On Mon, 11 Jul 2005 17:22:57 +
Joseph Quigley <[EMAIL PROTECTED]> wrote:

Hi, Joseph,


> Hi first off, here's my code:
> 
> # -*- coding: utf-8 -*-
> from Tkinter import *
> import random
> import time
> import about
> import quotes
> 
> 
> def closeprog():
> raise SystemExit
> 
> class main:
> root = Tk()
> frame = Frame()
> root.title("Quoter %s" % (about.ver))
> root.minsize(300, 50)
> 
> showquote = Label(root, text=random.choice(quotes.quote))
> showquote.pack()
> 
> exit = Button(root, text="Exit", command=closeprog)
> exit.pack(side=LEFT)
> 
> aboutprg = Button(root, text="About", command=about.main)
> aboutprg.pack(side=LEFT)
> 
> 
> totalq = Label(root, text=quotes.qts)
> totalq.pack(side=BOTTOM)
>
> root.mainloop()
> 
> (I'd appreciate some suggestions, or notifications on how bad something is)
> 

I think you should change the way you define the main class, so you keep 
references to the class attributes;
it looks like your main class fires up a Tk() window, so it's probably best to 
subclass Tk() :

class Main(Tk):# this doesn't really matter, but upper case letters are 
generally preferrred for class names

def __init__(self, *args, **kw):
Tk.__init__(self, *args, **kw)
# at this point the Main() class practically is a Tk(), so it can be 
handled just like a regular
# Tk() window from the outside; the "*args, **kw" construct allows to 
pass an arbitrary amount of
# arguments and keyword arguments to the parent class. "self" is a 
placeholder for the class instance
# that will be actually used in the code.
# To get a benefit over a normal Tk() window you can now start adding 
attributes:
self.showquote = Label(self, text=random.choice(quotes.quote))
self.showquote.pack()
< etc. >
# of course you can use the parent classes methods on "self", too:
self.title("Quoter %s" % (about.ver))
self.minsize(300, 50)
# now you can add a button which uses a "class-specific" command:
self.switchbutton = Button, text="Switch quote", 
command=self.switch_quote)
self.switchbutton.pack()
# finally the class method has to be defined:

def switch_quote(self):
newquote = get_the_new_quote()# it's up to you how to do this of course
self.showquote.configure(text=newquote)

Now the Main() class can be used like a regular Tk() :

root = Main()
root.mainloop()

And for something completely different:
be careful mixing pack(side = LEFT / RIGHT) with pack(side = BOTTOM / TOP),
you might not get the results you expected. For complex layouts you are 
probably better off
using grid() ( or you will find that you have to use extra Frames to pack() 
your widgets in.

I hope this helps

Michael

> I have a small problem: I don't know how to make a button that would 
> redisplay another quote in the same window, ie I need a button that 
> says: Show Another Quote. (Actually I don't know how to make it show 
> another quote even in a new window!!). I got the interface from Catfood 
> Fortune Cookie.
> 




> Here's a tid-bit of the quotes module:
>  # Brian Kernighan
> bk1 = """Controlling complexity is the essence of computer programming.
> 
> -- Brian Kernighan"""
> 
> yadayada = """Foo/bar"""
> 
> quote = [bk1, yadayada]
> 
> Thanks,
> Joe
> 
> -- 
> Unix Love, Linux Pride
> 
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter Q's

2005-07-13 Thread Michael Lange
On Wed, 13 Jul 2005 08:13:42 +
Joseph Quigley <[EMAIL PROTECTED]> wrote:

> Hi, 
>   what's the **kw stand for, used for? What does it mean?
> 

**kw means that there is an optional list of keyword arguments that you can 
pass to __init__
(for example: main = Main(background="black") ). Keyword, because there is 
defined set of keywords that may be used.

> > Here's what I would do:
> >
> > class Main(Frame):
> >def __init__(self, master=None, **kw):
> >Frame.__init__(self, master, **kw)
> >
> >showquote = Label(self, text=random.choice(quotes.quote))
> >showquote.pack()
> >
> ># etc
> >
> > if __name__ == '__main__':
> >root = Tk()
> >main = Main(root)
> >main.pack(fill=BOTH, expand=True)
> >root.mainloop()
> > ###
> >
> > Do you see what I am doing there, and why it is different from your 
> > approach?
> Uh, not really, no. I'm very new to GUI. So you're saying that If I make the 
> class actually do something (I edited and example in:
> An into to Tkinter, Fredrik Lundh).

O.k., let's try it in more detail

class Main(Frame):
def __init__(self, master=None, **kw):
Frame.__init__(self, master, **kw)

This defines a new class "Main"; the construct "Main(Frame)" means that "Main" 
is a subclass of Frame
and so inherits all methods and other attributes of a Frame (like pack(), 
configure() and so on).
The second line defines the classes __init__() method, which is called 
everytime you create a new instance of
the Main class with e.g. " main = Main() ". There are three arguments passed to 
__init__() : "self" is the first,
because everytime you call a class method, the first argument that is passed to 
the call is the class instance
that does the call, e.g if you do " root.mainloop() ", the mainloop() method 
gets called with your root window
as first argument. You actually don't need to call this variable "self", you 
could as well call it "joe", but
everyone uses "self", and this makes sense, because it points to what is meant.
The third line now is the first thing __init__() does: it calls the Frame's 
__init__()
and passes "self" as first argument to it, so now actually when you do:

main = Main()

your variable "main" is set to what your __init__() method returns and this is 
at this point nothing else
as that what Frame.__init__() returns - a newly created Frame instance. You 
see, all arguments
that are passed to __init__() are passed to Frame.__init__(), so after these 
three lines
The "Main" class is nothing more (or less) than a Frame.

I hope this made sense so far.
Now you are ready to add some useful features to your class, to make it "more" 
than a standard Frame;
e.g. start with adding some widgets and one new class method:

class Main(Frame):
def __init__(self, master=None, **kw):
Frame.__init__(self, master, **kw)
self.label = Label(self, text="Hello")
self.label.pack()
self.button = Button(self, text="Change quote", 
command=self.change_quote)
self.button.pack()

def change_quote(self):
if self.label['text'] == "Hello":
self.label.configure(text="World")
else:
self.label.configure(text="Hello")

You see, we added a Button and a Label to the Frame. As first argument we 
passed "self" to the widgets,
which, you remember, is a Frame instance; by calling the variable "self.label" 
instead of just "label" however you did some more:
you added a new attribute to the Frame instance. the advantage is that you now 
can access the label from the outside:

  root = Tk()
  main = Main(root)
  main.pack()
  main.label.configure(text="Foo")
  root.mainloop()

changes the Label's text.

The last thing is that you defined a new class method for the "Main" class: 
change_quote()
You see, change_quote() is defined *outside* of __init__() (note the 
indentation level), 
so it becomes another class attribute, just as __init__() itself and all the 
methods inherited from Frame.
You can try:

  root = Tk()
  main = Main(root)
  main.pack()
  root.after(3000, main.change_quote)
  root.mainloop()

Here when you call "main.change_quote" the class instance is passed as first 
argument to the method,
that's why you have to pass "self" as argument in the class method definition, 
basically the same as with __init__(),
and that's why you have to use "self.change_quote" as command for the button.

I hope this still made sense.


> >def changeQuote():
> >currQuote = showquote.cget('config')  # Get the current quote
> >newQuote = random.choice(quotes.quote)
> >while newQuote == currQuote:  # Make sure the new quote 
> > differs
> >newQuote = random.choice(quotes.quote)
> >showquote.config(text=newQuote)
> >Button(self, text='Show another quote', command=changeQuote).pack()
> 
> Aaag. I'm confused... I just tried you changeQuote example with out t

Re: [Tutor] Tk -- which label clicked

2005-07-15 Thread Michael Lange
On Fri, 15 Jul 2005 10:20:48 +1200 (NZST)
[EMAIL PROTECTED] wrote:


> def clicked(w):
> print 'Widget %s clicked! Text:' % (str(w), w.cget('text'))
> 
> def makeCallback(w):
> def callback(e):
> clicked(w)
> return callback
> 
> # create labels
> for text in ['foo', 'bar', 'baz']:
> lb = Label(master, text=text)
> lb.bind('', makeCallback(lb))
> 

I don't think it will work this way, because you don't catch the event bind() 
passes to the callback
(you also use a variable "e" in makeCallback() that isn't defined anywhere).

You probably better use a lambda in this case:

def callback(text):
print text

for text in ('foo', 'bar', 'baz'):
lb = Label(master, text=text)
lb.pack()
lb.bind('<1>', lambda event, t=text: callback(t))

or use event.widget to determine which label was clicked:

def callback(event):
print event.widget['text']

for text in ('foo', 'bar', 'baz'):
lb = Label(master, text=text)
lb.pack()
lb.bind('<1>', callback)

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] HTML links from Tkinter

2005-07-15 Thread Michael Lange
On Fri, 15 Jul 2005 10:55:37 +1200 (NZST)
[EMAIL PROTECTED] wrote:


> There's no table widget in standard Tkinter.  Search in the Python Cookbook 
> (on
> ActiveState) for a MultiListbox; it might do what you need.
> 
> -- 

On the Tkinter wiki there are some links to Tkinter table widgets (I have not 
tried any of these
though):



Regards

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tk -- which label clicked

2005-07-15 Thread Michael Lange
On Fri, 15 Jul 2005 23:29:22 +1200 (NZST)
[EMAIL PROTECTED] wrote:

> Quoting Michael Lange <[EMAIL PROTECTED]>:
> 
> > I don't think it will work this way, because you don't catch the event
> > bind() passes to the callback
> > (you also use a variable "e" in makeCallback() that isn't defined
> > anywhere).
> 
> That's what the variable 'e' is doing!
> 
> Here is some code I just wrote and tested:
> 
> >>> def clicked(w):
> ...  print 'Widget %s clicked! Text: %s' % (str(w), w.cget('text'))
> ...
> >>> def makeCallback(w):
> ...  def callback(e):
> ...   clicked(w)
> ...  return callback
> ...

Aah, you're right, I guess I got confused a little.
Still I think it's overly complicated in this context, when you can you get the 
same result with:

def makeCallback(event):
print "Widget %s clicked! Text %s" % (str(event.widget), 
event.widget['text'])

Regards

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ListBox in Tkinter

2005-07-19 Thread Michael Lange
On Mon, 18 Jul 2005 17:54:34 +0200
geon <[EMAIL PROTECTED]> wrote:

> Alan G napsal(a):
> 
> >> I would like to ask if it is possible to create such a listbox 
> >> (attached) in TKinter itself or must have pmw ot tix...or ...
> >
> >
> > PMW is written in Tkinter so yes, you could do it yourself but it is 
> > not a native widget. Using PMW would be much easier!
> >
> I have just found this: http://effbot.org/tkinterbook/optionmenu.htm - 
> that is nearly what I needed , just another design.
> I think there are even other new widgets in new Tk/Tcl compared to the 
> http://www.pythonware.com/library/tkinter/introduction/, but 
> undocumented yet. Or poorly or only in original Tk documentation.
> 

There are three new widgets in Tk 8.4:

the Spinbox (an entry field with "up" and "down" arrow buttons), the 
PanedWindow , which lets you
dynamically add resizable frames and the LabelFrame, a Frame with a decorative 
border
and a Label in one of its corners.

Regards

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Scrolling multilistbox help

2005-07-19 Thread Michael Lange
On Mon, 18 Jul 2005 13:54:45 +
"Alberto Troiano" <[EMAIL PROTECTED]> wrote:

> Hey tutors
> 
> I'm using the Multilistbox class and I noticed that it only handles the 
> mouse scroll and the scrollbar to go down or up.I succesfully implemented 
> the sort function that came with the class
> I also added code to handle the up and down arrow keys and it goes down all 
> right but only select the item and it doesn't scroll down or up
> 
> How can make it go up or down?
> I'm sendind the class here:
> 

Hi Alberto,

I haven't tested your code, but if I understand you correctly, the problem
is that the list is not automatically scrolled when you select a new item with
the Up and Down keys (right?).
Maybe it's the easiest to add a line like this to your _select1() and 
_select2() methods:

   l.see(int(l.curselection()[0]))

where l is the first of the listboxes; this should make sure the selected item 
is visible
(at least if you use selectmode=SINGLE). If keeping all lists in sync works, 
this
should be enough to scroll all other lists, too (like I said, untested though).

I hope this helps

Michael



> class MultiListbox(Frame):
> fila=0
> sortedBy=-1
> def __init__(self, master, lists):
>   Frame.__init__(self, master)
>   self.lists = []
>   for l,w,a in lists:
>   frame = Frame(self,background="red"); frame.pack(side=LEFT, 
> expand=YES, 
> fill=BOTH)
>   Button(frame,background="red",foreground="white",font="Verdana 8 
> bold",text=l, borderwidth=1, relief=RAISED,command=lambda a=a: 
> self._sortBy(a)).pack(fill=X)
>   lb = Listbox(frame, width=w, borderwidth=0, selectborderwidth=0,
>relief=FLAT, exportselection=FALSE)
>   lb.pack(expand=YES, fill=BOTH)
>   self.lists.append(lb)
>   lb.bind('', lambda e, s=self: s._select(e.y))
>   lb.bind('', lambda e, s=self: s._devolverfila(e.y))
>   lb.bind('', lambda e, s=self: s._devolverfila(e.y))
>   lb.bind('', lambda e, s=self: s._select(e.y))
>   lb.bind('', lambda s: _select1())
> lb.bind('', lambda s: _select2())
>   lb.bind('', lambda e: 'break')
>   lb.bind('', lambda e, s=self: s._b2motion(e.x, e.y))
>   lb.bind('', lambda e, s=self: s._button2(e.x, e.y))
>   frame = Frame(self,background="red"); frame.pack(side=LEFT, fill=Y)
>   Label(frame,background="red",foreground="white",font="Verdana 8 bold", 
> borderwidth=1, relief=RAISED).pack(fill=X)
>   sb = Scrollbar(frame,background="red", orient=VERTICAL, 
> command=self._scroll)
>   sb.pack(expand=YES, fill=Y)
>   self.lists[0]['yscrollcommand']=sb.set
> 
> def _sortBy(self, column):
> """ Sort by a given column. """
> if column == self.sortedBy:
> direction = -1 * self.direction
> else:
> direction = 1
> elements = self.get(0, END)
> self.delete(0, END)
> elements.sort(lambda x, y: self._sortAssist(column, direction, x, 
> y))
> self.insert(END, *elements)
> self.sortedBy = column
> self.direction = direction
> 
> def _sortAssist(self, column, direction, x, y):
> if column!=0:
> c = cmp(x[column], y[column])
> if c:
> return direction * c
> else:
> return direction * cmp(x, y)
> else:
> c = cmp(int(x[column]), int(y[column]))
> if c:
> return direction * c
> else:
> return direction * cmp(x, y)
> 
> def _select(self, y):
>   row = self.lists[0].nearest(y)
>   self.selection_clear(0, END)
>   self.selection_set(row)
>   self.fila=row
>   return 'break'
> 
> def _devolverfila(self, y):
>   row = self.lists[0].nearest(y)
>   self.selection_clear(0, END)
>   self.selection_set(row)
>   self.fila=row
> 
> def _select1(self):
> if self.fila==self.size()-1:
> pass
> else:
> self.selection_clear(0, END)
>   self.selection_set(self.fila+1)
> self.fila+=1
> self._scroll()
>   return 'break'
> 
> def _select2(self):
>   if self.fila==0:
> pass
> else:
> self.selection_clear(0, END)
> self.selection_set(self.fila-1)
> self.fila-=1
>   return 'break'
> 
> def _button2(self, x, y):
>   for l in self.lists: l.scan_mark(x, y)
>   return 'break'
> 
> def _b2motion(self, x, y):
>   for l in self.lists: l.scan_dragto(x, y)
>   return 'break'
> 
> def _scroll(self, *args):
>   for l in self.lists:
>   apply(l.yview, args)
> 
> def curselection(self):
>   return self.lists[0].curselection()
> 
> def delete(self, first, last=None):
>   for l in self.lists:
>   l.delete(first, last)
> 
> def get(self, first, last=None):
>   r

Re: [Tutor] Tkinter event for changing OptionMenu items

2005-07-21 Thread Michael Lange
On Thu, 21 Jul 2005 12:19:00 -0400
Bernard Lebel <[EMAIL PROTECTED]> wrote:

> Hello,
> 
> I'm trying to bind an event to the changes made to an OptionMenu. Ie
> the user chooses a different item, the rest of the Tk window gets
> updated. To repopulate the window, a function would be called by the
> binding.
> 
> Any suggestion?
> 
> 
> var1 = StringVar()
> var1.set( aTables[0] )
> oOptionMenu = OptionMenu( oRoot, var1, aTables[0], *aTables[1:] )
> sTableName = var1.get()
> oOptionMenu.bind( '', getTableColumns )
> oOptionMenu.pack( fill = X )
> 
> Here the '' event is obviously not the one I'm looking for,
> but is there to illustrate what code I have so far.
> 
>

Hi Bernard,

if I understand you correctly, the "" event of the OptionMenu's Menu may 
be the best
bet for you (not very much tested though):

 oOptionMenu['menu'].bind('', getTableColumns)

Otherwise you would probably have to call 
oOptionMenu['menu'].entryconfigure(command=...) on all menu entries.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter event for changing OptionMenu items

2005-07-23 Thread Michael Lange
On Thu, 21 Jul 2005 14:16:05 -0400
Bernard Lebel <[EMAIL PROTECTED]> wrote:

> Hi Michael,
> 
> Let say I have a MenuOption, that consists of 3 items. This MenuOption
> sits on top of the Tkinter window.
> 
> In the lower part, I have a bunch of widgets (text fields). When the
> choose a different item from the MenuOption, it would call a function
> that clears the lower part and repopulates it with new fields. My
> problem is binding this callback to the event of choosing an item.
> 
> 

In this case I would try the StringVar()'s trace method, which you can use to
track changes of its value; a simple example:

>>> from Tkinter import *
>>> root = Tk()
>>> s = StringVar()
>>> s.set('a')
>>> om = OptionMenu(root, s, 'a', 'b', 'c', 'd')
>>> om.pack()
>>> def changed(*args):
... print s.get()
... 
>>> s.trace('w', changed)

In the example changed() is called each time you select an item in the menu and 
with
s.get() you can query the current selection and update the window according to 
the current value.

I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter import error

2007-04-24 Thread Michael Lange
On Tue, 24 Apr 2007 00:09:21 +0100
"Alan Gauld" <[EMAIL PROTECTED]> wrote:

> 
> "John DeStefano" <[EMAIL PROTECTED]> wrote
> 
> > I've run into an error that I've seen reported in several places, 
> > but
> > none of the fixes seem to be working for me: when I try to "import
> > Tkinter" I get a configuration error:
> > Traceback (most recent call last):
> >  File "", line 1, in 
> >  File "/usr/local/lib/python2.5/lib-tk/Tkinter.py", line 38, in 
> > 
> >import _tkinter # If this fails your Python may not be configured 
> > for Tk
> > ImportError: No module named _tkinter
> 
> Have you specifically selected Tkinter when you compiled the code?
> I believe you need to set something via configure... Alternatively
> find an rpm with Tkinter configured already, that should be pretty
> easy.

Usually there is no need to pass extra arguments to configure.
My guess is that you missed to install Tcl / Tk and/or the Tcl/Tk development
packages before compiling python.

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] convert a file from plaintext(Ascii) to unicode? very quickquestions

2005-08-16 Thread Michael Lange
On Mon, 15 Aug 2005 22:51:20 -0400
Kent Johnson <[EMAIL PROTECTED]> wrote:

> I think Luke's suggestion will work if you use f.read() (to read the whole 
> file as a single string) instead of f.readlines() and f.write() instead of 
> writelines().
> 
> Kent
> 

And if you want to convert ascii into unicode you need to call * decode() * ( 
which does pretty much the same as unicode() )
on the string, not encode() .

Michael

> luke wrote:
> > List:
> > I'm forwarding this private message(hope you don't mind Denise)
> > I personally have no idea what to do, but
> > someone else might be able to help.
> > -Luke
> > 
> > 
> > - Forwarded Message -
> > 
> > text is a list, so you can't encode it.  but you can iterate over each
> > of the elements and encode them.  I have tried several variations of
> > that, but keep ending up with all my newlines being little boxes. any
> > ideas?
> > 
> > Thanks,
> > Denise
> > 
> > On 8/15/05, luke <[EMAIL PROTECTED]> wrote:
> >>I dont know much about Unicode but it seems like
> >>f = file(filename, "r")
> >>text = f.readlines()
> >>text = text.encode()
> >>#or maybe just text.encode()?
> >>f.close()
> >>
> >>should encode the filetext to unicode.
> >>then you could do a
> >>f = file(filename, "w")
> >>f.writelines(text)
> >>f.close()
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to make a script do two things at once.

2005-08-22 Thread Michael Lange
On Sun, 21 Aug 2005 16:23:20 -0500
nephish <[EMAIL PROTECTED]> wrote:

> Hey there,
> i have a simple question about getting a script to do
> two things at once.
> like this.
> 
> 
> for i in range(100):
> print i
> time.sleep(.2)
> if i == 15:
> os.system('python /home/me/ipupdate.py')
>
> print 'done'
> 
> when i run this, it stops at 15 and runs the script called out in the 
> os.system line. i know it is supposed to do that. But, how could i get a 
> script to do this without stopping the count (or delaying it unill the 
> script called exits) I don' t have to run it this way, i can import it 
> if necessary as a module. or whatever will work so i can execute two 
> things at once.
> 

If you just need to call a unix system command you can simply add "&" to the 
command string to
make it run in the background.

Regards

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] upgrading from 2.3 to 2.4.1 on Mandrake Linux 10.1

2005-09-12 Thread Michael Lange
On Mon, 12 Sep 2005 07:35:52 -0500
"Andy Dani" <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> Which is the best location to install Python in Linux? Should it be under one 
> directory or different (like lib, doc, bin etc.)?
> 
> I followed installation instructions in "inst.pdf" from python documents. I 
> can see that Python 2.4.1 has been installed in /user/lib/local by standard 
> installation procedure. When I launch my IDLE or "Python" at shell, Python 
> 2.3 comes up! Why? Do I need to upgrade any other config files? 
> 
> Also, I am looking for help in upgrading xwPython package, OpenGL package, 
> and installation of BOA constructor. They go in which directories?
> 

Hi Nirav,

I recommend not to *upgrade* the existing python installation but simply 
install a second version.
The reason is that some system specific programs may depend on python-2.3 or 
one of the extensions
that are already installed.

If you are running Mandrake the best bet is to download mandrake's source rpm 
from 

   


and build the binary RPM from it. After installing the RPM you should make sure
that the link "/usr/bin/python" points to "/usr/bin/python2.3" .

If you want to run the new python, just type "python2.4" (or in your scripts 
use the
shebang line "#!/usr/bin/env python2.4" )
(this should work if you already installed python-2.4 into /usr/local , too).

WxPython and OpenGL should probably be installed into the 
python2.x/site-packages directory,
BOA is (as far as I know) pure python and can be installed anywhere; if you 
want to run BOA with
python-2.4 you will probably have to edit the shebandg line in BOA's main 
program file (or type
python2.4 boa (or however the main program is called).

Maybe you can find mandrake source RPM's for these, too, which might make it 
easier for you
to install everything in the correct place.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Focus in tkinter

2005-09-14 Thread Michael Lange
On Wed, 14 Sep 2005 19:58:07 +0100 (BST)
David Holland <[EMAIL PROTECTED]> wrote:

> I want to make the mouse focus in a GUI move to the
> correct button/text entry widget.  Does anyone know
> how to do this ?
> 

Hi David,

to set the focus to a particular widget you need the focus_Set() method:

b = Button(parent)
b.focus_set()

Maybe you want to have a look at Frederik Lundh's excellent Tkinter books:

   

or the more complete, but a little outdated version:



I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New image with Tkinter?

2005-10-10 Thread Michael Lange
On Mon, 10 Oct 2005 11:36:22 -0600
Joseph Quigley <[EMAIL PROTECTED]> wrote:

> Hi,
> I've written an image reader that uses the PIL module.
> I have a variable that uses os.listdir('mydir') to make a list of all the
> pictures in the folder... here's what I'm talking about:
(...)
> The image won't refresh when I click on 'Next'! Any help would be
> appreciated.
> Joe
> 

Hi Joe,

the image won't refresh until you explicitely tell Tk to do so, so you would 
have to do some more
in newPic(); btw, it looks overly complicated to me to use a "Data" class where 
a simple variable
will do the trick, so I would suggest to change the code like this:

pics = os.listdir(imgDir)
pics.remove('license.txt')
pics.remove('gacor.py')
print "There are %s saved images in the image folder." % len(pics)
pic = 0

root = Tk()
root.title("GaCoR Image Browser")
app = Frame(root)
app.grid()

imgPrep = ImageTk.PhotoImage(file=os.path.join(imgDir, pics[pic]))
imgShow = Label(app, image=imgPrep).grid()
info = Label(app, text="Displaying %s" % pics[Data.pic])
info.grid()

def newPic():
global pic
pic = pic + 1
imgPrep.configure(file=os.path.join(imgDir, pics[pic]))

Button(app, text="Next Image", command=newPic).grid()
Button(app, text="Close", command=quitProg).grid()
app.mainloop()

I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 20, Issue 37

2005-10-11 Thread Michael Lange
On Mon, 10 Oct 2005 17:07:47 -0600
Joseph Quigley <[EMAIL PROTECTED]> wrote:


> Hi,
> 
> Unfortunately I get this error:
> 
> Exception in Tkinter callback
> Traceback (most recent call last):
> File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__
> return self.func(*args)
> File "Programming/Gacor/tmp.py", line 83, in newPic
> imgPrep.configure(file=os.path.join(imgDir, pics[pic]))
> AttributeError: PhotoImage instance has no attribute 'configure'
> 
> I think I should mention that I'm completely in the dark when it comes 
> to GUI programming (and I don't have much time to learn it... or do I?)

Oops, sorry for that; in fact it looks like you will have to define a new 
PhotoImage instance, like:

def newPic():
global pic, imgPrep
pic = pic + 1
imgPrep = ImageTk.PhotoImage(file=file=os.path.join(imgDir, pics[pic]))
imgShow.configure(image=imgPrep)

The configure() method works for Tkinter.PhotoImage, but obviously not for 
ImageTk.PhotoImage, so I got trapped here.

Regards

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] TKinter Question

2005-11-08 Thread Michael Lange
On Tue, 08 Nov 2005 00:10:16 -0600
Rob Dowell <[EMAIL PROTECTED]> wrote:

> Just a quick TKinter question. Is it possible to have custom 
> frames/widgets? In other words can I customize the way that the GUI 
> looks (i.e. rounded corners on the frames, beveled/raised edges, etc.) I 
> was just wondering if it was possible and if it is possible then where I 
> might get some information on how to do it. Thank you very much, Rob.
> 

Hi Rob,

I'm not sure what you mean with "beveled/raised edges" , maybe setting the 
widget's
relief to GROOVE or RIDGE does what you want?
Rounded corners are much more complicated; you will probably need the shape 
extension for Tk
which adds non-rectangular window support to Tk.
A version of shape that works with unix systems is included in the tkdnd drag 
and drop extension
(http://sourceforge.net/projects/tkdnd); I wrote a Tkinter wrapper for tkdnd 
(http://www.8ung.at/klappnase/TkinterDnD/TkinterDnD.html)
that makes it possible to use tkdnd from python. If you need windows support, 
you can try
a newer version of shape (http://www.cs.man.ac.uk/~fellowsd/tcl/shapeidx.html) 
that seems to support
windows platforms, too.

Regards

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] tkFileDialog.Directory

2005-11-14 Thread Michael Lange
On Mon, 14 Nov 2005 14:42:27 +0100 (MET)
[EMAIL PROTECTED] wrote:

> Hello!
> I want to learn Tkinter and try to build a small File search dialog. Tkinter
> is nice, but here is a problem where I am stuck:
> 
> I want to allow the dialog's user to pick a directory. The widget for this
> is tkFileDialog.Directory. But when I start the Directory-Window, it is
> possible move the focus back to my File Search dialog. Thus it is possible
> but not wanted to create several "Pick directory" windows. I tried to make
> the Directory instance modal by calling .grab_set() but this raises an
> attribute error. Here is a minimal example:
> 

Hi Karsten,

I guess the tkFileDialog.Directory class isn't intended to be used directly.
Try tkFileDialog.askdirectory() instead.
If there are problems with the grab state, try passing "parent=self.top" to 
askdirectory().

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] tkFileDialog.Directory

2005-11-15 Thread Michael Lange
On Tue, 15 Nov 2005 17:03:24 +0100 (MET)
[EMAIL PROTECTED] wrote:

> 
> I would like to ask another question. I don't understand the exception
> mechanism
> of Python when running a Tkinter app. If an exception happens (it does
> happen quite often
> at the moment..), a traceback is written to the console while the Tk window
> remains open
> and the application is still running. This is not what I expected -- I
> expected the application
> would end. Why is that?
> 
> Is there a way to create an error handler for uncaught exceptions in Tkinter
> apps?
> In other words, can I change the behaviour from writing a traceback to the
> console to
> something else? Can I, for example, show a message box instead?
> 

If you only want to see the traceback in your gui, I recommend using Pmw.
Pmw pops up a Text window that shows the complete traceback, it doesn't catch 
the exception though.

> Here is a small example:
> 
> --- snip ---  
> import Tix
> 
> def raise_exception():
>   print 1/0
>   
> if __name__ == '__main__':
> root = Tix.Tk()
> root.title("Exception demo")
> 
> Tix.Button(root, text = "Don't press", command = raise_exception).pack()
> 
> try:
>   root.mainloop()
> except:
>   print "An error has occured."
> --- snip ---
> 
> The except part gets never executed.
> 

That's because the error isn't in the mainloop() method.
Probably you meant something like

def raise_exception():
try:
print 1 / 0
except ZeroDivisionError:
print "An error has occured."
# or with a message box:
# tkMessageBox.showerror(message='ZeroDivisionError')

?

Thank god python is nice enough to raise the error where it actually happens;
imagine your example would work, you would never know *where* the error happened
nor could you create adequate handlers for different exceptions in different 
situations.


I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Creating Tkinter Menubars

2005-11-16 Thread Michael Lange
On Tue, 15 Nov 2005 16:17:53 -0500
Double Six <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> I am testing the following Tkinter code (attached at the end of
> this message) by Fredrik Lundh on a Mac OS X 10.4.2 with Python
> version 2.3. I do get a root window, but it is totally blank
> without the desirable menubars such as File and Edit. What am I
> missing?
> 


It works well for me (on linux, python-2.3), maybe a mac specific thing (sorry 
, I can't help then).
Does the following, simpler code work for you?

from Tkinter import *

root = Tk()
menubar = Menu(root)
menu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=menu)
menu.add_command(label="New")
menu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Edit", menu=menu)
menu.add_command(label="Cut")
menu.add_command(label="Copy")
menu.add_command(label="Paste")
root.config(menu=menubar)
root.mainloop()

The only thing that looks a little starnge to me in the original code is
that the menubar is created as a child of the AppUi class, which is basically a 
Frame,
but then it is attached to that Frame's parent (the root window).
Maybe the mac doesn't like this (just a thought)?

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter mainloop (was Re: tkFileDialog.Directory)

2005-11-16 Thread Michael Lange
On Wed, 16 Nov 2005 10:55:24 +0100 (MET)
[EMAIL PROTECTED] wrote:

Hi Karsten,

> I thought the mainloop() function is something like
> 
> def mainloop():
>   e= get_event()
>   if e:
> for w in widgets: w.handle(e)
> 
> but apparently it is not.
> 
> It's not bad that the Tkinter windows don't destroy upon an exception,
> since it gives me the option to display an error window, but I feel unsafe
> unless I understand why it does not.
> 

I am not enough of an expert to give you a "complete" answer for that, so anyone
please correct me if I am wrong.
As far as I understand, the mainloop() command just starts a tk shell and 
Tkinter gives
you an interface to communicate with this tk shell.
In fact Tkinter "translates" any widget command into a tk command and sends it 
to the
tk shell, which itself sends it to the associated Tk window (or the related 
widget).
The tk shell will run as long as

a - Python decides to close it for you (e.g. after the main (Tk()) window has 
been destroyed)
b - you explicitely close it calling the widget's quit() method
c - a fatal tk error occurs, so the tk shell decides to quit itself

Now most of the errors that occur happen of course on the python level and are 
caught
by the python interpreter (that shows you the traceback) and there is no reason
for python to inform the tk shell that it should quit.

I hope this makes sense

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI?

2005-11-29 Thread Michael Lange
On Tue, 29 Nov 2005 13:48:21 -0700
"Nathan Pinno" <[EMAIL PROTECTED]> wrote:

> Hey Danny and all,
> 
> Alberto told me that there was a password entry box in TKInter. Can anyone
> tell me about that, please?
> 

Hi Nathan,

maybe he meant the Pmw.PromptDialog 
() ?

Regards

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unicode trouble

2005-11-30 Thread Michael Lange
On Wed, 30 Nov 2005 13:41:54 -0500
Kent Johnson <[EMAIL PROTECTED]> wrote:


> >>>This is the full error:
> >>>Traceback (most recent call last):
> >>>  File
> >>>"C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
> >>>line 310, in RunScript
> >>>exec codeObject in __main__.__dict__
> >>>  File "C:\Python\BA\Oversett.py", line 47, in ?
> >>>  File "C:\Python\BA\Oversett.py", line 23, in kjor
> >>>en = i.split('\t')[0]
> >>>  File "C:\Python23\lib\codecs.py", line 388, in readlines
> >>>return self.reader.readlines(sizehint)
> >>>  File "C:\Python23\lib\codecs.py", line 314, in readlines
> >>>return self.decode(data, self.errors)[0].splitlines(1)
> >>>UnicodeDecodeError: 'utf8' codec can't decode bytes in position 168-170:
> >>>invalid data
> > 
> > 
> >>This is fairly strange as the line
> >> en = i.split('\t')[0]
> >>should not call any method in codecs. I don't know how you can get such a
> >>stack trace.
> > 
> > The file f where en comes from does contain lots of lines with one english
> > word followed by a tab and a norwegian one. (Approximately 25000 lines) It
> > can look like this: core\tkjærne
> 
> Yes, I understand that.
> 
> > So en is supposed to be the english word that the program need to find in
> > MS Word, and to is the replacement word. So wouldn't that be a string that
> > should be handeled by codecs?
> > 
> > for i in self.f.readlines():
> > en = i.split('\t')[0]
> 
> The thing is, it's the line
>   for i in self.f.readlines():
> that is calling the codecs module, not the line
>   en = i.split('\t')[0]
> but it is the latter line that is in the stack trace.
> 
> Can any of the other tutors make any sense of this stack trace?

As far as I see here, isn't the line

return self.decode(data, self.errors)[0].splitlines(1)

causing the traceback?

I haven't read all of this thread, but maybe you are trying to pass a
non-utf8 string to the utf8 codec?

Michael




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI?

2005-12-03 Thread Michael Lange
On Fri, 2 Dec 2005 15:20:43 -0700
"Nathan Pinno" <[EMAIL PROTECTED]> wrote:

> I like the Toolkit, is there anywhere where there is a how to use it?
>  

A good place to look for Tkinter resources is the wiki:



There is a number of links to Tkinter documentation there:



And still the best resource on Tkinter programming is John Grayson's "Python 
and Tkinter programming":



Regards

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] tkFileDialog bug on windows

2005-12-03 Thread Michael Lange
On Fri, 2 Dec 2005 16:58:26 -0800
Fred Lionetti <[EMAIL PROTECTED]> wrote:

> Hi everyone,
> 
> I may have found a strange bug with tkFileDialog, and I'm wondering if
> anyone has a workaround for the problem.  It happens when you have a
> button (or any other clickable widget) directly behind the
> askopenfilename dialog box and double click on a file.  The button
> (behind the open file dialog) gets clicked, when it shouldn't.  It
> occurs with the code below (but only under windows).
> 
> --
> from Tkinter import *
> import tkFileDialog
> 
> def cmd():
> print "button was pressed"
> 
> parent = Tk()
> Button(parent, text = "hello", command = cmd, width=30, height = 10).pack()
> tkFileDialog.askopenfilename(parent=parent, title = "Double click on a
> file with the 'hello' button directly behind")
> 
> parent.mainloop()
> -

Hi Fred,

I don't have a windows box here to try it, so I can just guess.
On my linux box the list in the dialog responds to ButtonRelease events,
but I think on windows tk uses native dialogs, and maybe these respond to 
ButtonPress events;
if this is the case, it may happen that the ButtonRelease occurs *after* the 
dialog window
has been destroyed, so the event gets delivered to the button in the parent 
window.

Regards

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter help required

2005-12-14 Thread Michael Lange
On Wed, 14 Dec 2005 15:05:07 +0200
Vlad Popescu <[EMAIL PROTECTED]> wrote:

Hi Vlad,

> Hello everyone,
> 
> I have been desperately trying to get Tkinter to run, but without much
> success thus far. I've followed the instructions at
> http://wiki.python.org/moin/TkInter ; importing _tkinter does not work
> and I have no idea what files I should edit in order to add the module.
> Both Tcl and Tk, along with their -devel packages, are installed and
> updated. Python version is 2.4.1
> 

it looks like you are running a linux box?
If so , probably Tkinter is in a separate package that may be called "tkinter" 
or "python-tk"
or something similar, depending on the distro. May be this package is not 
installed?

Regards

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] First steps with Tkinter

2006-01-26 Thread Michael Lange
On Thu, 26 Jan 2006 18:20:48 +
[EMAIL PROTECTED] wrote:


> 
> root.mainloop()
> 
> I am running from inside Pythonwin 2.4 IDE under XP Pro and every time I run 
> hello2.py it freezes when I press "QUIT".  The only way to kill it is through 
> Alt-Ctrl-Del but this crashes Pythonwin.  Any workaround for this so that I 
> can use Tkinter from inside the IDE?  BTW the same thing happend with IDLE
> 

Hi,

when running Tkinter apps from IDLE or Pythonwin, you need to comment out the 
call to mainloop() .
This is because the IDE itself runs a Tkinter mainloop() and two of these 
cannot coexist in one process.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Using ioctl

2006-02-02 Thread Michael Lange
Hello,

I am writing an app that records from the soundcard using ossaudiodev.
In the OSS programmer's guide they recommend when reading data fragments from 
the soundcard
to use the fragment size as it is requested by the driver. According to the 
programmer's guide
the ioctl call to determine the requested fragment size is:

int frag_size;
if ioctl(audio_fd, SNDCTL_DSP_GETBLKSIZE, &frag_size) == -1)
error();

Unfortunately this procedure is not implemented in the ossaudiodev module, so I
tried to write it myself.
>From reading the fcntl module's docs, I came to the following solution:

try:
f = array.array('h', [0])
fcntl.ioctl(audio_fd, ossaudiodev.SNDCTL_DSP_GETBLKSIZE, f, 1)
frag_size = f.tolist()[0]
except:
frag_size = -1
if frag_size <= 0:
frag_size = 4096


This *seems* to work, I tried several soundcards and got frag_size values like 
4096, 8192 or 16384 .
However I am not really sure about what I am doing there, so I would feel more 
confident
if anyone could explain how ioctl is supposed to be used ( I also felt that I 
should use
the try...except block for the call in case it fails, but I don't have an idea 
"except *what*").

Any hints are much appreciated.

thanks in advance

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] GUI Development - Which toolkit

2006-02-06 Thread Michael Lange
On Mon, 6 Feb 2006 09:44:48 -0500
Paul Kraus <[EMAIL PROTECTED]> wrote:

> I am developing applications that need to run without work on both windows 
> and 
> linux and was wondering what gui toolkits everyone uses and why.
> 
> I have been looking at wxpython and tkinter.
> 

I have only used Tkinter so far, so I cannot say much about wx.

Tkinter's biggest disadvantage is that some advanced widgets are missing, like
a spreadsheet widget or a html viewer. There is also no built-in drag&drop 
support.
A lot of these things are available by installing extension modules, though.

If you don't need any of these Tkinter is worth a try; it is well documented, 
stable
and easy to learn, and the biggest advantage over other toolits, it is included 
in
the standard python distribution.

If you want to use Tkinter you should also have a look at Tix, which is now 
included
in python's windows installer (and also in any recent linux distro) and which
adds a lot of nice extra widgets to Tkinter, like Combobox and Tree widget.

A good place to find out more about Tkinter is the wiki: 
.

I hope this helps

Michael


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing instance attributes in different threads

2006-02-07 Thread Michael Lange
On Mon, 06 Feb 2006 18:34:18 -0500
Kent Johnson <[EMAIL PROTECTED]> wrote:


> 
> It sounds like you have some attributes that you are using as flags to 
> allow one thread to control another. There are definitely some pitfalls 
> here. You probably want to use threading.Condition or Queue.Queue to 
> communicate between the threads. Can you give more details of what you 
> are trying to do?
> 

I have used a boolean to control access to a variable that is used by two 
threads,
as in this example:

thread 1 does:

while self.locked:
pass
self.locked = 1
if condition:
self.name = 'bob'
else:
self.name = 'mike'
self.locked = 0

thread 2 does:

while self.locked:
pass
self.locked = 1
n = self.name
self.locked = 0
if n == 'bob':

else:


I *thought* this would be safe, but now reading this thread I start to doubt.
Are there any pitfalls I overlooked in this technique?

Thanks

Michael


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing instance attributes in different threads

2006-02-07 Thread Michael Lange
On Tue, 07 Feb 2006 06:02:45 -0500
Kent Johnson <[EMAIL PROTECTED]> wrote:

> 
> One way to make this code thread-safe is to use a threading.Condition() 
> instead of a boolean variable:
> 
> thread 1 does:
> 
>  self.lock.acquire()
>  if condition:
>  self.name = 'bob'
>  else:
>  self.name = 'mike'
>  self.lock.release()
> 
> thread 2 does:
> 
>  self.lock.acquire()
>  n = self.name
>  self.lock.release()
>  if n == 'bob':
>  
>  else:
>  
> 
> If this is the only communication or synchronization between the two 
> threads I don't think the lock is needed at all - thread 2 is presumably 
> in a loop and thread 1 is controlling the behaviour of the loop 
> asynchronously. If there is some other kind of synchronization between 
> the loops, and thread 2 is only supposed to run once for each setting of 
> self.name in thread 1, you could use Condition.wait() and 
> Condition.notify() to do the synchronization.
> 

Thanks Kent,

In fact I have three threads, a main gui thread and two child threads. Child 
thread 1 reads data
from the soundcard and appends these data to two lists which I use as recording 
buffer. The data from
list 1 are used by the gui thread to draw a vumeter, the data from list 2 are 
written to the
target file. So the communication between the threads occurs when the gui 
thread resp. child thread 2
read and empty the buffer lists to process the data.
So my functions currently (with boolean "locks") look like:

gui thread (this function is called periodically by Tkinter):

def get_peaks(self):
if self.vu_locked:
return None
self.vu_locked = 1
data = [x for x in self.vubuffer]
self.vubuffer = []
self.vu_locked = 0
if not data:
return None
left, right = 0, 0
for d in data:
left = max(audioop.max(audioop.tomono(d, 2, 1, 0), 2), left)
right = max(audioop.max(audioop.tomono(d, 2, 0, 1), 2), right)
return left, right

thread 1:

vubuffer = []
recbuffer = []
while self.running:
data = self._audioobj.read(self._fragsize)# read data from soundcard
vubuffer.append(data)
if not self.vu_locked:
self.vu_locked = 1
self.vubuffer += vubuffer
vubuffer = []
self.vu_locked = 0
if self.recording:
recbuffer.append(data)
if not self.rec_locked:
self.rec_locked = 1
self.recbuffer += recbuffer
recbuffer = []
self.rec_locked = 0

thread 2:

while self.recording:
# wait a moment until there is something in the buffer to be written
time.sleep(0.1)
if not self.rec_locked:
self.rec_locked = 1
data = [x for x in self.recbuffer]
self.recbuffer = []
self.rec_locked = 0
for d in data:
self._waveobj.writeframesraw(d)# write the data to a file

So I think I need two Condition objects here; it is most important here that 
thread 1 does not
block to minimize the risk of recording buffer overruns, but from reading the 
docs I am
not sure about the correct procedure. So if I change self.rec_locked and 
self.vu_locked from the
code above to be Condition objects is it correct to do:

thread 1:

vubuffer = []
recbuffer = []
while self.running:
data = self._audioobj.read(self._fragsize)# read data from soundcard
vubuffer.append(data)
if self.vu_locked.acquire(blocking=0):
self.vubuffer += vubuffer
vubuffer = []
self.vu_locked.release()
if self.recording:
recbuffer.append(data)
if self.rec_locked.acquire(blocking=0):
self.recbuffer += recbuffer
recbuffer = []
self.rec_locked.release()

thread 2:

while self.recording:
# wait a moment until there is something in the buffer to be written
time.sleep(0.1)
data = []
if self.rec_locked.acquire(blocking=0):
data = [x for x in self.recbuffer]
self.recbuffer = []
self.rec_locked.release()
for d in data:
self._waveobj.writeframesraw(d)# write the data to a file

Thanks

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing instance attributes in different threads

2006-02-08 Thread Michael Lange
On Tue, 7 Feb 2006 23:31:06 +0100
Michael Lange <[EMAIL PROTECTED]> wrote:

> 
> So I think I need two Condition objects here; it is most important here that 
> thread 1 does not
> block to minimize the risk of recording buffer overruns, but from reading the 
> docs I am
> not sure about the correct procedure. So if I change self.rec_locked and 
> self.vu_locked from the
> code above to be Condition objects is it correct to do:
> 


Ok, some testing gave me the answer, with the code I posted I got an 
AssertionError, so obviously
the release() call has to be inside the "if self.rec_lock.acquire(blocking=0):" 
block.
So now my functions look like:

gui thread (periodically called by Tkinter):

def get_peaks(self):
if not self.vu_lock.acquire(blocking=0):
return None
data = [x for x in self.vubuffer]
self.vubuffer = []
self.vu_lock.release()
if not data:
return None
left, right = 0, 0
for d in data:
left = max(audioop.max(audioop.tomono(d, 2, 1, 0), 2), left)
right = max(audioop.max(audioop.tomono(d, 2, 0, 1), 2), right)
return left, right
   
child thread 1:

vubuffer = []
recbuffer = []
while self.running:
data = self._audioobj.read(self._fragsize)# read data from soundcard
vubuffer.append(data)
if self.vu_lock.acquire(blocking=0):
self.vubuffer += vubuffer
vubuffer = []
self.vu_lock.release()
if self.recording:
recbuffer.append(data)
if self.rec_lock.acquire(blocking=0):
self.recbuffer += recbuffer
recbuffer = []
self.rec_lock.release()

child thread 2:

while self.recording:
# wait a moment until there is something in the buffer to be written
data = []
time.sleep(0.1)
if self.rec_lock.acquire(blocking=0):
data = [x for x in self.recbuffer]
self.recbuffer = []
self.rec_lock.release()
for d in data:
self._waveobj.writeframesraw(d)# write data to file

This *seems* to work, however it looks like this code does not separate 
properly the gui from the child
threads which everyone says should be avoided in any case.
On the other hand, with the technique I used before, with a boolean as "lock", 
like:

 if not self.vu_locked:
self.vu_locked = 1
self.vubuffer += vubuffer
vubuffer = []
self.vu_locked = 0

it seems like the worst case is that both the gui and the child thread pass the 
test "if not self.vu_locked" at
the same time which might cause some data to be lost from the vubuffer list; 
probably that is something
I could live with.
So now my question:
Does anyone know how a threading.Condition() object is handled internally, so 
maybe its methods actually
can be called safely from the gui thread?

Thanks

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing instance attributes in different threads

2006-02-08 Thread Michael Lange
On Wed, 08 Feb 2006 08:37:18 -0500
Kent Johnson <[EMAIL PROTECTED]> wrote:

> Another architecture you might consider is to have thread 1 put the 
> actual acquired buffers into two Queues that are read by the two 
> consumer threads. This would save you a lot of copying and give you a 
> cleaner implementation. It may block on the producer thread but the 
> Queue is locked only while something is actually being put in or taken 
> out so the blocks should be short.
> 
> For example (not tested!):
>  def get_peaks(self):
>  try:
>  data = self.vu_queue.get_nowait()
>  except Queue.Empty:
>  return None
>  left, right = 0, 0
>  for d in data:
>  left = max(audioop.max(audioop.tomono(d, 2, 1, 0), 2), left)
>  right = max(audioop.max(audioop.tomono(d, 2, 0, 1), 2), right)
>  return left, right
> 
> child thread 1:
> 
>  while self.running:
>  data = self._audioobj.read(self._fragsize)# read data from 
> soundcard
>  self.vu_queue.put(data)
>  self.rec_queue.put(data)
> 
> child thread 2:
> 
>  while self.recording:
>  data = self.rec_queue.get()
>  for d in data:
>  self._waveobj.writeframesraw(d)# write data to file
> 

Thanks Kent,

the problem with Queues is that Queue.get() returns only one item at a time, 
but I found that depending
on cpu load and disk usage hundreds of data fragments may accumulate into the 
recording buffer, so in the "writer"
thread I would have to use something like (and similar in the get_peaks() 
method):

while self.recording:
data = []
while not self.rec_queue.empty():
try:
   data.append(self.rec_queue.get(block=0))
except Queue.Empty:
   break
for d in data:
self._waveobj.writeframesraw(d)

I am not sure if this approach is more robust than the one that uses 
Condition() objects,
however I don't think the code looks cleaner.

> 
> > This *seems* to work, however it looks like this code does not separate 
> > properly the gui from the child
> > threads which everyone says should be avoided in any case.
> 
> I don't understand your concern here.
> 

Maybe it is just because I have not fully understood how the Condition objects 
work; what I had in mind are
warnings like this one (from 
http://www.astro.washington.edu/owen/TkinterSummary.html):

All Tkinter access must be from the main thread (or, more precisely, the 
thread that called mainloop).
Violating this is likely to cause nasty and mysterious symptoms such as 
freezes or core dumps. Yes this
makes combining multi-threading and Tkinter very difficult. The only fully 
safe technique I have found is polling
(e.g. use after from the main loop to poll a threading Queue that your 
thread writes). I have seen it suggested
that a thread can safely use event_create to communicate with the main 
thread, but have found this is not safe.

I guess I have to spend a second thought at this.

Thanks again

Michael


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing instance attributes in different threads

2006-02-08 Thread Michael Lange
On Wed, 08 Feb 2006 13:47:39 -0500
Kent Johnson <[EMAIL PROTECTED]> wrote:

> > while self.recording:
> > data = []
> > while not self.rec_queue.empty():
> > try:
> >data.append(self.rec_queue.get(block=0))
> > except Queue.Empty:
> >break
> > for d in data:
> > self._waveobj.writeframesraw(d)

> I don't understand why this is better than my code. It's a little 
> different - you get all the data, then write all the data; I get a 
> little, write a little - but since you are writing one datum at a time 
> in both cases, I don't know why it would make much difference.
> 

Sorry, I missed to insert the time.sleep(0.1) I used in my original while loop 
into the example above.
The reason for using time.sleep() is that I need to avoid lots of loops over an 
empty buffer.
The amount of time until the producer thread reads a new data fragment into the 
buffer may
be significant, depending on the fragment size requested by the driver (e.g my 
fm801 card
wants fragments of 16384 bytes which is about 0.09 audio seconds). On the other 
hand the
buffer may contain hundreds of kB of data if other processes cause a lot of 
disk I/O.

> You should be able to take the try/except out of your version, since 
> this code is the only consumer from the Queue, if queue.empty() is 
> false, queue.get() should succeed.
> 

Not if I call it with block=0; if I understand the docs correctly the queue 
will raise a Queue.Empty exception
if the queue is currently locked by another thread. 

> In the vu meter thread I can see you might want to consume a minimum 
> length of data but again that doesn't seem so hard.
> 
> OTOH your latest code looks OK too, this was just a suggestion.
> 

It was a good suggestion, I never looked at the Queue class before, and it's 
definitely good to know about it.
In my special case here, your other suggestion of using Condition() seems to 
allow me easier handling of
my buffers, though. Another part of my code I did not post here that is 
executed when the recording
is stopped (i.e. self.recording is set to 0) also seems to be easier to 
implement with the Condition technique.

> > All Tkinter access must be from the main thread (or, more precisely,
> the thread that called mainloop).
> 
> OK, yes. What this means is that any code that changes the state of the 
> GUI should be called from the main thread. In your case, that means that 
> the thread that updates the vu meter must be the main thread. If you are 
> calling get_peaks() from a scheduled Tkinter task (scheduled with 
> after() or after_idle()) you will be fine.
> 
Yes, that's what I am doing. I think I just was confused because I did not 
understand what the Condition class does.
Now I think I see clearer, thanks for all your help.

Michael



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing instance attributes in different threads

2006-02-09 Thread Michael Lange
On Wed, 08 Feb 2006 18:14:14 -0500
Kent Johnson <[EMAIL PROTECTED]> wrote:

> > Sorry, I missed to insert the time.sleep(0.1) I used in my original while 
> > loop into the example above.
> > The reason for using time.sleep() is that I need to avoid lots of loops 
> > over an empty buffer.
> > The amount of time until the producer thread reads a new data fragment into 
> > the buffer may
> > be significant, depending on the fragment size requested by the driver (e.g 
> > my fm801 card
> > wants fragments of 16384 bytes which is about 0.09 audio seconds). On the 
> > other hand the
> > buffer may contain hundreds of kB of data if other processes cause a lot of 
> > disk I/O.
> 
> Using Queue.get() will do this for you automatically. If there is no 
> data it will block until something is added to the queue and you avoid a 
>   polling loop. If there is data it will return it quickly.
> > 

> > Not if I call it with block=0; if I understand the docs correctly the queue 
> > will raise a Queue.Empty exception
> > if the queue is currently locked by another thread. 
> 
> No, the block flag controls whether the call will wait until something 
> is in the queue or return immediately. The call to Queue.get() will 
> always block waiting for the lock that controls access to the Queue; it 
> can't even tell if the Queue is empty until it gets this lock.
> 

Ah , then I misunderstood what the docs meant with "return an item if one is 
immediately available, else raise the Empty exception".
I thought "immediately available" means the Queue is currently not locked by 
another thread.

Thanks again

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] G'day

2006-02-15 Thread Michael Lange
On Wed, 15 Feb 2006 22:05:39 +1100
"John Connors" <[EMAIL PROTECTED]> wrote:

> G'day, I'm new to Python and new to the list and just thought I'd say a quick 
> hello before asking my 1st dumb question. My name is John and I live in 
> Australia,  I've been using computers since about 1983. I haven't done any 
> programming since the commodore 64 basic days, I was fairly proficient with 
> basic so I'm hoping I can pick up python without too much grief. I'm running 
> Fedora Core 4 and using Python 2.4.1. My 1st dumb question: I have a copy of 
> Teach Yourself Python in 24 Hours, printed in 2000 so I guess it's virtually 
> usless but i was hoping to learn some of the basics from it. There is a small 
> bit of code near the beginning... print "Hello, World!"print ' 'Goodbye, 
> World!" which returns a syntax error for the 2nd line. I thought it was a 
> typo and changed it to print "Goodbye, World!".  This would be fine except 
> further on the book there is similar syntax in some of the longer scripts. My 
> guess is that syntax was ok for an older version of Python that book was writ!
 ten for.  I would like to know what the correct code should be. John

Hi John,

I don't think the book is completely useless, it just misses the features added 
to python since 1.5.2;
it was my first book, too, and I think it's still fine to learn the basics.
I don't have it at hand right now, so I cannot look for your example, and mine 
is a german copy, so it probably
won't have the same typo. If the code example looks like:

print "Hello world"
print ''Goodbye world"

it's a typo.
It is just a guess, maybe the example later in the book looks rather like:

print 'I say "Hello world"'
or
print "You say 'Goodbye world'"
?
In python you can use both single (') or double (") quotes to delimit a string, 
but you need to use the same
character both at the beginning and the end of the string. The character that 
is not used to delimit the string
can be used inside the string.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter, Frame and Canvas question.

2006-02-24 Thread Michael Lange
On Thu, 23 Feb 2006 11:26:44 -0600
Hugo González Monteverde <[EMAIL PROTECTED]> wrote:

> Hi all,
> 
> I'm running into trouble displaying some Tkinter Canvases, they keep a 
> border between themselves and there's no way I can have them display 
> without a grey gap between them.
> 
> I've narrowed the problem to the following example. I've tried all kind 
> of padding and border parameter to the Frame's pack() method and the 
> Canvas' pack() method.
> 
> Is there something I'm missing or plainly not understanding? I'd like to 
>   display canvases one next to the other without some kind of background 
> showing throug.
> 
> Thanks for taking a look, here's the example:
> 
> ===
> 
> import Tkinter
> from Tkconstants import *
> 
> class App(Tkinter.Frame):
>  def __init__(self, master=None):
>  Tkinter.Frame.__init__(self, master)
>  self.pack(pady=0, ipady=0)
>  canvas1 = Tkinter.Canvas(self, background='#00', borderwidth=0)
>  canvas2 = Tkinter.Canvas(self, background='#00', borderwidth=0)
> 
>  canvas1.pack(pady=0)
>  canvas2.pack(pady=0)
> 
> if __name__ == '__main__':
>  myapp = App()
>  myapp.mainloop()

Hi Hugo,

try passing 

highlightthickness=0

to the Canvas constructor. The hightlightthickness is the width of the border 
around the widget
that becomes black when the widget has keyboard focus and it probably defaults 
to 1. If you set highlightthickness
to 0 you should probably also set takefocus to False (if this is an option for 
you).

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python and unicode

2006-03-10 Thread Michael Lange
On Fri, 10 Mar 2006 08:55:35 +0100
Ferry Dave Jäckel <[EMAIL PROTECTED]> wrote:

> Hello list,
> 
> I try hard to understand python and unicode support, but don't get it 
> really.
> 
> What I thought about this until yesterday :)
> If I write my script in unicode encoding and put the magic # -*- coding: 
> utf-8 -*- at its start, I can just use unicode everywhere without problems.
> Reading strings in different encodings, I have to decode them, specifying 
> there source encoding, and writing them in different encode i have to 
> encode them, giving the target encoding.
> 
> But I have problems with printing my strings with print >> sys.stderr, 
> mystring. I get "ASCII codec encoding errors". I'm on linux with python2.4
> 
> My programming problem where I'm stumbling about this:
> I have an xml-file from OO.org writer (encoded in utf-8), and I parse this 
> with sax, getting some values from it. This data should go into a mysql db 
> (as utf-8, too). I think this works quite well, but debug printing gives 
> this errors.
> 
> What is the right way to handle unicode and maybe different encodings in 
> python?
> What encoding should be put into the header of the file, and when to use the 
> strings encode and decode methods? Are there modules (as maybe sax) which 
> require special treatment because of lack of full unicode support?
> In general I'd like to keep all strings as unicode in utf-8, and just 
> convert strings from/to other encodings upon input/output.
> 

Hi Dave,

you should be aware that utf-8 is *not* unicode, but just another encoding.
Look here for more details:

  http://www.joelonsoftware.com/articles/Unicode.html

I am not sure what happens in your program, but generally when converting a 
unicode
string into a byte string python assumes to use the ascii codec if no other 
codec
is explicitely specified, which seems to be what occurs.
In this case calling encode('utf-8') on the unicode string before processing it 
may help.

If you are using strings in different encodings it is probably the best to 
convert them
all into unicode objects after reading with decode() (however you need to know 
which codec
to use) and to use only unicode internally. However you are right, some modules 
may
not be unicode-proof (i don't know about sax though). You will have to encode 
these
strings again when calling these module's functions.

If your program is supposed to run on different systems it may help to know the 
encoding
the system uses if you want to read some files there; you can look at the top of
the IOBinding module in idlelib to see how to guess the system encoding.

I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Test If File System is mounted in Linux

2006-03-17 Thread Michael Lange
On Fri, 17 Mar 2006 00:36:35 -0700
fortezza-pyt <[EMAIL PROTECTED]> wrote:

> If there a semi-standard way to test if a file system has been mounted 
> or not using Python? In the Linux command line, I can type "mount" and 
> see all mounted file system, and then see if the one I am looking for is 
> in the list. While I could replicate this with
> Python, I am curious if there is an easier way.
> 

Hi Fortezza,

try os.path.ismount() .

HTH

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple way for i18n ?

2006-03-23 Thread Michael Lange
On Wed, 22 Mar 2006 17:41:14 +0100
"francois schnell" <[EMAIL PROTECTED]> wrote:

> Hello all,
> 
> I wish to translate a Python script from English to French. I've read the
> offical documentation (python.org doc) but I must admit that I'm lost now
> ...
> I've found some simple explanations here but I can't make it work:
> http://karrigell.sourceforge.net/en/internationalization.htm
> 
> Here's where I'm stuck:
> 
> Let's imagine my app is: myapp.py
> --
> import gettext
> _ = gettext.gettext
> 
> print _("hello friends")
> print _("Bye Bye")
> ---
> 
> Here are my folders on a windows box:
> 
> C:\myappfolder\
> ---\Translations\francais\LC_MESSAGES
> 
> My myapp.py is in myappfolder
> 
> In this folder I've used pygettext.py to produce a messages.pot file => I
> add the translation in it => I have a messages.po file.
> I then used msgfmt.py to produce messages.mo file.
> 
> I then copied messages.po and messages.mo in LC_MESSAGES folder
> C:\myappfolder\
> ---\Translations\francais\LC_MESSAGES
> 
> I now come back to myapp.py and add two lines:
> 
> ---
> import gettext
> _ = gettext.gettext
> 
> t=gettext.translation("messages","c:\myappfolder\Translations","francais")
> t.install()
> 
> print _("hello friends")
> print _("Bye Bye")
> ---
> 
> When I do that Python anwers:
> 
> >>>
> Traceback (most recent call last):
>   File "C:\myappfolder\myapp.py", line 4, in ?
> t=gettext.translation
> ("messages","c:\myappfolder\Translations","francais")
>   File "C:\Python24\lib\gettext.py", line 456, in translation
> raise IOError(ENOENT, 'No translation file found for domain', domain)
> IOError: [Errno 2] No translation file found for domain: 'messages'
> >>>
> 
Hi Francois,

not sure if it is different on windows, on linux I simply do:

  import gettext
  gettext.install(domain, localedir)

to install _() into my application's global namespace,
where localedir in your case was "c:\myappfolder\Translations".
The path that contains the french translation should be "..\fr\LC_MESSAGES" 
instead of "..\francais\LC_MESSAGES"
I think (at least that is true on linux).

I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple way for i18n ?

2006-03-24 Thread Michael Lange
On Thu, 23 Mar 2006 23:58:58 +0100
"francois schnell" <[EMAIL PROTECTED]> wrote:

> 
> Now I'd like to be able to change language without loging out, change
> language, log in.
> 
> Martelli says in his book that to set the default language for the app I
> just need to do:
> 
> >>> os.environ.setdefault('LANG', 'fr_FR')
> 
> and Python doesn't complain (but doesn't work) but if I then do:
> 
> >>> print locale.getdefaultlocale()
> 
> Python says : ('en_GB', 'utf-8')  # meaning that really couldn't work ?
> 
> How can I have my app in French even if I'm still in the GB version of
> Ubuntu (change the language for the app) ?
> 

Hi Francois,

I tried to do so with one of my apps (on Mandrake) and found that I have to 
change
the LANGUAGE environment variable, changing LANG had no effect on this.
>From the python gettext docs I found:

If languages is not given, then the following environment variables are 
searched: LANGUAGE, LC_ALL, LC_MESSAGES, and LANG.

So it looks like the easiest may be to do

$ LANGUAGE=en_GB

in the shell before you start your app.

> I've also tried the "translation" way instead of the "install" way:
> 
> if I do:
> gettext.install("myapp", localedir) #it translates in French when I'm in the
> French Ubuntu
> but if I do instead: gettext.translation("myapp", localedir,
> languages="fr_FR") #with the same localedir which worked before
> =>
> Python complains:
> "gettext.translation("myapp", localedir, languages="fr_FR")
>   File "/usr/lib/python2.4/gettext.py", line 480, in translation
> raise IOError(ENOENT, 'No translation file found for domain', domain)
> IOError: [Errno 2] No translation file found for domain: 'myapp' "
> 
> I find it strange that "install" finds it but not "translation" (for the
> same localedir) ?
> 

I admit I nevered bothered to find out how to use gettext.translation() since 
gettext.install()
works that fine for me. Maybe you should set "languages" to "fr" instead of 
"fr_FR" (just a guess though)?

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ossaudiodev, pygtk, and flushing buffers

2006-05-11 Thread Michael Lange
On Wed, 10 May 2006 09:59:14 -0700
Matthew White <[EMAIL PROTECTED]> wrote:

> Hello All,
> 
> I'm writing a little audio player that plays voicemail files.  (I realize
> I'm reinventing the wheel, but it's still fun.)
> 
> The problem I'm experiencing is that I'm hearing the last fraction of
> the sound clip twice, either when the clip is done playing or when the
> program exits.
> 
> I've tried a few things and none of them have worked.  The bit of code
> that does the playing is here:
> 
> def play(self):
> if self.data_written < self.file_length:
> buf = self.data.read(self.buf_size)
> self.data_written += self.dsp.write(buf)
> self.percent_done = self.data_written / self.file_length
> 
> if self.data_written == self.file_length:
> self._reopen_audio_device()
> 
> This causes the second playing of the "last little bit" when the end of
> the file is reached.  When I don't include the second if statement, the
> "last little bit" gets played when the program exits.
> 
> According to the documentaiton, closing the audio device will flush any
> data in the sound card buffer.  I guess what I'm hearing is that buffered
> clip being flushed.  I've thought about using the mixer device to put the
> volume to zero, flush the buffer, then turning the volume back up again,
> but that seems like a hack.
> 

Hi Matthew,

you never explicitely close the audio device, except when calling 
self._reopen_audio_device().
According to the OSS programmer's guide 
(http://www.opensound.com/pguide/index.html ) this is generally considered bad 
practice,
because no other application will be able to access the audio device. Probably 
it is not guaranteed that the device's
buffers will be flushed until calling close(), too (maybe calling reset() also 
flushes the buffers, but after reset() you
should close and reopen the device anyway).
I have not tried it, but I think the effect you describe may depend on the 
driver in use.

Does it help if you change your play() method like this:

def play(self):
if self.data_written < self.file_length:
buf = self.data.read(self.buf_size)
self.data_written += self.dsp.write(buf)
self.percent_done = self.data_written / self.file_length
if self.data_written == self.file_length:
self.dsp.close()
# then reopen the device right before starting playback, probably from 
player.PlayerWindow.play()

? 

There may be a short delay between the call to self.dsp.close() and the actual 
stopping of playback,
(which can be avoided by calling self.dsp.reset() before self.dsp.close()), 
however this should not be a problem if you
play the file to the end, I think. 

I hope this helps

Michael




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with erros using subprocess module

2006-05-12 Thread Michael Lange
On Thu, 11 May 2006 10:59:19 -0700 (PDT)
Jerome Jabson <[EMAIL PROTECTED]> wrote:

> 
> Am I missing some module you are referencing with
> "types"?
> 

Hi Jerome,
 
that's right, try

   import types

first.

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] laying out a menu widget inside a frame

2006-05-12 Thread Michael Lange
On Thu, 11 May 2006 15:03:53 -0400 (EDT)
"Zubin Wadia" <[EMAIL PROTECTED]> wrote:

> Hello All,
> 
> from Tkinter import *
> 
> class App:
> #create a frame
> def __init__(self, master):
> frame = Frame(master, bg="LIGHTBLUE", relief=RIDGE, bd=3)
> frame.pack(side=TOP, ipadx=15, ipady=15, fill=X)
> 
> ##create dropdown menu
> 
> menubar = Menu(frame)
> 
> filemenu = Menu(menubar)
> menubar.add_cascade(label="File", menu=filemenu)
> filemenu.add_command(label="New")
> 
> root.config(menu=menubar) ##edit
> 
> root = Tk()
> root.minsize(100,100)
> app = App(root)
> root.mainloop()
> 
> This works great but I can't get the dropdown menu to layout in the frame
> widget instead of the root. I tried frame.config() in the ##edit line but
> I don't think there is a config method for the frame widget, it errors
> out.
> 

Hi Zubin,

there is a typo in your code, it should be

master.config(menu=menubar)

but this does not seem to be your problem?
If you just want the menu to be inside the "lightblue", "RIDGE" part of the 
window, try:

root.config(relief=RIDGE, bg="lightblue", bd=3)

and relief="flat", bg="lightblue" on the frame.

I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] laying out frames

2006-05-15 Thread Michael Lange
On Mon, 15 May 2006 15:42:48 -0400 (EDT)
"Zubin Wadia" <[EMAIL PROTECTED]> wrote:

> Hello Everyone,
> 
> Another basic question in regard to frame layouts with Tkinter.
> 
> I want to create a basic quadrant of frames but am not able to follow the
> logic to do so, whats the right way or an easier way to control layout of
> frames and wigets. A pixel approach would be nice (where by you can
> specify pixel locations for a frame or a widget to be located) instead of
> specifying arbitary location positions like LEFT, RIGHT, etc and things
> moving constantly when you add more widgets or resize windows.
> 

Hi Zubin,

there are three different geometry managers in Tkinter, pack(), grid() and 
place().
As you have noticed, pack() is very handy to use for simple gui layouts but 
more complex
ones may be hard to achieve.
grid() is more flexible than pack(), it lets you arrange widgets in row and 
columns, e.g.:

from Tkinter import *
root = Tk()
# define rows and columns that should expand on window resizing
root.grid_rowconfigure(1, weight=1)
root.grid_rowconfigure(2, weight=1)
root.grid_columnconfigure(0, weight=1)
Label(root, text='Label1', bg='white').grid(row=0, column=0, sticky='ew')
Label(root, text='Label2', bg='yellow').grid(row=0, column=1)
Label(root, text='Label3', bg='green').grid(row=0, column=2)
Label(root, text='Label4', bg='red').grid(row=1, column=0, columnspan=2, 
sticky='nsew')
Label(root, text='Label5', bg='blue').grid(row=2, column=0, columnspan=3, 
sticky='nsew')
root.mainloop()

place() is even much more flexible than grid(), but it is much more complex to 
use, too,
so I recommend to think twice if you really need its capabilities.
With place() you can define absolute or relative x ynd y coords of a widget in 
its container and
relative or absolute dimensions, e.g:

from Tkinter import *
root = Tk()
Label(root, text='Label1', bg='green').place(x=10, y=40, relwidth=0.5, 
relheight=0.3)
Label(root, text='Label2', bg='yellow').place(relx=0.1, rely=0.8, width=60, 
height=30)
root.mainloop()

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] laying out a menu widget inside a frame

2006-05-16 Thread Michael Lange
On Mon, 15 May 2006 18:47:16 -0400 (EDT)
"Zubin Wadia" <[EMAIL PROTECTED]> wrote:

Hi Zubin,

> root.config(relief=RIDGE, bg="lightblue", bd=3) doesn't seem to work

it works for me (linux), maybe a platform issue?

> I'm not sure if the menu() widget can be packed in a frame container??
> 

I don't think you can:

>>> m=Menu(frame)
>>> m.pack(side='top', fill='x')
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 1595, in pack_configure
self.tk.call(
TclError: can't pack ".135695884.135828540": it's a top-level window

It seems like the Pmw.MenuBar widget can do what you want:

>>> mb =Pmw.MenuBar(frame)
>>> mb.pack(side='top', fill='x')
>>> mb.addmenu('File', 'File')
>>> 

adds a menu bar to the Frame, so maybe you will want to have a look at Pmw.

I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] combo box

2006-06-07 Thread Michael Lange
On Tue, 06 Jun 2006 13:39:21 +0700
kakada <[EMAIL PROTECTED]> wrote:

> Dear Friends,
> 
> I am now working on GUI python (Tkinter).
> I want to use combobox as my widget, but I cannot find it in any document.
> 
> Does anybody have experience with that?
> 

There is no ComboBox widget in plain Tkinter.
Probably the easiest way to get one is to use Tix which is included in the 
windows python
distribution and should be available in any recent linux distro.

If you want to use Tix simply replace the import line

from Tkinter import *

with

from Tix import *

You then can use your Tknter widgets as usual, plus a nice set of extra widgets 
(ComboBox, NoteBook, DirTree etc.) .

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] abs beginner first project

2006-07-12 Thread Michael Lange
On Wed, 12 Jul 2006 06:48:44 -0500
Luke Paireepinart <[EMAIL PROTECTED]> wrote:

> For example, in Tkinter, you can bind buttons to function calls, but you 
> can't have buttons pass arguments to the functions.  So you have to 
> somehow make a separate function for each button, or do some weird 
> backend event handling stuff that you can look up  if you're really 
> interested.

BTW, that is not really true:

>>> from Tkinter import *
>>> def test(*args):
... print args
... 
>>> root = Tk()
>>> b = Button(root, text='Hi', command=lambda widget=b: test(widget))
>>> b.pack()

Now when you press the button, you get:

>>> (,)

>>>

so the callback actually "knows" which widget called it, and you could easily 
perform
different actions for several buttons.

I know that is not what this thread is about, I just could not resist...

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List Box binding

2006-07-19 Thread Michael Lange
On Wed, 19 Jul 2006 06:45:36 -0400
Kent Johnson <[EMAIL PROTECTED]> wrote:

> Joe Cox wrote:
> > I am using Tk and have a series of Radio buttons that I want to bind 
> > to it's own listbox for further selection.
> > I just don't get the point how to click the button and select the 
> > proper listbox I want it tied too.
> Do you mean you want clicking on the radio button to enable a listbox? 
> It sounds like you need to bind an event handler to clicks on the radio 
> button. Can you show us what you have done so far?
> 

Usually a set of Radiobuttons should share one variable, and this sounds like 
they
should also share one command, which might look like:

var = StringVar()
var.set('a')

def radio_command():
if var.get() == 'a':
# button with value 'a' selected
do_this()
elif var.get() == 'b':
# button with value 'b' selected
do_that()
(etc.)

radio_a = Radiobutton(parent, variable=var, value='a', command=radio_command)
radio_b = Radiobutton(parent, variable=var, value='b', command=radio_command)
(etc.)

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [tutor] how to get the fileextention?

2006-07-20 Thread Michael Lange
On Thu, 20 Jul 2006 11:19:46 +0300
[EMAIL PROTECTED] wrote:

> Hi,
> 
> is this the right (shortest) way to get the file extention
> (under MS WIN)?
> 
> 
> def getext(fname):
> ext = fname.split('.').pop()
> return ext
> 

Hi Emily,

for filename operations, you should have a look at the os.path module.
In your case

os.path.splitext(fname)[1]

should do the trick, or if you need to remove the leading period from the 
extension
(as in your example)

os.path.splitext(fname)[1][1:]
.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me make it look pretty!

2006-07-21 Thread Michael Lange
On Thu, 20 Jul 2006 20:16:58 +0100
"John CORRY" <[EMAIL PROTECTED]> wrote:

> Good evening all.
>  
> I am writing a program using python 2.4, glade 2 and pygtk.  It takes
> input from the user using textentry boxes.  The input should be a
> number.  When the user keys the data in, it automatically left
> justifies.  The function below, takes the input for four boxes and right
> justifies it by using an ugly, string format.  The boxes are 45
> characters big, so I use the len function to fit them into the box.  The
> code is below.
>  
> I am looking for a way to set the text entry up, so that there is a
> decimal point in the box regardless of what the user does and I am also
> looking for a way to keep the numbers right justified.
>  
> Any suggestions or comments as always are greatly appreciated.
>  

Hi John,

I don't know about gtk, but have made some experience validating the user input
in Tkinter Entries, so I can only try to give you some general advice.
First, the Tkinter.Entry has a configuration option "justify", so
entry.config(justify=RIGHT) would very simply solve the first problem; are
you sure the gtk entry box does not have something similar?
Second, I found validating (and especially "on-the-fly"-converting) user input
is always a very tricky thing. Usually when testing some "solution" that seemed
to work, I found that in some special cases the widget showed an completely 
unexpected
behavior. Generally it is safer not to restrict user input too much and do the 
validation
when the entry boxes' contents are actually needed; if it is not valid you can 
pop up
a message box that tells the user what to do. If you really need to perform 
"real time" validation,
make sure to test your widgets very carefully.
Again, I don't know about gtk, in Tkinter you can pass a "validatecommand" to 
the entry widget to which
you can pass the old and the new entry's contents,
that is called each time the user types something into the entry box. If gtk 
offers something similar,
you could start with something like:

# pseudo code
def validate(old, new):
x = text38.get_text()
if x in ('', '.'):
ok = 1
elif '.' in x:
try:
float(x)
ok = 1
except ValueError:
print '\a'#acoustic feedback, in Tkinter I would use bell() of 
course
ok = 0
else:
try:
int(x)
text38.set_text('.'+x)#don't know how this would actually look in 
gtk, I hope you know what I mean
ok = 1
except ValueError:
print '\a'
ok = 0
if not ok:
# the new text is not allowed, restore the old
text38.set_text(old)

I bet this kind of solution has its traps, too.
Maybe the best solution is a web search if someone else has already written 
such a widget.
A quick google search for "pygtk entry validation" for example lead me here:

http://www.astro.umass.edu/~dpopowich/python/ :

ValidatedEntry, a pygtk extension providing a validated Entry widget

ValidatedEntry is a subclass of gtk.Entry, providing validation of input based 
on programmable functions. Sample functions included in the package provide 
validation for integers, floats, non-empty strings, ISBN numbers, phone 
numbers, money and bounded values (e.g., integers in a range). A demo app is 
included in the package. The latest version, 1.0.4, can be downloaded here.

Good luck!

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] : finding out if the horizontal scrollbar on a Tix.CheckList is being used or not

2006-07-21 Thread Michael Lange
On Fri, 21 Jul 2006 03:02:30 -0400
Orri Ganel <[EMAIL PROTECTED]> wrote:

> Hello all,
> 
> I'm working on the GUI for my extended iTunes search, which allows 
> searches far beyond the native iTunes capability.  Once the search has 
> been completed, a window contining a Tix.CheckList with the resulting 
> tracks is displayed.  If anyone has any idea how to figure out whether 
> or not the horizontal scrollbar is visible (ie if the length of the 
> track name extends beyond the width of the CheckList) programmatically, 
> I'd be extremely grateful :-).
> 

Hi Orri,

how about check_list.hsb.get() ?
I think in case it is != (0.0, 1.0) the scrollbar should be visible.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] : finding out if the horizontal scrollbar on a Tix.CheckList is being used or not

2006-07-22 Thread Michael Lange
On Fri, 21 Jul 2006 15:01:30 -0400
Orri Ganel <[EMAIL PROTECTED]> wrote:

> As a follow up to my last email, I think the issue is more that the 
> display doesn't update before the command associated with the "search" 
> button has finished processing, so any attempts to get data about the 
> display from within the method are fruitless since the display hasn't 
> changed yet.  I am well and truly stumped.  I have no idea how to get 
> around this.  

Calling update_idletasks() from within this method before quering diplay data
should do the trick.

The only way I can think of to do this without using the 
> display is figuring out the longest track name length and setting the 
> CheckList width to the pixel version of that.  Unfortunately, I don't 
> know the conversion for character units to pixels, either, so I'm still 
> stuck.
> 

I think the tkFont module has what you need:

>>> from Tkinter import *
>>> l=Label(text='hi')
>>> l.pack()
>>> import tkFont
>>> f=tkFont.Font(family='helvetica', size='-14')
>>> l.config(font=f)
>>> print f.measure(l['text'])
11
>>> print f.measure('blahblah')
54

I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Listbox selection

2006-08-04 Thread Michael Lange
Hi Joe,

On Thu, 3 Aug 2006 11:12:28 -0700
"Joe Cox" <[EMAIL PROTECTED]> wrote:

> I am still having a problem getting my listbox's binded to the radiobuttons.
> I am getting closer.
> 
> ###Assign each Radiobutton with its own listbox values, show one selected
> button and one listbox###
> 
> 
> 
> from Tkinter import *
> 
> root = Tk()
> 
> var = StringVar()
> var.set('a')
> 
> { 'Aluminum' : ['Wrought', 'Die cast'],
>'Steel'   : ['Low Carbon', 'Medium-high carbon','Alloy'] }
> 

Didn't you want to keep a reference to the dictionary?

> 
> def radio_command():
> if var.get() == 'a':
> # button with value 'a' selected
> listbox.insert('a') #here I am trying to put the string starting
> with 'Steel' in the listbox
> elif var.get() == 'b':
> # button with value 'b' selected
> listbox.insert('b')   #here I am trying to put the string starting
> with 'Aluminum' in the listbox
> 
> 
> 
> radio_a = Radiobutton(root,text="Steel", variable=var, value='a',
> command=radio_command).pack()

Are you aware that pack() returns None, so you actually assign None to all your
radio_* variables; if you want to keep access to the widgets you need to do:

radio_a = Radiobutton()
radio_a.pack()

> radio_b = Radiobutton(root,text="Aluminum", variable=var, value='b',
> command=radio_command).pack()
> radio_c = Radiobutton(root,text="Cast Iron", variable=var, value='c',
> command=radio_command).pack()
> radio_d = Radiobutton(root,text="Nickel", variable=var, value='d',
> command=radio_command).pack()
> radio_e = Radiobutton(root,text="Titaniuim", variable=var, value='e',
> command=radio_command).pack()
> 
> 
> listbox = Listbox(root)
> for item in ():
> listbox.insert(END, item)

The last two lines don't really seem to have much sense, if you want an empty 
Listbox,
just don't insert anything.

> listbox.pack(side=LEFT, fill=BOTH)
> 
> root.mainloop()
> 


I am not sure what your question is here, maybe you want to try something like 
(untested):

var = StringVar()
var.set('Steel')
listbox = Listbox(root)
listbox.pack(side=LEFT, fill=BOTH)

metals = {'Aluminum' : ['Wrought', 'Die cast'],
   'Steel'   : ['Low Carbon', 'Medium-high carbon','Alloy'] }

def radio_command():
listbox.delete(0, 'end')
for m in metals[var.get()]:
listbox.insert('end', m)

for metal in metals.keys():
# assuming that you don't need to keep references to all buttons
Radiobutton(root, text=metal, variable=var, value=metal, 
command=radio_command).pack()

# fill the listbox with initial values
radio_command()

I hope this helps

Michael



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multiple buttons, One callback (fwd)

2006-08-04 Thread Michael Lange
> -- Forwarded message --
> Date: Fri, 4 Aug 2006 09:32:48 -0700 (PDT)
> From: Michael Cochez <[EMAIL PROTECTED]>
> To: [EMAIL PROTECTED]
> Subject: Multiple buttons, One callback
> 
> Hi Danny,
> I've just been reading your reply on this subject at
> http://mail.python.org/pipermail/tutor/2005-September/041358.html
> about a year ago.
> I need something like this but also something more:
> I'm making an app with an interface that is going to
> look like in the added image. The "=" buttons are
> there to copy the contents of the previous lines to
> the current line.
> To make the buttons tried a lot of things but the
> problem is: the number of buttons is always different
> (one less as the number of day) so it can be none or
> 20 or something else. So i putted the creation in a
> for loop.
> But now the real problem: every button must have its
> own callback(because the linenumber is different) So
> my question is: how can I give each button its 'own'
> callback while only having one (the callbacks are all
> the same but with another value of linenumber. I added
> a piece of the code to show what i mean.

I would use a lambda for this, like:


def makeidentical(linenumber):

print "the linenumber is: %d" % (linenumber)


for day in datelist:

a=datelist.index(day)

if a>0:#on every line exept the first

identicalbutton=Button(frame2,text="=",command=lambda : 
makeidentical(a))

identicalbutton.grid(row=a+2,column=3,sticky=W)

frame2widgets.append(identicalbutton)


I hope this helps

Michael

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] i18n Encoding/Decoding issues

2006-08-10 Thread Michael Lange
Hi Jorge,


On Thu, 10 Aug 2006 13:32:10 +0100
"Jorge De Castro" <[EMAIL PROTECTED]> wrote:

(...)
> 
> Using unicode(body, 'latin-1').encode('utf-8') doesn't work either. Besides, 
> am I the only one to feel that if I want to encode something in UTF-8 it 
> doesn't feel intuitive to have to convert to latin-1 first and then encode?
> 

if the above does not work, it is because the original message is not
latin-1 encoded. unicode(body, 'latin-1') does not convert *to* latin-1, but
convert a latin-1 encoded string into unicode. This will obviously only work as
expected if the original string is actually latin-1.
In order to safely convert the message body into utf-8 you would have to find 
out
which encoding is used for the message and then do
unicode(body, original_encoding).encode('utf-8')

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Limiting Characters

2006-08-22 Thread Michael Lange
On Mon, 21 Aug 2006 13:19:54 -0400
"Marcus Dean Adams" <[EMAIL PROTECTED]> wrote:

> I_m fairly new to python, I_ve been dabbling in it for school and I have a
> question.  I_ve written a few programs using graphical windows with input
> boxes such as a stopwatch, temperature converter, etc.  I_ve always found a
> gui much prettier than command line.  Anyway, I have limited the size of the
> input boxes to the number of digits I wanted, but you can still put more
> digits than that in the box.  For example, the temperature converter input
> box is only 3 digits wide, however I can enter a 20 digit number if I want,
> it just only shows 3 digits at a time.  How can I actually limit the number
> of characters a user can enter, and not just the size of the input box?
> 
> 

Hi Marcus,

this depends of course on the toolkit you use.
If it is Tkinter, you can use the Entry widget's validatecommand, see:

http://mail.python.org/pipermail/tkinter-discuss/2006-August/000863.html

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter Icon Suse 10

2006-08-25 Thread Michael Lange
On Fri, 25 Aug 2006 15:14:49 -0400
"Alberto Troiano" <[EMAIL PROTECTED]> wrote:

> Hi everyone
> 
> It's been a long time since I left Python for .NET 2003, but then again I
> need it to make an app under Linux Suse 10 and I have a question
> I'm trying to put an icon to my window...
> Here is the code so far:
> 
> ###Start Code###
> 
> import Tkinter
> from Tkinter import *
> 
> root = Tk()
> root.iconbitmap("Change.ico")
> root.mainloop()
> 
> ###End Code###
> 
> It works great under Windows but on an Suse 10 Machine it complains about
> the file. Is this because the icon files are not the same as in Windows or
> should I be using another sentence to make it work?
> I know it's a dumb question but I'm out of practice and I couldn't find docs
> on Google (maybe I didn't look where I supposed to)
> Ups..I forgot, I'm using Python 2.4.1
> 

Hi Alberto,

you will have to use an xbm bitmap file for the iconbitmap, like

root.iconbitmap("@Change.xbm")

HTH

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] about tkinter

2006-09-05 Thread Michael Lange
On Tue, 5 Sep 2006 01:46:02 -0700
"linda.s" <[EMAIL PROTECTED]> wrote:

> >
> If I close the 'main' window, 'sub' window will be closed too. How can
> I close just one window?
> Linda

Hi Linda,

you can use a "hidden" root window, like this:

root = Tk()
root.withdraw()# hide the root window
top1 = Toplevel(root)
top2 = Toplevel(root)

Don't forget to define a method that exits the application when the last 
Toplevel
is being closed, because if you close both Toplevels the root window is still 
there and no
way to close it from the gui.
Here is a primitive to show how this might work:

def close_top1():
global top1
top1.destroy()
top1 = None
if top2 is None:
root.quit()

top1.protocol("WM_DELETE_WINDOW", close_top1)

( and the same for top2 of course)

This makes the close_top1() function be executed when the "X" in the window's 
upper right
corner is clicked.

I hope this helps.

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter GUI Grid Layout Manager

2006-09-21 Thread Michael Lange
On Wed, 20 Sep 2006 21:21:25 -0700 (PDT)
Johnston Jiaa <[EMAIL PROTECTED]> wrote:

> I am trying to get 3 buttons, equally separated along the top of the window.  
> How do I get them to all be the same size and how do I make them so that they 
> are equidistant to each other?
> 
> Along with those three buttons, I am trying to get a text box, near the 
> middle of the window.  Every time I attempt to put this in, it messes up the 
> position of the top buttons.  My code follows:
> 
> # Top "Mode" Widgets
> # Settings Button
> self.settings_bttn = Button(self, text = "Settings")
> self.settings_bttn.grid(row = 0, column = 2, columnspan = 2, sticky = EW)
> 
> # Statistics Button
> self.stats_bttn = Button(self, text = "Statistics")
> self.stats_bttn.grid(row = 0, column = 5, columnspan = 2, sticky = EW)
> 
> # Procrastinate Button
> self.proc_bttn = Button(self, text = "Procrastinate")
> self.proc_bttn.grid(row = 0, column = 8, columnspan = 2, sticky = EW)
> 
> 
> # Top-Mid Separator
> self.top_mid_sep_lbl = Label(self, text = 
> "--")
> self.top_mid_sep_lbl.grid(row = 1, column = 0, columnspan = 10, sticky = 
> EW)
> 
> 
> # Mid Assignments Widgets
> # Assignments Text Display
> self.assign_disp_txt = Text(self, width = 30, height = 18, wrap = WORD)
> self.assign_disp_txt.grid(row =3, column = 1, columnspan = 5, sticky = W)
> 
> 

Hi Johnston,

in order for the columns to actually expand you will have to use 
grid_columnconfigure(column, weight=1),
in order to make sure all buttons have the same size you can calculate the 
maximum size of all buttons and pass it to grid_columnconfigure() as minsize 
before
actually gridding them, like

max = 0
for b in (self.settings_bttn, self.stats_bttn, self.proc_bttn):
w = b.winfo_reqwidth()
if w > max:
max = w

self.grid_columnconfigure(0, weight=1, minsize=max)
# etc.
self.settings_bttn.grid(row = 0, column = 2, columnspan = 2, sticky = EW)

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] tkinter

2006-10-09 Thread Michael Lange
On Mon, 9 Oct 2006 14:00:26 +0100
"Alan Gauld" <[EMAIL PROTECTED]> wrote:

> > We try to build new software using python and tkinter. We would like 
> > to
> > enter some fields using grid style.
> 
> Based on the fact that you say:
> 
> > these. I hope I could explain I did not mean this grid which is 
> > using
> > instead of pack.
> 
> I assume you mean like a spreadsheet grid of cells?
> 
> > we wonder if there is already some classes or widgets to do this.
> 
> I'm not aware of such a control but its quite likely someone has
> built one. Try asking on the Tkinter mailing list, they are more
> likely to know.
> 

As far as I know the tktable widget (http://tktable.sourceforge.net) is a quite 
advanced
spreadsheet widget, and there is a Python wrapper module in the demos 
directory, I never used
it though.
Another option is the Tix.Grid, unfortunately there is only a partially 
implememted (and partially broken)
python interface included in the Python-2.5 Tix module.
For more functionality you can try the Tix.Grid wrapper I wrote a while ago 
(http://www.8ung.at/klappnase/TixGrid/TixGrid.html),
however it is not much tested and the tixGrid itself seems to be alpha or beta 
quality, some
methods do not seem to have any effect.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Seeking good resources for Tkinter

2006-10-09 Thread Michael Lange
On Mon, 9 Oct 2006 22:04:17 +0100
"Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote:

> Hi folks,
> 
> I want to learn the GUI programming in Python. Can you suggest some nice web
> resources as well as books to start.
> 
> Thanks in anticipation.
> 

Hi Asrar,

for Tkinter a good place to start is the wiki:

http://tkinter.unpy.net/wiki/

Several Tkinter books are mentioned here:

http://tkinter.unpy.net/wiki/books

where John Grayson's "Python and Tkinter programming" is (although it is a 
little outdated)
still the ultimate resource.
For a start the Tkinter reference from New Mexico Tech 
(http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html)
and Frederik Lundh's book 
(http://www.pythonware.com/library/tkinter/introduction/) are good, too (and 
they are free).

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me with this Tkinter code

2006-10-11 Thread Michael Lange
On Tue, 10 Oct 2006 23:32:57 +0100
"Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote:

> The error message is as under:
> 
> 
> *Microsoft Visual C++ Runtime Library*
> 
> * Runtime Error!
>  Program: C:\python\Lib\site-packages\pythonwin\Pythonwin.exe*
> 
> * This application has requested the Runtime to terminate it in an unusual
> way. Please contact the application's support team for more inforamtion.*
> Any idea??? what is this and how can it be fixed???
> 

If you run a Tkinter program from IDLE you should not call mainloop(), as Alan 
pointed
out before, you try to run a new mainloop inside the already existing one which
confuses Tk (at least this was true for the version of IDLE i had used).

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] an alternative to shutil.move()?

2006-10-16 Thread Michael Lange
On Mon, 16 Oct 2006 01:16:19 +0200
Alfonso <[EMAIL PROTECTED]> wrote:

> Is there an alternative in python to use shutil.move()?
> 
> It copies the files and then removes the source file insted of just 
> moving directly the file (don't know much about file systems, but I 
> suppose that when you move using the shell, if both source and 
> destination are in the same partition, it's just a matter of changing 
> the entries in the file allocation table). Copying the entire file, 
> specially with big files is very slow, and I think that it makes an 
> unnecesary use of the hard drive and system resources, when both source 
> file and destination are on the same partition...
> 

Try os.rename(old, new)

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to get the width of teh button widget..??

2006-10-20 Thread Michael Lange
On Fri, 20 Oct 2006 11:55:10 +0100
"Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote:

> Folks,
> 
> Sorry for asking you such a trivial question.!!! But i want to size up all
> the buttons with the same size as the largest one in the interface.. And
> thats why I am asking this question..
> 

Hi Asrarahmed,

in case you use Tkinter, something like this should do the trick (untested):

b1 = Button(master, text='Hi')
b1.grid(row=0, column=0, sticky='ew')
b2 = Button(master, text='Good-bye')
b2.grid(row=0, column=1, sticky='ew')

maxwidth = 0
for button in (b1, b2):
w = button.winfo_reqwidth()
if w > maxwidth:
maxwidth = w

master.grid_columnconfigure(0, minsize=maxwidth)
master.grid_columnconfigure(1, minsize=maxwidth)

or, if this is an option for you, use a Pmw.ButtonBox and call its 
alignbuttons() method.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PyAlsaAudio with Multiple Sound Cards?

2006-10-21 Thread Michael Lange
On Fri, 20 Oct 2006 18:13:04 -0400
"Rick Sterling" <[EMAIL PROTECTED]> wrote:

> 
> Hi.
> 
> I am pretty new to Python, but am trying to get up to speed so I move over 
> to Python from Perl.  One progam I wrote in Perl I am trying to re-write in 
> Python. It controls the mixer settings on my sound card.  I managed to 
> rewrite most of it by borrowing and stealing from the mixertest.py included 
> with PyAlsaAudio.
> 
> I haven't been able to figure out on thing however.  I know that normally 
> when you assign the mixer with:
> 
> mixer = alsaaudio.Mixer("Master")
> 
> It seems to use the first card in the system.  My system has two sound 
> cards, and I can't figure out how to access the second card.  Digging around 
> online I found the following syntax:
> 
> mixdev = alsaaudio.Mixer(mixer, id, device)
> 
> I don't know what values it expects for id and device.  I have tried using 0 
> for the id and using "hw:1" for the device to no avail.  I am sure it is 
> something simple, but after trying many different things I still haven't 
> been able to figure out how to access my second sound card.
> 

Hi Rick,

isn't there any documentation for pyalsaaudio? If no, maybe you would be better 
off
using ossaudiodev, which works well with ALSA, too.
For the device question, I guess they might want something like 
device=/dev/snd/hwC0D0
or however these device files are named on your system.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple calculator

2006-11-01 Thread Michael Lange
Hi Joe,

On Tue, 31 Oct 2006 18:37:27 -0800
"Joe Cox" <[EMAIL PROTECTED]> wrote:

> I found this simple calculator on the web:
> 
> from Tkinter import *
> from math import *
> ###http://sunsite.uakom.sk/sunworldonline/swol-02-1998/swol-02-python.htmlBy
> Cameron Laird and Kathryn Soraiz...Getting Started with Python###
> 
> def evaluate(event):
> label['text'] = "Result:  " + str(eval(expression.get()))
> 
> frame = Frame(None)
> 
> entry = Entry(frame)
> entry['textvariable'] = expression = StringVar()
> entry.bind("", evaluate)
> 
> label = Label(frame)
> 
> button = Button(frame, text = "Submit", command = evaluate)
> 
> frame.pack()
> entry.pack()
> label.pack()
> button.pack()
> frame.mainloop()
> 
> I get this:
> 
> >>> Traceback (most recent call last):
>   File
> "D:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
> line 310, in RunScript
> exec codeObject in __main__.__dict__
>   File "D:\Python24\Calculator\Calc.py", line 12, in ?
> entry.bind("", evaluate)
>   File "D:\Python24\lib\lib-tk\Tkinter.py", line 933, in bind
> return self._bind(('bind', self._w), sequence, func, add)
>   File "D:\Python24\lib\lib-tk\Tkinter.py", line 888, in _bind
> self.tk.call(what + (sequence, cmd))
> TclError: no events specified in binding
> 

this code seems to be quite old, so I guess that the line

entry.bind("", evaluate)

used to be legal in older version of Tk. I don't know what it is supposed
to do, though. Maybe there was some default event defined for such cases.
In today's Tk you need to specify an event sequence the callback should be 
bound to, like

entry.bind("", evaluate)

This does not work either, because you will get a syntax error on "incomplete"
expressions like "3*" when trying to type in "3*3" ,
so the evaluate() callback will have to catch this syntax error:

def evaluate(event):
try:
label['text'] = "Result:  " + str(eval(expression.get()))
except SyntaxError:
pass

This still does not work, when you press the "submit" button you get:

Traceback (most recent call last):
  File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1345, in __call__
return self.func(*args)
TypeError: evaluate() takes exactly 1 argument (0 given)

so the constructor must be changed like:

   def evaluate(event=None):
  (...)

because the Tkinter.Button's "command" callback is called without any arguments
(again I don't know if this was different in old Tk versions).

With these changes at least the few simple examples I tried seem to work.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   >