Re: Tkinter or Python issue?

2005-10-19 Thread Eric Brunel
On Tue, 18 Oct 2005 22:30:33 -0400, Ron Provost <[EMAIL PROTECTED]> wrote:

> Hello,
>
> I'm using python 2.4.2 on Win XP Pro.  I'm trying to understand a behavior
> I'm seeing in some Tkinter code I have.  I've reduced my question to a small
> piece of code:
>
>
> #BEGIN CODE
> #
> import Tkinter as Tk
> import tkFont
>
> sampleText = """Here is a test string.  This is more text
> Here is a second line of text.  How much
> more can I type.  I can't think of anything else to type.
> """
>
> root = Tk.Tk( )
> t = Tk.Text( root )
> t.pack( )
>
> t.insert( Tk.END, sampleText )
>
> t.tag_config( 'AB', font=tkFont.Font( family='ariel', size=24,
> weight=tkFont.BOLD ) )
> t.tag_config( 'TBU', font=tkFont.Font( family='times', size=10,
> weight=tkFont.BOLD, underline=1 ) )

Here is what I think is happening:
- The first tag_config creates a font using tkFont.Font. At tcl level, this 
font is not known as an object as in Python, but just as a font name, which is 
a string. This name happens to be built using the internal identifier for the 
Python object.
- Once this tag_config is over, no Python variable references your tkFont.Font 
instance anymore. It is is fact still known at tcl level (via the font name), 
but Python doesn't know that. So the reference counter for your tkFont.Font 
instance falls to 0, and the object is discarded.
- The second tag_config seems to create a new font using tkFont.Font. 
Unfortunately, since the previous font has been discarded, the space occupied 
by this font is reused for the new font. So the new font happens to have the 
same internal identifier as the font object created by the first tkFont.Font. 
So its name is in fact the same as your previous font, and is registered as 
such at tcl level. So in fact, you didn't create a new font at tcl level, but 
modified the previous one.

All this actually happens by accident. If you add something allocating some 
memory between the two tag_config, you'll certainly see your code working. It 
works when I run it myself...

[snip]
> f1 = font=tkFont.Font( family='ariel', size=24, weight=tkFont.BOLD )
> f2 = font=tkFont.Font( family='times', size=10, weight=tkFont.BOLD,
> underline=1 )
> t.tag_config( 'AB', font=f1 )
> t.tag_config( 'TBU', font=f2 )

You should now see why it works here: your first tkFont.Font is remembered at 
Python level in a variable. So it is not discarded once the tag_config is over. 
So the second tkFont.Font is not allocated at the same location, so it doesn't 
have the same id, and it doesn't have the same name at tcl level. This is the 
general solution to the problem: keep your fonts in Python variables, so they 
won't be discarded and their names will never be re-used. You could have 
written:

f1 = font=tkFont.Font( family='ariel', size=24, weight=tkFont.BOLD )
t.tag_config( 'AB', font=f1 )
f2 = font=tkFont.Font( family='times', size=10, weight=tkFont.BOLD, underline=1 
)
t.tag_config( 'TBU', font=f2 )

This should still work. The order is not important; it's just the fact that 
your fonts are actually known at Python level which prevents Tkinter to reuse 
their name.

BTW, this is a variant of a well known problem biting newbies regularly, 
documented here:
http://tkinter.unpythonic.net/wiki/Images

It's basically the same problem for images: it does not suffice to reference an 
image at tcl level; it must also be referenced at Python level or it will be 
discarded by Python and you won't be able to use it in your widgets.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Set an environment variable

2005-10-20 Thread Eric Brunel
On 20 Oct 2005 01:58:44 -0700, the_crazy88 <[EMAIL PROTECTED]> wrote:

> Just use
> os.system("export PYTHONPATH = %s" %("your_pythonpath"))

... except it won't work: os.system will execute the command in a new process, 
so the environment variable change will only be visible in *this* process. 
Since you don't do anything else, the environment variable change will never be 
seen by anyone.

As for the OP's question, the short answer is "you can't": the Python 
interpreter will always be executed in a different process than the calling 
shell, and environment variable changes *never* impact the calling process on 
Unix.

The closest thing you can do is that:

-myScript.py--
print 'export MY_VARIABLE=value'
--

-myScript.sh--
python myScript.py > /tmp/chgvars.sh
. /tmp/chgvars.sh
--

This is quite ugly: you write the shell commands changing the environment 
variables to a file, then "source" this file in the calling shell. But this is 
probably the best way to do what you want.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Set an environment variable

2005-10-24 Thread Eric Brunel
On Fri, 21 Oct 2005 20:13:32 -, Grant Edwards <[EMAIL PROTECTED]> wrote:

> On 2005-10-21, Mike Meyer <[EMAIL PROTECTED]> wrote:
>> Grant Edwards <[EMAIL PROTECTED]> writes:
>>> My point: the OP wanted to know how to export an environment
>>> variable to a child process.  Either of the lines of code above
>>> will do that, so what's with all the shellular shenanigans?
>>
>> Actually, the OP didn't say he wanted to export a variable to a child
>> process. He said he wanted to know how to do the equivalent of "export
>> SYMBOL=value", which got intreprted as "setting a variable in the
>> parent shell."
>
> The only think you can export an environment variable to is a
> child process

Well, you know that, and I know that too. From my experience, many people 
don't...

> so I thought it obvious that was what he was
> doing with the "export" command example.

Well, when I first read the OP's message, I thought it was obvious he wanted to 
export the variable to the parent shell. Re-reading it, it was actually not so 
obvious, so my apologies for not having included an example using 
os.environment...
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write an API for a Python application?

2005-11-16 Thread Eric Brunel
On 16 Nov 2005 06:18:05 -0800, Paul Boddie <[EMAIL PROTECTED]> wrote:

> Gary Kshepitzki wrote:
>> I would like to create an API for a piece of Python code. The API is for use
>> by non Python code.
>> It should support interaction in both directions, both accessing functions
>> on the API and the ability for the API to raise events on its client.
>> What is the best way to do that?
>
> One technology that I used many years ago with Python, and which should
> still do the job is CORBA - at that time ILU, but I suppose the various
> other ORBs should also be as capable; certainly, ILU permitted
> callbacks from the server into the client. These days, you might want
> to look at omniORB, Fnorb and ORBit.
>
> Paul

I never saw any way to create callbacks from server to client with CORBA. How 
would you describe such a callback in the IDL file?

TIA
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write an API for a Python application?

2005-11-17 Thread Eric Brunel
On Wed, 16 Nov 2005 15:43:33 -0500, Mike Meyer <[EMAIL PROTECTED]> wrote:

> "Eric Brunel" <[EMAIL PROTECTED]> writes:
>> On 16 Nov 2005 06:18:05 -0800, Paul Boddie <[EMAIL PROTECTED]> wrote:
>>> One technology that I used many years ago with Python, and which should
>>> still do the job is CORBA - at that time ILU, but I suppose the various
>>> other ORBs should also be as capable; certainly, ILU permitted
>>> callbacks from the server into the client. These days, you might want
>>> to look at omniORB, Fnorb and ORBit.
>> I never saw any way to create callbacks from server to client with CORBA. 
>> How would you describe such a callback in the IDL file?
>
> It's OO, not functional. You pass an object to the server, and the
> server invokes methods on that object. In the IDL, you use the
> interface name as a type. I.e.:
>
>   interface Window {
>   ...
>   }
>  and in another interface:
>   WindowList  FindWindows(in Window name) ;

This is slowly drifting OT, but aren't the interfaces in the IDL implemented on 
the server, and not on the client? So passing an "interface instance" to a 
method will just make the server call itself, won't it? Or you have to turn 
your client into a server, which makes things a lot more complicated.

> And, FWIW, Fnorb hasn't been maintained for a while. It requires
> patching to run on recent versions of Python.

Back on-topic: it seems to run fine with Python 2.1. I don't know about later 
versions.
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cosmetic Tkinter question

2005-01-03 Thread Eric Brunel
Sean McIlroy wrote:
I've got a bunch of Frames, all packed into the root window with
side=TOP, and in each Frame I've got a Checkbutton packed with
side=LEFT. I expected the Checkbuttons to be flush with the left edge
of the window, but they're not, and it looks a little gross. How do I
get them to align?
The standard behaviour for frames is to adapt to their contents, and packing 
them with side=TOP without any other option will center them in their container.

So you have a few solutions to your problem:
- use the anchor option when packing the frames; setting anchor=W should do what 
you want
- use fill=X when packing the frames, as Harold said. This expands the frame to 
the whole width of its container, so this should align the check-buttons (if it 
doesn't work, add the option expand=1 to force the frame to be wider than its 
contents)

A silly question BTW: why do you use frames? If you have only check-buttons in 
them, you do not need them:

from Tkinter import *
root = Tk()
for i in range(0, 101, 20):
  b = Checkbutton(root, text='Option %s' % i)
  b.pack(side=TOP, anchor=W)
root.mainloop()
HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter zoom box

2005-01-03 Thread Eric Brunel
Philippe C. Martin wrote:
Hi,
I have the following convern: I have Tkinter applications that require a zoom 
box, and have had the following behavior without changing a line of code:

1) Mandrake 10.0/KDE 3.2/Python 2.3: no zoom box 
2) Mandrake 10.0/KDE 3.2/Python 2.4: zoom box shows
3) Mandrake 10.1/KDE 3.3/Python 2.4: no zoom box
4) Mandrake 10.1/Gnome 2.6/Python 2.4: zoom box shows

I know that sounds strange, but I am fairly certain this is what happened.
Is there a way to _force_ that zoom box ?
What do you call a "zoom box"? There's no widget with this name in "regular" 
Tkinter widgets, so it must be built with some other one... Which one is it? A 
button, a menubutton, or what else?

If you had some (simple) code showing the problem, that would also help a lot to 
understand what's going on...
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter zoom box = maximize/unmaximize box/button

2005-01-03 Thread Eric Brunel
Philippe C. Martin wrote:
By zoom box I meant one of the top right button/box one uses to 
maximize/unmaximize the current window.
This is a known problem in tcl/tk. See http://minilien.com/?7O2BAOm9t0
There is apparently a patch available. Latest tcl/tk versions apparently include 
the correction.

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter Puzzler

2005-01-07 Thread Eric Brunel
Tim Daneliuk wrote:
I am trying to initialize a menu in the following manner:
for entry in [("Up", KeyUpDir), ("Back", KeyBackDir), ("Home", 
KeyHomeDir), ("Startdir", KeyStartDir), ("Root", KeyRootDir)]:

func = entry[1]
UI.ShortBtn.menu.add_command(label=entry[0], command=lambda: 
func(None))

However, at runtime, each of the menu options binds to the *last* function
named in the list (KeyStartDir).
Explicitly loading each entry on its own line works fine:
UIcommand=lambda:KeyWHATEVERDir(None)
Any ideas why the first form does not fly?
This has nothing to do with Tkinter, but only with the way nested scopes work: 
to put it roughly, your "lambda: func(None)" only knows about the *name* func, 
which is not actually evaluated until the button is pressed. And when the button 
is pressed, the name func is bound to the last command in the loop.

To do what you want, change your code to:
for entry in (...):
  UI.ShortBtn.menu.add_command(
label=entry[0],
command=lambda func=entry[1]: func(None)
  )
This way, the value for the func parameter is evaluated when the function is 
defined and not when it is called.

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyChecker messages

2005-01-11 Thread Eric Brunel
Frans Englich wrote:
Hello,
I take PyChecker partly as an recommender of good coding practice, but I 
cannot make sense of some of the messages. For example:

runner.py:878: Function (main) has too many lines (201)
What does this mean? Cannot functions be large? Or is it simply an advice that 
functions should be small and simple?
This is an advice. You can set the number after which the warning is triggered 
via the maxLines option in your .pycheckrc file.

runner.py:200: Function (detectMimeType) has too many returns (11)
The function is simply a long "else-if" clause, branching out to different 
return statements. What's wrong? It's simply a "probably ugly code" advice?
Same thing; the corresponding option in .pycheckrc is maxReturns. Other options 
that may interest you are maxBranches, maxArgs, maxLocals and maxReferences. 
Please see PyChecker's documentation for more details.

A common message is these:
runner.py:41: Parameter (frame) not used
But I'm wondering if there's cases where this cannot be avoided. For example, 
this signal handler:

#---
def signalSilencer( signal, frame ):
"""
Dummy signal handler for avoiding ugly
tracebacks when the user presses CTRL+C.
"""
print "Received signal", str(signal) + ", exiting."
sys.exit(1)
#---
_must_ take two arguments; is there any way that I can make 'frame' go away?
See/set the unusedNames option in .pycheckrc; this is a list of names for which 
this kind of warnings are not triggered. If you set for example:

unusedNames = [ 'dummy' ]
in .pycheckrc and if you define your function with:
def signalSilencer(signal, dummy):
  ...
the warning will not be triggered.
BTW, if your signal handler is just here to catch Ctrl-C, you'd better do a 
try/except on KeyboardInterrupt...

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Python 2.1 / 2.3: xreadlines not working with codecs.open

2005-06-23 Thread Eric Brunel
Hi all,

I just found a problem in the xreadlines method/module when used with 
codecs.open: the codec specified in the open does not seem to be taken into 
account by xreadlines which also returns byte-strings instead of unicode 
strings.

For example, if a file foo.txt contains some text encoded in latin1:

>>> import codecs
>>> f = codecs.open('foo.txt', 'r', 'utf-8', 'replace')
>>> [l for l in f.xreadlines()]
['\xe9\xe0\xe7\xf9\n']

But:

>>> import codecs
>>> f = codecs.open('foo.txt', 'r', 'utf-8', 'replace')
>>> f.readlines()
[u'\ufffd\ufffd']

The characters in latin1 are correctly "dumped" with readlines, but are still 
in latin1 encoding in byte-strings with xreadlines.

I tested with Python 2.1 and 2.3 on Linux and Windows: same result (I haven't 
Python 2.4 installed here)

Can anybody confirm the problem? Is this a bug? I searched this usegroup and 
the known Python bugs, but the problem did not seem to be reported yet.

TIA
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Frame widget (title and geometry)

2005-06-24 Thread Eric Brunel
On Fri, 24 Jun 2005 10:21:01 -0400, Shankar Iyer ([EMAIL PROTECTED]) <[EMAIL 
PROTECTED]> wrote:

> Hi,
>
> I am still new to Python and Tkinter, so I apologize in advance if I do not
> word my question optimally.  I am trying to use a frame widget as the parent
> for other widgets.  There is a class with the header "class 
> classtitle(Frame):"
> in a script called classtitle.py.  Having imported classtitle, I create a 
> Frame
> widget within my gui using the command "w = Frame(self)."  Then, I grid this
> widget and issue the command "classinstance = classtitle.classtitle(w)."  When
> I attempt to execute this code, I receive an error claiming that w lacks
> geometry and title attributes that the code in classtitle.py attempts to 
> access.
> Does this mean that I cannot use a Frame widget as w in this situation?  
> Thanks
> for your help.

Please post a short script showing the behavior you get. Without this, we 
cannot help you much. The only thing I can tell you right now is that you 
obviously don't need to create a Frame via "w = Frame(self)": since you defined 
your classtitle class as a sub-class of frame, every instance of classtitle is 
also an instance of Frame, so you can use it as such:

>>> from Tkinter import *
>>>root = Tk()
>>> class MyClass(Frame):
... pass
...
>>> o = MyClass(root)
>>> o.grid()

just works. If you have to add anything in the constructor, do not forget to 
call the constructor for Frame in it, as in:

>>> class MyClass(Frame):
... def __init__(self, *args, **options):
... Frame.__init__(self, *args, **options)
... ## Other stuff...
...

If you do that, everything should be OK.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter radiobutton

2005-06-26 Thread Eric Brunel
On Sat, 25 Jun 2005 19:34:50 GMT, William Gill <[EMAIL PROTECTED]> wrote:

> I am placing radiobuttons in a 4 X 4 matrix (using loops) and keep
> references to them in a 2 dimensional list ( rBtns[r][c] ).  It works
> fine, and I can even make it so only one button per column can be
> selected, by assigning each column to an intVar.  In many languages a
> radiobutton has a property that can be directly read to see if it is
> selected on unselected.  Tkinter radiobuttons don't seem to have any
> such property.  Is there any way to look (via the script not the screen)
> to determine if it is selected?, or can this only be achieved via
> control variables?

The value and variable options for a radiobutton seem to be what you're looking 
for. Here is an example showing how to use them:


 from Tkinter import *

root = Tk()
v = StringVar()
Radiobutton(root, text='foo', value='foo', variable=v).pack()
Radiobutton(root, text='bar', value='bar', variable=v).pack()

def p():
   print v.get()

Button(root, command=p, text='Print').pack()

root.mainloop()


HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.1 / 2.3: xreadlines not working with codecs.open

2005-06-28 Thread Eric Brunel
On Thu, 23 Jun 2005 14:23:34 +0200, Eric Brunel <[EMAIL PROTECTED]> wrote:

> Hi all,
>
> I just found a problem in the xreadlines method/module when used with 
> codecs.open: the codec specified in the open does not seem to be taken into 
> account by xreadlines which also returns byte-strings instead of unicode 
> strings.
>
> For example, if a file foo.txt contains some text encoded in latin1:
>
>>>> import codecs
>>>> f = codecs.open('foo.txt', 'r', 'utf-8', 'replace')
>>>> [l for l in f.xreadlines()]
> ['\xe9\xe0\xe7\xf9\n']
>
> But:
>
>>>> import codecs
>>>> f = codecs.open('foo.txt', 'r', 'utf-8', 'replace')
>>>> f.readlines()
> [u'\ufffd\ufffd']
>
> The characters in latin1 are correctly "dumped" with readlines, but are still 
> in latin1 encoding in byte-strings with xreadlines.

Replying to myself. One more funny thing:

>>> import codecs, xreadlines
>>> f = codecs.open('foo.txt', 'r', 'utf-8', 'replace')
>>> [l for l in xreadlines.xreadlines(f)]
[u'\ufffd\ufffd']

So f.xreadlines does not work, but xreadlines.xreadlines(f) does. And this 
happens in Python 2.3, but also in Python 2.1, where the implementation for 
f.xreadlines() calls xreadlines.xreadlines(f) (?!?). Something's escaping me 
here... Reading the source didn't help.

At least, it does provide a workaround...
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: custom Tkinter ListBox selectMode

2005-07-03 Thread Eric Brunel
On Fri, 1 Jul 2005 20:19:20 -0400, Ron Provost <[EMAIL PROTECTED]> wrote:

> Hello,
>
> I've written a simple GUI which contains a listbox to hold some information.
> I've found that the click-selection schemes provided by Tkinter are
> insufficient for my needs.  Essentiall I need to impletement a custom
> selectMode.  As a first go, I've attempted to implement a click-on-click-off
> mode.  So for each entry, a click on that entry toggels its selection mode.
> A click on any entry does not affect the selection mode of any other entry.

What you describe is exactly the behavior you get when you set 
selectmode='multiple' on a list box; see:
http://www.tcl.tk/man/tcl8.3/TkCmd/listbox.htm#M57

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter Checkbutton initialization problem

2005-07-04 Thread Eric Brunel
On 03 Jul 2005 02:32:21 -0700, Paul Rubin  wrote:

> Python 2.4, Windows XP.  If I say:
>
> f = Frame()
> f.grid()
> v = IntVar()
> c = Checkbutton(f, text='hi there', variable=v)
> c.grid()
> f.mainloop()
>
> then the checkbutton should initially display as being checked.
> But it doesn't.  It shows up unchecked, even though v.get() returns 1.
> The select operation DOES update the display if there's no variable.

In tcl/tk, booleans are not integers. So using an IntVar to represent something 
which is basically a boolean will cause unexpected behaviors like the one 
you're experiencing here. Just do:

...
v = BooleanVar()
v.set(1)
...

and everything should be fine.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter grid layout

2005-07-06 Thread Eric Brunel
On Wed, 06 Jul 2005 11:44:55 +0100, Richard Lewis <[EMAIL PROTECTED]> wrote:

> Hi there,
>
> I've got a tree control in Tkinter (using the ESRF Tree module) but I
> can't get it to layout how I want it.
>
> I'd like to have it so that it streches north/south (anchored to the top
> and bottom), is of a fixed width and is anchored to the left hand side.
> Here's my code (its derived from one of the examples from the ESRF web
> site):
>
> class MainWindow(Frame):
[snip code]

First of all, it is not a good idea to make your so-called window inherit from 
Frame: a Frame is not a window in tk, but a generic container. Creating a Frame 
without a container window will automatically initialize the tk toolkit, 
creating a default window which will become the default parent for widgets 
where you don't specify one. According to the well-known "explicit is better 
than implicit" principle, if a MainWindow instance are actually the main window 
for your application, you'd really better inherit from the Tkinter class for 
the main window, which is Tk. Doing it this way has a lot of advantages over 
what you do; for example, if you later have to create a menu bar for your 
application, you will be able to do it in the MainWindow class. If you inherit 
from Frame, you won't get any access to the actual window, so you won't be able 
to create a menu in it.

This may seems to be unrelated to your problem, but it's not: by creating a 
Frame, you introduce one more unneeded container. So, in some code you don't 
show here, you have to insert the MainWindow instance into its parent window 
via a call to its pack or grid method. Since the code you show seems to be 
correct, I guess the problem is in this call to pack or grid, which probably 
does not tell the Frame how to behave when its parent window is resized, 
causing it to get the default behaviour, which is "do nothing at all".

To be sure this actually is the problem, try to replace the line:
Frame.__init__(self, master)
in MainWindow.__init__ by:
Frame.__init__(self, master, bg='blue', bd=2)
This way, a blue border will appear around the frame, allowing you to see how 
it grows.
Then run your application, and resize the window. You should see that the frame 
does not grow when the window grows, explaining why your tree deos not grow (in 
fact, it would grow if its container did; but its container doesn't...)

So you should either make your MainWindow class inherit from Tk, which 
eliminates the unneeded container and the problems it may cause, or make sure 
the pack or grid on your MainWindow instance actually tells the container to 
grow with its container. With pack, it's quite easy: just do 
myWindow.pack(fill=BOTH, expand=1). With grid, it's a bit more complicated, 
since you will have to configure the grid on the container.

But basically, my advice would be:
- Never make your windows inherit from Frame; make them inherit from Tk for the 
main window or from Toplevel for all other ones
- When you have resize problems, always check the whole widget hierarchy from 
the actual window down to the widget showing the problem. The cause is very 
often not on the widget itself, but on one of its containers.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter grid layout

2005-07-07 Thread Eric Brunel
On Wed, 06 Jul 2005 16:32:42 GMT, William Gill <[EMAIL PROTECTED]> wrote:

> Excuse me for intruding, but I followed examples and ended up with a
> similar architecture:
>
>  from Tkinter import *
>  class MyMain(Frame):
>  def __init__(self, master):
>  self.root = master
>  self.master=master
>  root = Tk()
>  app = MyMain(root)
>  app.master.title("Object Editor")
>  root.mainloop()
>
> Erick, are you saying it should be modified to something like :
>
>  from Tkinter import *
>  class MyMain(Tk):
>  ...
>  ...
>  app = MyMain()
>  app.title("My App")
>  app.mainloop()

Well, basically, that's what I'm saying; but your example is a bit better than 
the OP's.

Basically, the problem is that an instance of MyMain will just be some kind of 
graphical component that can be inserted into basically anything. So nothing 
prevents me to do for example:

root = Tk()
Label(root, text='This is my application').pack(side=TOP)
frm = Frame(root)
frm.pack(side=TOP)
app = MyMain(frm)
# You don't show where you pack or grid your MayMain instance in its
# parent, so I'm doing it explicitely here...
app.pack()
root.mainloop()

So the container for MyMain is a Tk instance in your example, and a Frame 
instance in mine. And it works, because it's basically the use case for Frame 
sub-classes: they can be pack'ed or grid'ed or place'd into anything.

So MyMain cannot make any assumption on its container (self.master in your 
first example), since it can be any valid container. So there are many things 
that you just can't do in MyMain, because you don't have a window. For example, 
you can't set the window title, or define a menu bar, since all these are 
defined via methods only available on windows, i.e. Tk or Toplevel instances.

Basically, you did this right, since you call app.master.title(...) in the main 
script, where you know that app.master is a Tk instance. But what can be the 
reason to do it *outside* MyMain? Isn't it the window itself that knows what 
title it should have?

So in your second version, you can do:

 from Tkinter import *
class MyMain(Tk):
   Tk.__init__(self)
   self.title("My App")
   ...
...
app = MyMain()
app.mainloop()

And this always works: since an instance of MyMain is an instance of Tk, you do 
have a window on which to call title. Note that this cannot be safely done in 
your first version, since self.master may not have a title method (see my 
example above).

So you should really stick to the following rules:
- If you write a class defining the main window for your application, make it 
inherit from Tkinter.Tk
- If you write a class defining a "secondary" window for your application, make 
it inherit from Tkinter.Toplevel
- If you write a class defining a graphical component that can be placed 
anywhere in a GUI, make it inherit from Tkinter.Frame
This is basically just a matter of good OO programming: you should choose the 
most accurate super-classes for the classes you define, or someday, you'll run 
into problems...

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32ui CreatePrintDialog

2005-07-18 Thread Eric Brunel
On Fri, 15 Jul 2005 18:08:35 -0400, Chris Lambacher <[EMAIL PROTECTED]> wrote:

> Hi,
>
> This question has come up a few times on the list with no one giving a public
> answer.  How do you use CreatePrintDialog from win32ui?
>
> About a year ago someone posted that:
> dlg = win32ui.CreatePrintDialog(1538)
> dlg.DoModal()
>
> will give you the window, but the ok button does not work.

Here is what I did to make it work:


import win32ui
 from pywin.mfc import window, dialog

class WindowsPrintDialog(window.Wnd):

   # Numbers for various items in the dialog
   PROPERTIES_BTN  = 1025
   PRINTER_NAME= 1139
   PRINT_TO_FILE   = 1040
   PRINT_ALL   = 1056
   PRINT_PAGES = 1058
   PRINT_SELECTION = 1057
   FIRST_PAGE  = 1152
   LAST_PAGE   = 1153
   FROM_TEXT   = 1089
   TO_TEXT = 1090
   NB_COPIES   = 1154

   def __init__(self):
 dlg =  = win32ui.CreatePrintDialog(1538)
 window.Wnd.__init__(self, printDlg)

   def OnInitDialog(self):
 ## Initialize dialog itself
 self._obj_.OnInitDialog()
 ## Activate all widgets
 for i in (WindowsPrintDialog.PRINT_ALL, WindowsPrintDialog.PRINT_PAGES,
   WindowsPrintDialog.FIRST_PAGE, WindowsPrintDialog.LAST_PAGE,
   WindowsPrintDialog.FROM_TEXT, WindowsPrintDialog.TO_TEXT,
   WindowsPrintDialog.PRINT_SELECTION):
   itm = self._obj_.GetDlgItem(i)
   itm.EnableWindow()
 ## Disable "Properties" button: it doesn't work...
 itm = self._obj_.GetDlgItem(WindowsPrintDialog.PROPERTIES_BTN)
 itm.EnableWindow(0)

   def OnOK(self):
 ## Call on dialog itself
 self._obj_.OnOK()
 self._obj_.UpdateData(1)
 ## Now you can get values entered in dialog via:
 ## - self.IsDlgButtonChecked() pour check-buttons
 ## - self.GetDlgItemText() for textual fields
 ## - self.GetDlgItemInt() for integer fields
 ## Then use these info. to create your printer DC; for example:
 printerName = self.GetDlgItemText(WindowsPrintDialog.PRINTER_NAME)
 dc = win32ui.CreateDC()
 dc.CreatePrinterDC(printerName)
 ## And so on...


Note that the printer properties button is explicitely disabled. If it's not, 
it seems to be working (it actually opens the printer properties dialog and all 
options can be modified without any error), but actually doesn't change a 
thing: the printing will be done with the printer default settings. If anybody 
has any idea on how this thing works, please let me know: I'm very interested.

> Diging into the source shows that the 1538 is being loaded as a template
> resource.  The MSDN documentation does not say anything about this being
> neccessary and in fact, other common dialogs provide this as an option, but
> not a requirement.  Why is this made a requirement?  If it was not made a
> requirement, would the dialog work?

I guess it would just be a matter of giving the default value 1538 to the idRes 
parameter in win32ui.CreatePrintDialog; AFAICT, this is always the id for the 
default print dialog. Can't figure out why it was not done in the first place...

> Unfortunately I can't play with this because I don't have Visual Studio.  I
> guess the logical next step, if the above worked, would be to add the
> GetPrinterDC() method (and maybe some others) so that we can do something
> useful with the dialog.

Yep. See above.

> Thanks,
> Chris

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: main window in tkinter app

2005-07-18 Thread Eric Brunel
On Mon, 18 Jul 2005 16:57:51 GMT, William Gill <[EMAIL PROTECTED]> wrote:

> A short while ago someone posted that(unlike the examples) you should
> use Tk as the base for your main window in tkinter apps, not Frame.   Thus :
>
>class MyMain(Frame):
>def __init__(self, master):
>self.root = master
>self.master=master
>self.createWidgets()
>def createWidgets():
> ...
>root = Tk()
>app = MyMain(root)
>app.master.title("Object Editor")
>root.mainloop()
>
> would become:
>
> class MyMain(Tk):
>...
>...
> app = MyMain()
> app.title("My App")
> app.mainloop()
>
> When I try converting to this approach I run into a problem with the
> __init__() method.  It appears to go into an infinite loop in
> tkinter.__getattr__().
[...]

I never ran into this problem. Can you please post a short script showing this 
behavior? Without knowing what you exactly do in your __init__ and 
createWidgets method, it's quite hard to figure out what happens...
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clearing a Text Widget

2005-07-25 Thread Eric Brunel
On Fri, 22 Jul 2005 23:42:52 -0400, Kane Bonnette <[EMAIL PROTECTED]> wrote:

> Kane Bonnette wrote:
>> Does anyone know how the clear the text from a Tkinter Text Widget? The
>> delete(0, END) trick that works for Entry widgets doesn't work for Text
>>
>> I get "0 is an invalid index" when i try to do so
>>
>> Thanks in advance
>
> In case anyone's wondering, you must use 0.0 instead of 0 on a Text Widget

In fact, you should use 1.0, which means line 1, column 0 (lines are numbered 
from 1 in text widgets).

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem (or even bug?) with Tkinter

2005-08-19 Thread Eric Brunel
On Fri, 19 Aug 2005 09:53:20 +0100, Matt Hammond <[EMAIL PROTECTED]> wrote:

> Here's a strange one in Tkinter that has me stumped:
> (I'm running python 2.4 on Suse Linux 9.3 64bit)
>
> I'm trying to make a set of Entry widgets with Label widgets to the left
> of each one, using the grid layout. If I make and grid the Label *before*
> the Entry then the Entry widget doesn't seem to work - it lets me put the
> cursor in it, but I can't type! See example code below.
>
> Is this just me doing something really really silly, or is there a bug
> here?

I tested with Python 2.1 on Mandrake Linux 8.0 and it works fine. My tcl/tk 
version is 8.3.4

Do you know the tcl/tk version you have? If you don't, you can get it via:

 from Tkinter import Tk()
root = Tk()
root.tk.eval('puts $tk_patchLevel')

I suspect a bug at tcl level. So can you execute the following tcl script:

---
entry .en1
grid .en1 -row 0 -column 1

label .lb1 -text "CAN WRITE ->"
grid .lb1 -row 0 -column 0


label .lb2 -text "CAN'T WRITE ->"
grid .lb2 -row 1 -column 0

entry .en2
grid .en2 -row 1 -column 1
---

It is exactly the same as yours in tcl syntax. To execute it, just save it to 
the file script.tcl and type in a shell:
wish script.tcl

(The "wish" command may include a version number, such as "wish8.4")

If the script above shows the same behaviour as your Python script, then it's 
not Tkinter's fault, but tk's. You should then report the bug to comp.lang.tcl.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a question about tkinter StringVars()

2005-08-24 Thread Eric Brunel
On Wed, 24 Aug 2005 15:07:27 GMT, William Gill <[EMAIL PROTECTED]> wrote:

> Working with tkinter, I have a createWidgets() method in a class.
> Within createWidgets() I create several StringVars() and
> assign them to the textvariable option of several widgets.
> Effectively my code structure is:
>
> def createWidgets(self):
>  ...
>  var = StringVar()
>  Entry(master,textvariable=var)
>  ...
>  ...
>
> Though 'var' would normally go out of scope when createWidgets
> completes, since the Entry and its reference do not go out of scope,
> only the name 'var' goes out of scope, not the StringVar object, Right?

Well, apparently not:


 from Tkinter import *

class MyStringVar(StringVar):
   def __del__(self):
 print "I'm dying!"

root = Tk()

def cw():
   var = MyStringVar()
   Entry(root, textvariable=var).pack()

cw()

root.mainloop()


Running this script actually prints "I'm dying!", so there is obviously no 
reference from the Entry widget to the variable object. The reference is 
actually kept at tcl level between an entry and the *tcl* variable, which knows 
nothing about the *Python* variable.

BTW, the whole purpose of StringVar's is to be kept so that the text for the 
entry can be retrieved or modified by another part of the program. So what can 
be the purpose of creating variables in a function or method and not keeping 
them anywhere else than a local variable?
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkraise oddity

2005-08-24 Thread Eric Brunel
On 24 Aug 2005 06:57:07 -0700, twd <[EMAIL PROTECTED]> wrote:

> I'm seeing some new and unexpected behaviour with tkinter + python2.4,
> in a gnome+linux environment. The code below used to work (and
> continues to work under windows). The intended behaviour is that a
> window is created the the first time the button is pushed, and then
> de-iconified and brought to the top whenever the button is pushed
> again. The behaviour I'm seeing is that the window is de-iconified (if
> iconified) correctly, but if already present on the screen, it is not
> raised.

What exactly do you expect? Do you want to raise the window above all other 
windows *in your application*, or above *all* other windows? I doubt tk can 
guarantee the latter, and this seems to be confirmed by the manuel for tk's 
raise command; cf. http://www.tcl.tk/man/tcl8.4/TkCmd/raise.htm

If you put the window with the button in front of the window with the label, 
and if pressing the button doesn't bring the window with the lable above the 
other, then it may be a bug. If it works, I guess it's just a matter of how the 
window managers interpret what "raising a window" means... But I'm no 
specialist here, so maybe someone else will confirm that.

[snip]
> from Tkinter import *
>
> t = None
>
> def cmd():
> global t
> if t:
> t.tkraise()
> t.deiconify()
> else:
> t = Toplevel()
> l = Label( t, text=" some text goes here ..." )
> l.pack()
>
> b =  Button(text="Raise",command=cmd)
> b.pack()
> b.mainloop()

(BTW, did you try to put the deiconify before the tkraise?)

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: file access dialog

2005-08-26 Thread Eric Brunel
On Fri, 26 Aug 2005 07:52:06 GMT, Wouter van Ooijen (www.voti.nl) <[EMAIL 
PROTECTED]> wrote:

> I have a tool in Python to which I want to add a small GUI. The tools
> currently runs everywhere PySerial is supported. I need a file-access
> dialog. What is the preffered way to to this? Is there a
> platform-independent file-access dialog available, or should I use the
> windows native version when running on windows (and how do I do that)?

Tkinter has a file acces dialog available with the same API on all platforms. 
It is also mapped to the standard dialog on Windows. Since Tkinter is certainly 
installed by default with Python, if a file dialog is everything you need, you 
probably don't have to look further.

To use the dialog, just do:

 from Tkinter import Tk
 from tkFileDialog import askopenfilename
## Tk needs a main window to work, so create one and hide it
root = Tk()
root.withdraw()
## Ask the file name
fileName = askopenfilename(filetypes=[('Python files', '*.py'), ('All files', 
'*')])
if fileName:
   print 'open', fileName
else:
   print 'cancelled'
## Over
root.destroy()

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TKinter, Entry objects and dynamic naming

2005-09-13 Thread Eric Brunel
On 13 Sep 2005 08:51:47 +0100, Ian Vincent <[EMAIL PROTECTED]> wrote:

> I am hoping someone may be able to help.
>
> I am using Python and TKinter to create a GUI program that will
> eventually create an XML file for a project I am working on. Now, the XML
> file contents changes depending on the type of file it represents - so I
> am dynamically creating the TK Entry boxes. The problem is, I want the
> variable assigned to each of these boxes to be dynamically assigned as
> well but I cannot see how to do this (if it is indeed possible).
>
> Example
>
> If the file the XML is to represent is a spreadsheet - I want the first
> entry box to be:
>
> spreadsheetField = StringVar()
> value = Entry(root, relief=SUNKEN, justify=LEFT,
> textvariable=spreadsheetField)
>
> however, if the file is a document - I want the first entry box to be:
>
> documentField = StringVar()
> value = Entry(root, relief=SUNKEN, justify=LEFT,
> textvariable=documentField)
>
> I have quite a few Entry boxes for each file type (about 10) and a lot of
> filetypes (over 80), so I do not want to have a custom function for each
> filetype if I can help it.

Your requirements are not very precise here. What do represent the entry 
fields? How do you build them? Are they always strings or can they be integers, 
or floats, or anything else? Do you have only entry fields or other widgets as 
well (check buttons, radio buttons, ...)? How do you know the format of the 
dialog you build?

> I have looked at using a dictionary but I cannot get my head around how
> to do that either.

This is the way I would go, but without answering the questions above, I won't 
be able to give you much advice. Supposing you have only entry fields accepting 
strings, a mapping file type -> field name -> StringVar may be a good solution.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter add_cascade option_add

2005-09-13 Thread Eric Brunel
On Tue, 13 Sep 2005 22:31:31 -0600, Bob Greschke <[EMAIL PROTECTED]> wrote:

> Root.option_add("*?*font", "Helvetica 12 bold")
>
> Want to get rid of the "font =":
> Widget.add_cascade(label = "File", menu = Fi, font = "Helvetica 12 bold")
>
> Does anyone know what ? should be to control the font of the cascade
> menus (the labels on the menu bar)?  "*Menu*font" handles the part that
> drops down, but I can't come up with the menu bar labels part.

option_add('*Menu.font', 'helvetica 12 bold') works for me for all sorts of 
menu items (cascade, commands, checkbuttons, whatever...).

What is your platform? There may be a few limitations for menu fonts on Windows.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter add_cascade option_add

2005-09-15 Thread Eric Brunel
On Wed, 14 Sep 2005 09:58:25 -0600, Bob Greschke <[EMAIL PROTECTED]> wrote:
> "Eric Brunel" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> On Tue, 13 Sep 2005 22:31:31 -0600, Bob Greschke <[EMAIL PROTECTED]> wrote:
>>
>>> Root.option_add("*?*font", "Helvetica 12 bold")
>>>
>>> Want to get rid of the "font =":
>>> Widget.add_cascade(label = "File", menu = Fi, font = "Helvetica 12 bold")
>>>
>>> Does anyone know what ? should be to control the font of the cascade
>>> menus (the labels on the menu bar)?  "*Menu*font" handles the part that
>>> drops down, but I can't come up with the menu bar labels part.
>>
>> option_add('*Menu.font', 'helvetica 12 bold') works for me for all sorts
>> of menu items (cascade, commands, checkbuttons, whatever...).
>>
>> What is your platform? There may be a few limitations for menu fonts on
>> Windows.
>>
> You can set the font for the labels on the menu bar, and you can set the
> font of the items in the drop down portion independently (except on Windows
> where you cannot control the font of the menu bar labels).  I just don't
> know how to set the font for the menu bar labels using an option_add
> command.
>
> ...option_add("*Menu*font", "Helvetica 12 bold")  works fine
> ...option_add("*Cascade*font", "Helvetica 12 bold")  does not,
>
> because I can't figure out what to put in for "Cascade".  There must be
> something, because I can use font = "Helvetica 12 bold" in the add_cascade
> command OK (see below).

I'm still not sure what your exact requirements are. Do you want to have a 
different font for the menu bar labels and the menu items and to set them via 
an option_add? If it is what you want, I don't think you can do it: the menus 
in the menu bar are just ordinary items for tk, and you can't control 
separately the different kind of menu items. In addition, you can have cascade 
menus in "regular" menus, like in:

--
 from Tkinter import *

root = Tk()

menuBar = Menu(root)
root.configure(menu=menuBar)

fileMenu = Menu(menuBar)
menuBar.add_cascade(label='File', menu=fileMenu)

openRecentMenu = Menu(fileMenu)
fileMenu.add_cascade(label='Open recent', menu=openRecentMenu)

openRecentMenu.add_command(label='foo.txt')
openRecentMenu.add_command(label='bar.txt')

fileMenu.add_command(label='Quit', command=root.quit)

root.mainloop()
--

All menu items get the options you defined via option_add('*Menu.*', ...), 
whether they are cascade or commands or whatever. Not doing so would end up in 
quite weird results.

To do what you seem to want, I'd create a custom class for menu bars like this:

--
 from Tkinter import *

class MyMenuBar(Menu):

   def __init__(self, master, **options):
 Menu.__init__(self, master, **options)
 master.configure(menu=self)

   def add_cascade(self, **options):
 if not options.has_key('font'):
   options['font'] = ('helvetica', 14, 'bold')
 Menu.add_cascade(self, **options)


root = Tk()

menuBar = MyMenuBar(root)

fileMenu = Menu(menuBar)
menuBar.add_cascade(label='File', menu=fileMenu)

openRecentMenu = Menu(fileMenu)
fileMenu.add_cascade(label='Open recent', menu=openRecentMenu)

openRecentMenu.add_command(label='foo.txt')
openRecentMenu.add_command(label='bar.txt')

fileMenu.add_command(label='Quit', command=root.quit)

root.mainloop()
--
This prevents you from putting the font=... option in all menus you create in 
your menu bar without the need for an option_add.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter menu bar problem

2005-02-09 Thread Eric Brunel
On Wed, 09 Feb 2005 11:35:40 GMT, John Pote <[EMAIL PROTECTED]>  
wrote:

I have a menu bar in a top level window as follows
[snip code]
Q1 Cannot find a way of changing the menu bars background colour. When
colour options are accepted they seem to be ignored. Is this a native  
look
and feel characteristic of write once run anywhere, not yet implemented  
or
possibly a bug.
Even if the tk man pages [1] don't mention it, it would not be surprising  
if the background option for menu items did not work on Windows, since  
many things seem to be "hardcoded" on this platform. I tested the  
following code on Linux; it works without problem and has the expected  
behaviour:

from Tkinter import *
root = Tk()
mb = Menu(root)
root.configure(menu=mb)
m = Menu(mb)
mb.add_cascade(label='Menu', menu=m)
m.add_command(label='Quit', command=root.quit, background='red')
If it is what you did and if it doesn't work on Windows, it is likely that  
the background option for menu items is not supported for this platform...

Q2 Some of the menu options in the config menu will not always be  
available
depending on program state. How can individual items in such a menu be
turned to faint gey to indicate their unavailability. Also a tick mark
against an item would be useful to show the currently selected option. Is
this possible?
To "grey out" a menu item:
parentMenu.entryconfigure(itemIndex, state=DISABLED)
To have menu items with a check-mark, use the add_checkbutton or  
add_radiobutton methods on the parent menu. Their use is similar to the  
Checkbutton and Radiobutton classes. See [1] for all available options.

[1] http://www.tcl.tk/man/tcl8.4/TkCmd/menu.htm
 - Eric Brunel -
--
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter menu bar problem

2005-02-09 Thread Eric Brunel
On Wed, 09 Feb 2005 11:35:40 GMT, John Pote <[EMAIL PROTECTED]>  
wrote:

I have a menu bar in a top level window as follows
[snip code]
Q1 Cannot find a way of changing the menu bars background colour. When
colour options are accepted they seem to be ignored. Is this a native  
look
and feel characteristic of write once run anywhere, not yet implemented  
or
possibly a bug.
Even if the tk man pages [1] don't mention it, it would not be surprising  
if the background option for menu items did not work on Windows, since  
many things seem to be "hardcoded" on this platform. I tested the  
following code on Linux; it works without problem and has the expected  
behaviour:

from Tkinter import *
root = Tk()
mb = Menu(root)
root.configure(menu=mb)
m = Menu(mb)
mb.add_cascade(label='Menu', menu=m)
m.add_command(label='Quit', command=root.quit, background='red')
If it is what you did and if it doesn't work on Windows, it is likely that  
the background option for menu items is not supported for this platform...

Q2 Some of the menu options in the config menu will not always be  
available
depending on program state. How can individual items in such a menu be
turned to faint gey to indicate their unavailability. Also a tick mark
against an item would be useful to show the currently selected option. Is
this possible?
To "grey out" a menu item:
parentMenu.entryconfigure(itemIndex, state=DISABLED)
To have menu items with a check-mark, use the add_checkbutton or  
add_radiobutton methods on the parent menu. Their use is similar to the  
Checkbutton and Radiobutton classes. See [1] for all available options.

[1] http://www.tcl.tk/man/tcl8.4/TkCmd/menu.htm
 - Eric Brunel -
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter option_add for menu radiobutton

2005-02-14 Thread Eric Brunel
On Sun, 13 Feb 2005 15:31:18 -0700, Bob Greschke <[EMAIL PROTECTED]> wrote:
[snip]
Root.option_add("*Radiobutton*selectColor", "black")
also works fine for regular radiobuttons.  What I can't
do is get the selectColor of the radiobutton's in the
menu to be black...the x.add_radiobutton() ones.
Root.option_add("*Menu.Radiobutton*selectColor", "black")...nope
Root.option_add("*Menu*selectColor", "black")...no change
Strange... The last one works for me (as it should - see 
http://www.tcl.tk/man/tcl8.4/TkCmd/menu.htm). What platform are you on and what 
is your tcl/tk version?
 - Eric Brunel -
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pmw.Balloon under Windows

2005-02-17 Thread Eric Brunel
On 16 Feb 2005 10:51:27 -0800, Aki Niimura <[EMAIL PROTECTED]> wrote:
[snip]
The software is working fine under Solaris 9.
However, when I tried it under Windows, it worked also fine but it spit
out
the following error message when exiting.
(from cygwin terminal)
% c:/Python23/python my_app.py
This application has requested the Runtime to terminate it in an
unusual way.
Please contact the application's support team for more information.
(the same error message is observed when I run the program directly in
Windows XP environment.)
//
[snip]
After painful investigation, I found Pmw.Balloon was causing this
problem
(because the problem went away if I commented out all balloon
statements).
Then I compared my usages and Pmw Balloon example because the example
didn't
cause this. (http://pmw.sourceforge.net/doc/Balloon.html)
I used the Pmw.Balloon quite a lot and never see any problem.
One question: what Python do you use? Is it a regular Windows Python distribution or the 
Python delivered with Cygwin? I know by experience that the Python in Cygwin has quite a 
lot of problems (mine crashes *very* often). If you don't already use a 
"regular" Windows distro, I think using one may solve your problem.
My questions are:
(1) Why my program is complaining and is there any workaround?
(2) What is the difference between using widget quit() method
and using Windows 'X' button.
- I know clicking Windows 'X' button generates an event but I thought
- ultimately it reached to the same routine to terminate the program.
I think the default binding for the 'X' button is to call destroy, not 
quit. Calling destroy on the main window is almost equivalent to calling quit, 
so maybe it can be a solution?
(3) Is it possible to fake clicking 'X' button?
I see a widget has event_generate() method.
Not that I know of. The event_generate method won't help here, because the 'X' button is 
handled by the window manager, and not by the application. It's a bit more complicated on Windows 
(as usual...) since there is no "real" window manager, but from the tk/Tkinter point of 
view, the result is the same: you can't "fake" a window manager event using 
event_generate.
BTW, what are the versions of Python, tk and Pmw you're using?
HTH a little...
 - Eric Brunel -
--
http://mail.python.org/mailman/listinfo/python-list


Re: Hello File.py

2005-02-18 Thread Eric Brunel
On 18 Feb 2005 00:17:01 -0800, Lith <[EMAIL PROTECTED]> wrote:
Here's a simple script, where I want to use a GUI to select a file.
(And eventually do something interesting with it.) Some problems
appear.
(1) Why does it call MenuOpen automatically?
Because this code:
menuFile.add_command(label='Open', command=MenuOpen(parent=root))
*calls* your MenuOpen function and assign its *returned value* to the 
command option in your menu. You need to pass the function itself, not call it. 
In fact, you did it correctly in:
menuFile.add_command(   label='Exit', command=sys.exit)
Here, you pass the sys.exit function. What you did above is as if you wrote:
menuFile.add_command(label='Exit', command=sys.exit())
With this line, sys.exit gets called and your application will terminate 
immediatly.
As for the line above, the general solution is to do:
menuFile.add_command(label='Open', command=lambda root=root: MenuOpen(root))
The 'lambda' stuff creates an anonymous function that will call your MenuOpen 
function when the menu is selected. For more details, please refer to the 
Python tutorial - 
http://docs.python.org/tut/node6.html#SECTION00675
But here, you don't even need that, since the root window is the default parent 
for all Tkinter dialogs, so doing:
menuFile.add_command(label='Open', command=MenuOpen)
is enough.
(2) Why won't it open when I choose the menu item?
Since you assigned the value returned by MenuOpen to the command option, 
and since MenuOpen doesn't return anything, there is no command associated to 
your menu and it does nothing at all.
(3) Python Cookbook gave me the sys.exit call, if I run it from IDLE it
gives me a traceback. Should I be using something else?
No you shouldn't; I don't know exactly how IDLE handles this, but the way 
sys.exit() terminates your program is actually by raising an exception. In 
regular usage, i.e. if you run your Python script from the command line, you'll 
never see this exception. Maybe IDLE treats it like any other one; any 
experience on this topic, anyone?
(4) Does tkFileDialog have any useful official documentation? The main
google results for it don't even give the possible parameters for the
function calls, or sample code showing how to use.
The best documentation you'll ever find is the tcl/tk one, e.g. here: 
http://www.tcl.tk/man/tcl8.4/TkCmd/contents.htm
The corresponding functions are tk_getOpenFile & tk_getSaveFile; you'll just 
have to convert the '-option value' syntax to 'option=value' to be able to use it 
via Tkinter.
(5) Is the 'parent = parent,' line just plain wrong?
It may look so, but it isn't: the parent at the left is the name for a 
keyword parameter for the function and the one at the right is the name of a 
variable. There is no possible confusion here, and this form is actually quite 
frequent.
Feel free to note any horrors you see.
Just one little thing: if you declare:
def MenuOpen(parent): ...
you'd better call it via:
MenuOpen(root)
and not:
MenuOpen(parent=root)
The 'parent=' stuff is unnecessary and may be confusing, since this syntax is 
often used only when you declare a function with keyword parameters like:
def f(arg, **kwdParams): ...
HTH
 - Eric Brunel -
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mixing Txinter and Pygame

2005-02-22 Thread Eric Brunel
On Tue, 22 Feb 2005 13:17:37 +1300, Tim Knauf <[EMAIL PROTECTED]> wrote:
Hi everyone, I'm glad to have found this list.
I've written a small script for my own use which, amongst other things,
captures mouse click information from a window containing an image. I
used Pygame to manage the image window, as it was the easiest way to
implement the functionality I needed. The surrounding interface windows
(there are two) are constructed with Tkinter.
Despite their unholy union, Pygame and Tkinter seem, generally, to
cooperate. I'm using this main loop to update one, then the other:
while 1:
gameLoop() # This function pumps the Pygame events and checks for
mouse and keyboard events
pygame.time.wait(10)
mainwin.update() # mainwin is an instance of Application class,
which is a child of Tkinter.frame
I have my interface set up so that when *any* of the windows' close
boxes are clicked, this function will be called:
# This portion of the Pygame loop calls doquit() when it gets a 'QUIT'
event...
def gameLoop():
pygame.event.pump()
for event in pygame.event.get():
if event.type == QUIT:
doquit()
# Etc.
# And this portion of the Tkinter interface sets the
WM_DELETE_WINDOW protocol to call doquit()
def createWidgets(self):
self.title("Region Management")
self.geometry('+830+8')
self.protocol("WM_DELETE_WINDOW", doquit)
# Etc.
# A temporary file is removed, and both Pygame and Tkinter are
instructed to quit
def doquit():
if os.access('recalc.tmp', os.F_OK):
os.remove('recalc.tmp')
pygame.quit()
mainwin.master.destroy()
Perhaps you've begun to see where I might be having problems. You see,
if I close the script by closing the Pygame window, I get this exception:
Traceback (most recent call last):
  File "D:\Development\Python\sludge helpers\addScreenRegion
helper.pyw", line 363, in ?
mainwin.update()
  File "C:\Python24\lib\lib-tk\Tkinter.py", line 859, in update
self.tk.call('update')
TclError: can't invoke "update" command:  application has been destroyed
Conversely, if I close the application by closing a Tkinter window, I
get this exception:
Traceback (most recent call last):
  File "D:\Development\Python\sludge helpers\addScreenRegion
helper.pyw", line 361, in ?
gameLoop()
  File "D:\Development\Python\sludge helpers\addScreenRegion
helper.pyw", line 203, in gameLoop
pygame.event.pump()
error: video system not initialized
Obviously, Pygame doesn't like Tkinter telling it to quit (when it's
trying to do something from its internal loop) and vice versa. Is there
a simple way that I can avoid getting these exceptions on exit, or have
I taken the wrong approach? Everything else appears to work fine. Please
do excuse me if this seems a silly question, as I'm fairly new to Python
and Pygame, and a total novice when it comes to Tkinter.
Well, since these are just exceptions, a simple try... except block would 
be fine, and you can even figure out the reason for the exception. Here is what 
I'd do:
- when you create your Tkinter main window, initialize an attribute that you'll 
use to see if the application has quit, e.g mainwin.hasQuit = False
- rewrite doquit this way:
def doquit():
if os.access('recalc.tmp', os.F_OK):
os.remove('recalc.tmp')
mainwin.hasQuit = True
pygame.quit()
- rewrite your custom event loop this way:
while 1:
gameLoop()
pygame.time.wait(10)
try:
  mainwin.update()
except TclError:
  if not mainwin.hasQuit:
raise
And: (1) your problem should go away; (2) the "real" exceptions you may get 
from Tkinter windows should not passed unnoticed.
On a side note, has anyone else found the Tkinter documentation awfully
obscure? I've found Python a joy to learn about, and Pygame's tutorials
are a lot of fun. I can't say the same for Tkinter, and found myself
having to do many Google searches before I uncovered information I could
put to use. Has anyone found any high-quality (online) documentation
that proves me wrong? :^)
Incomplete, but very useful: 
http://www.pythonware.com/library/tkinter/introduction/index.htm
But the best reference documentation you'll ever find is the tcl/tk man pages, 
on-line here: http://www.tcl.tk/man/tcl8.4/TkCmd/contents.htm
It unfortunately requires to know how to convert the tcl/tk syntax to Python/Tkinter syntax, but it 
is actually quite easy (mainly read "option=value" when the tcl/tk documentation says 
"-option value")
HTH
 - Eric Brunel -
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'modal dialogs' with Tkinter

2005-02-22 Thread Eric Brunel
On 22 Feb 2005 06:03:14 -0800, Sean McIlroy <[EMAIL PROTECTED]> wrote:
I'd like to have a function f such that, when f is invoked, a Tk
window w is presented in which a number of variables can be modified,
and f returns the values that are indicated by the relevant
menus/checkbuttons/etc at the time w gets closed. I've tried various
ways of doing this, without success. Any assistance would be greatly
appreciated.
Here are the necessary ritual incantations to create a modal dialog with 
Tkinter:
dlg = Toplevel()
# ... build the window ...
## Set the focus on dialog window (needed on Windows)
dlg.focus_set()
## Make sure events only go to our dialog
dlg.grab_set()
## Make sure dialog stays on top of its parent window (if needed)
dlg.transient(parentWdw)
## Display the window and wait for it to close
dlg.wait_window(dlg)
The callbacks for your "OK", "Cancel" or whatever buttons you want to use 
should then call dlg.destroy(). This will terminate the wait_window call and continue the execution 
of the code after it.
HTH
 - Eric Brunel -
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mixing Txinter and Pygame

2005-02-23 Thread Eric Brunel
On Wed, 23 Feb 2005 10:23:09 +1300, Tim Knauf <[EMAIL PROTECTED]> wrote:
[snip]
(When I'm starting on a language feature, though, I usually find I learn
a lot more from worked examples than from straight command information.
You may be interested in Tkinter best kept secret: the example scripts in 
the Demo/tkinter sub-directory of the Python source installation. It mainly 
covers the basics, but may be quite helpful when you start.
HTH
 - eric -
--
http://mail.python.org/mailman/listinfo/python-list


Re: Fonts

2005-02-28 Thread Eric Brunel
On Fri, 25 Feb 2005 11:00:41 -0600, phil <[EMAIL PROTECTED]> wrote:
I'm cpmpletely lost on fonts.
I'm using Tkinter
I do medarial = '-*-Arial-Bold-*-*--24-*-*-*-ISO8859-1"
or Courier or Fixed in various sizes.
Works great on my RH 7.2
But a small embedded system Im working on, nothing seems to work,
almost everything falls back to a fixed 12
You should be able to use a font specification like (family, size [, 
style]), e.g ('helvetica', 24, 'bold'). This is the most portable way of 
specifying fonts (X11 font names may not work on some systems).
You can get the available font families on your system as seen by Tkinter/tk 
with:
from Tkinter import *
import tkFont
root = Tk()
print tkFont.families()
BTW - according to http://www.tcl.tk/man/tcl8.4/TkCmd/font.htm#M25 - the font 
family names 'helvetica', 'times' and 'courier' are guaranteed to work anywhere 
with tk/Tkinter.
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Polling selections from a listbox (Tkinter)

2005-02-28 Thread Eric Brunel
On 26 Feb 2005 03:48:16 -0800, Harlin Seritt <[EMAIL PROTECTED]> wrote:
[snip]
Obviously when this starts up this is going to show selection #0 inside
the label box. How do I make sure that whatever is arbitrarily selected
ends up in the label box as this gui runs? I tried doing a bind:
self.listbox.bind("", self.changelabel)
This did not work as intended as the changelabel's text option only
showed what the selection index was BEFORE the event took place.
Bind on ;  is a synonym for , and 
when the button is pressed, the selection is not done yet.
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: scrollbar dependencies

2005-03-03 Thread Eric Brunel
On 3 Mar 2005 01:06:48 -0800, Marion <[EMAIL PROTECTED]> wrote:
Hello.
I am using Tkinter and Pmw.
I would like to build 2 canvases/frames that are scrollable together
horizontally, and independently vertically (so, the vertical
scrollbars should not be moved by the horizontal one).
So I built a Pmw.ScrolledFrame() containing the 2 canvases,
horizontally scrollable.
I'd not go that way: a Pmw.ScrolledFrame is not supposed to be used this 
way, and you may have great troubles making it work as you want...
[snip]
Is this possible or not ? If not, does somebody allready did that another way ?
Here is a solution using only pure-Tkinter:
--DualCanvas.py--
from Tkinter import *
## Main window
root = Tk()
root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(0, weight=1)
## First canvas
c1 = Canvas(root, width=200, height=100, bd=2, relief=SUNKEN,
  scrollregion=(0, 0, 500, 500))
c1.grid(row=0, column=0, sticky='nswe')
## Second canvas
c2 = Canvas(root, width=200, height=100, bd=2, relief=SUNKEN,
  scrollregion=(0, 0, 500, 500))
c2.grid(row=1, column=0, sticky='nswe')
## Special function scroll both canvases horizontally
def xscrollboth(*args):
  c1.xview(*args)
  c2.xview(*args)
## Horizontal scrollbar for both canvases
hScroll = Scrollbar(root, orient=HORIZONTAL, command=xscrollboth)
hScroll.grid(row=2, column=0, sticky='we')
## Vertical scrollbars
vScroll1 = Scrollbar(orient=VERTICAL, command=c1.yview)
vScroll1.grid(row=0, column=1, sticky='ns')
vScroll2 = Scrollbar(orient=VERTICAL, command=c2.yview)
vScroll2.grid(row=1, column=1, sticky='ns')
## Associate scrollbars to canvases
c1.configure(xscrollcommand=hScroll.set, yscrollcommand=vScroll1.set)
c2.configure(xscrollcommand=hScroll.set, yscrollcommand=vScroll2.set)
## Put a few things in canvases so that we see what's going on
c1.create_oval(80, 80, 120, 120, fill='red')
c1.create_oval(380, 80, 420, 120, fill='red')
c1.create_oval(80, 380, 120, 420, fill='red')
c1.create_oval(380, 380, 420, 420, fill='red')
c2.create_oval(80, 80, 120, 120, fill='blue')
c2.create_oval(380, 80, 420, 120, fill='blue')
c2.create_oval(80, 380, 120, 420, fill='blue')
c2.create_oval(380, 380, 420, 420, fill='blue')
## Go!
root.mainloop()
-
The "trick" is simply to create a function accepting the same arguments as the 
xview methods on canvases and forward these arguments to the xview methods of both canvases. 
You then pass this function to the command option of both scrollbars, and voilà. The link 
canvas -> scrollbar is done the usual way.
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: scrollbar dependencies

2005-03-03 Thread Eric Brunel
On 3 Mar 2005 02:38:59 -0800, Harlin Seritt <[EMAIL PROTECTED]> wrote:
Pardon a question I should already know the answer to, but what are the
*args in the:
def xscrollboth(*args):
   c1.xview(*args)
   c2.xview(*args)
Thanks,
Harlin
If your question is about the syntax, it's just the way of passing any 
number of arguments to a function as explained in:
http://docs.python.org/tut/node6.html#SECTION00673
If your question is about what will actually be passed in these arguments, the 
answer is simply: I don't know, and I don't care. That's why I used a *args: I 
just want to pass to the c1.xview and c2.xview methods exactly what was passed 
to my xscrollboth function. Since Python allows me to just pass the list of 
arguments unchanged, I happily do it.
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Setting default option values for Tkinter widgets

2005-03-03 Thread Eric Brunel
On 3 Mar 2005 03:02:48 -0800, Harlin Seritt <[EMAIL PROTECTED]> wrote:
There are certain options for Tkinter widgets that have default values
that I don't much care for (borderwidth, font come to mind) and
continuously change when I'm building interfaces. With a bit of
tweaking I have been able to give the widgets a look that rivals the
best of them. However, I get tired of doing this when I'm writing code
and would like a way that I could universally change them on my system.
I have tried to find where in the class files (Tkinter.py) that I can
change these and haven't been able to find them. Are there certain
lines in certain files/modules/classes that I can change the values for
these things like font, border, etc.?
tk allows to write your preffered options to an option file and to load it 
via the method option_readfile in your application.
For an example on how the options can be set, see:
http://mini.net/tcl/10424
The file should contain the arguments passed to "option add" commands.
For a reference on what options are available and how to specify them in an 
option file, see the tk manual pages here:
http://www.tcl.tk/man/tcl8.4/TkCmd/contents.htm
The name for the widget is usually the name of the corresponding Tkinter class; the name 
for the option is the second name found in the standard and widget-specific options 
sections in the man pages (named "Database name" in the section text). So for 
example, if you want to set the default select color for checkbuttons, you'll put in your 
option file a line:
*Checkbutton.selectColor: blue
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter Bitmap Newbie question

2005-03-15 Thread Eric Brunel
On Tue, 15 Mar 2005 00:00:57 GMT, Neil Hodgson <[EMAIL PROTECTED]> wrote:
Wim Goffin:
But just to make sure I'm on the right track,
- Is XBM the best way to for bitmaps? The ones I saw so far are all black
and white. Do they also exist in color?
   XPM is the version of XBM with colour.
- Is XBM also the best format for glyphs on the Windows platform? Or would
'Images' of a different format be nicer?
   It depends on what you want to do with icons. Do you want users to be
able to change icons? It is less likely Windows users will have tools
for manipulating XPM files. The only feature that you are likely to want
that is not available from XPM is multi-level transparency which is
available from PNG files.
   My generic advice without additional details of your project is that
PNG is the best format for icons displayed by your code. Icons used by
the operating system such as for applications should be in a format
supported by that OS: Windows prefers ICO files.
XPM, PNG and ICO files are not natively supported by tk/Tkinter. The only 
natively supported format is GIF, apparently mainly for historical reasons. 
There are tcl/tk extensions allowing to handle other image formats, but they 
may be weird to use from Tkinter (never tried them). If you want a portable 
application or if you just don't want to bother, you'd better use either XBM or 
GIF files for images.
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Tkinter) Adding delay to PopUpMsg

2005-03-18 Thread Eric Brunel
On 17 Mar 2005 23:40:20 -0800, Harlin Seritt <[EMAIL PROTECTED]> wrote:
I am working on making something called a PopMsg widget which is
actually identical to a Balloon widget from Pmw. Here is the code:
---code---
from Tkinter import *
import time
class PopMsg:
def showmsg(self, event):
for a in range(1000): pass
Very effective way to waste a lot of CPU time and to make your delay 
totally dependent on the CPU speed! Why don't you at least use time.sleep (that 
you use some lines below for no apparent reason BTW)?
[snip code]
My problem you'll notice is that I tried to put something of a 'delay'
that will allow the popup to show a few seconds after the cursor has
entered the targeted widget's space (in this case the button). That
works ok but I've found that while waiting I can't activate (or
'click') on the button until the PopMsg has shown up. Is there anything
I can do to solve this problem?
Use Tkinter widgets' "after" method; the binding on  on the widget 
should do something like:
self.widget.after(1000, self.showmsg)
This tells the tk main loop to wait 1000 milliseconds, then run the method. Note that no event will 
be passed, so you should make the "event" parameter in showmsg optional. This is an 
active wait, so all other events will be treated. If for some reason, you want to cancel the 
action, you can remember the result of the "after" method, and then pass it to the 
after_cancel method on the same widget:
x = self.widget.after(1000, self.showmsg)
...
self.widget.after_cancel(x)
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with tkinter mainloop

2004-11-30 Thread Eric Brunel
k2riddim wrote:
Hello,
I'm a beginner with Python and Tkinter development.
My application parse links in an html file. And I use Tkinter to
implement a GUI. This GUI has a button to launch the parse treatment,
and a status bar to show the state of the treatment.
I know that because of the mainloop, my tkinter application freeze
while my treatment isn't finished. That's why my status bar doesn't
update herself in real time.
I wanted to use the after or the after_idle function, but I don't
really understand why it doesn't work.
after and after_idle won't help you: the action you register in these methods 
are called only when the main loop gets back the control, and your problem is 
precisely that the main loop does not get it...

The method you're probably looking for is update_idletasks: it updates the 
display without getting any user event. There's another method called update, 
but this one does process user events, so it may call some of your code if such 
an event is pending. This is usually not what you want to do, except in some 
very rare cases.

Here is how it may look like in your code, along with a few remarks on your 
code:
My apps is build approximately like that :
---Gui.py---
class Gui(Frame):
Why do you inherit from Frame? A Tkinter Frame is a generic container widget; 
this is not a window. IMHO, you'd better inherit from Tk for your main window or 
from Toplevel for other windows. You'd also get better control on the actual 
window, since some of the methods available on Tk and Toplevel are not available 
on other widgets (e.g. geometry or protocol)

def __init__(self):
...
def launchTreatment(self):
   b = Treatment()
   self.after(b.treatment.parse)
This cannot be your code; the after methods takes two parameters: the number of 
milliseconds to wait before the action will be called and the action itself. You 
only provide the action here. But again, the after method won't help you to get 
what you want...

---Treatment.py---
class Treatment():
def __init__(self):
...
def parse(self):
   ...
   GUIinstance.status.set("state 1")
This is where the GUIinstance.update_idletasks() should go.
   ...
   GUIinstance.status.set("state 2")
Another GUIinstance.update_idletasks() here.

---Main.py---
#instanciation of classes
GUIinstance = Gui
Again, this cannot be your code, since you do not instantiate the class here. 
The correct line should be:

GUIinstance = Gui()
It is usually far better to post a working example demonstrating the problem you 
have instead of just extracting a few lines of your whole code. This will help 
people who are willing to help to understand exactly what is going on.

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.4 and Tkinter

2004-12-02 Thread Eric Brunel
Jeffrey Barish wrote:
[snip]
Here's what I get when I import Tkinter at a python prompt:
[EMAIL PROTECTED]:~$ python
Python 2.4 (#1, Nov 30 2004, 08:58:13)
[GCC 3.2.3 20030316 (Debian prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
import Tkinter
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/local/lib/python2.4/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
I tried make clean and make.  Same result.  Ah, now I see that the
output from make includes:
INFO: Can't locate Tcl/Tk libs and/or headers
Aren't the libs and headers included in Python-2.4.tgz?
On Windows, the Python distribution does include Tkinter and tcl/tk. It's 
different on Unices (including Linux): since tcl/tk is very often installed by 
default, it is not included in the Python distribution.

Have you looked for libraries / header files in /usr/lib and /usr/include? This 
is usually where they go when you install them with Linux. Since you mentionned 
you upgraded to Python 2.4, I assume you had a working installation of a 
previous Python version. So the tcl/tk libraries and header files must be there 
somewhere. Did you look at your Modules/Setup for the older Python? If Tkinter 
was working with this version, the setup for the _tkinter module should use the 
correct paths.

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.4 and Tkinter

2004-12-03 Thread Eric Brunel
Jeffrey Barish wrote:
[snip]
OK, I downloaded tcl8.4.8 and tk8.4.8.  They are now installed.  Back to
python2.4 make.  It now bombs at:
gcc -pthread -shared build/temp.linux-i686-2.4/_tkinter.o
build/temp.linux-i686-2.4/tkappinit.o -L/usr/X11R6/lib64
-L/usr/X11R6/lib -L/usr/local/lib -ltk8.4 -ltcl8.4 -lX11 -o
build/lib.linux-i686-2.4/_tkinter.so
*** WARNING: renaming "_tkinter" since importing it failed: libtk8.4.so:
cannot open shared object file: No such file or directory
running build_scripts
Here's what I don't get:
[EMAIL PROTECTED]:/tmp/Python-2.4# ls -l /usr/local/lib/libtk8.4.so
-rwxr-xr-x1 root staff  893866 2004-12-02
15:28 /usr/local/lib/libtk8.4.so
The library is there but gcc claims that it isn't.  Any suggestions?
Is /usr/local/lib in your LD_LIBRARY_PATH environment variable? It needs to be 
in the compiler options for the compilation phase, but then you have to put it 
in $LD_LIBRARY_PATH to be able to import the module.

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie alert !

2004-12-03 Thread Eric Brunel
Jean Montambeault wrote:
I am not only learning Python but programming itself ; reading your 
posts makes me believe that nobody is that much of a beginner here. Is 
there a newgroup or list for my type somewhere I can't find it ?

To illustrate my case this script :

# function to draw rings for an Olympic flag
def rings(size,offsetX,offsetY,coul):
x1,y1,x2,y2 = 170, 103, 170, 103,
can1.create_oval(x1-size-offsetX,y1+size+offsetY,\
 x2+size-offsetX,y2-size+offsetY,\
 width=8, outline=coul)
# **mainmainmainmainmainmain**
fen1=Tk()
can1=Canvas(fen1, bg='white', height=206, width=340)
can1.pack(side=LEFT)
bou_europe=Button(fen1, text='Europe',\
  command=rings(41, 100, -22, 'blue'))
Here is what you do here: you *call* your "rings" function with the given 
parameters, and you assign the *result* of the function (which is None, since 
you do not have any "return" statement in rings) to the "command" option of your 
button. Since you do that for all buttons, all circles are drawn right away and 
no command is attached to any of your buttons.

The basic solution would be to create 5 different functions - one for each ring 
- and assign the function to the button's command option:

def ringEurope():
  rings(41, 100, -22, 'blue')
bou_europe = Button(fen1, text='Europe', command=ringEurope)
And so on...
Another shorter, but more difficult to understand solution would be to use an 
anonymous function built with lambda. Here is how it goes:

bou_europe = Button(fen1, text='Europe',
command=lambda: rings(41, 100, -22, 'blue'))
There are however some issues with lambda, so you'd probably better stick to the 
first solution.

[snip]
bou_africa=Button(fen1, text='Africa',\
  command=rings(size=41, offsetX=0,offsetY=-22, 
coul='black'))
(BTW, why do you pass the function arguments as positional parameters in the 
first call and as named parameters in the following ones? IMHO, since the 
parameters are positional in the function definition, you'd better pass them as 
such in the calls, i.e: rings(41, 0, -22, 'black')

(Et sinon, il existe un newsgroup Python francophone (fr.comp.lang.python) sur 
lequel tu seras le bienvenu si jamais tu préfères discuter en français)

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple GUI question

2004-12-08 Thread Eric Brunel
Roose wrote:
[snip]
Another thing I would *like* but is not strictly necessary would be to
change the font size and color of the text within the box.  Is there a good
way of doing that?  I have googled around but can't find any decent example
code for some reason.
Short answer: you can't. The tkMessageBox functions use "native" dialogs, which 
cannot be configured.

The long answer depends on which platform you're on. If you are on Windows..., 
see short answer ;-) : the dialogs used are actually the native ones, and apart 
from abandonning the tkMessageBox module and designing your own dialogs, there 
is no way to alter their appearence (not that I know of).

If you're on Unix, it's a bit better but not much: since there's no such thing 
as "native" dialogs, the dialogs are actually tcl code that is in the tcl/tk 
distro, that you can hack anyway you want. This is however not recommended (not 
by me, anyway...), because it has many drawbacks (modify the tcl code will 
modify *all* your dialogs and you won't be able to simply distribute your script 
with the appearence changes: you'll have to distribute the new tcl code for the 
dialogs too...)

So if you really want to do that, the simplest way is definetely to avoid using 
the tkMessageBox module and to design your own dialogs.

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: spawn or fork

2004-12-08 Thread Eric Brunel
C Gillespie wrote:
Dear All,
I have a function
def printHello():
fp = open('file','w')
fp.write('hello')
fp.close()
I would like to call that function using spawn or fork. My questions are:
1. Which should I use
2. How do I call that function if it is defined in the same file.
spawn execute an external executable program *outside* your current script, 
*not* a Python function. So say you want to run wordpad.exe from your Python 
script, you could do:

os.spawn(os.P_NOWAIT, "C:\\Program files\\Accesories\\wordpad.exe, [...])
So you *need* an external executable to be passed to spawn.
fork works another way: it duplicates the context of your process in another one 
and continues both processes in parallel. So basically, it doesn't *execute* 
anything, but just creates a process. You may then call your function is the new 
process (a.k.a the "child" process):

def printHello():
  ...
if os.fork() == 0:
  ## fork returns 0 in the process copy => this is where we call our function
  printHello()
else:
  ## If fork doesn't return 0, we're in the original => other code
  ...
However, fork is only available on Unices.
What are you trying to do exactly? If you provide more explanations, we may 
provide a better help than the simplistic one above.

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: spawn or fork

2004-12-08 Thread Eric Brunel
C Gillespie wrote:
What are you trying to do exactly? If you provide more explanations, we
may
provide a better help than the simplistic one above.
Dear All,
Thanks for the suggestions.
Basically, I have the situation where a user (via the web) requests data
from a database that has to be written to file. However, this takes a couple
of minutes. So the way I thought of doing this is:
1. create an empty file.
2a. tell the user where to look for the file.
2b. spawn a process to insert data into the file.
This way the user can see the data as its being written.
You may want to use threads for this instead of processes. See 
http://docs.python.org/lib/module-threading.html

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: GUIs: wxPython vs. Tkinter (and others)

2004-12-13 Thread Eric Brunel
[EMAIL PROTECTED] wrote:
Hi, I had very bad experience with Tkinter when using input servers(for
CJK languages like scim, xcin...) on Linux (doesn't work), so you might
consider this.
Eh? I use (not frequently, I admit...) kinput2 with canna and wnn servers with 
Tkinter on Linux and it works quite smoothly. Can you describe what happens to 
you exactly?
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multithreading tkinter question

2004-12-17 Thread Eric Brunel
Oleg Paraschenko wrote:
[snip]
In my case "Hello" works and "Quit" doesn't (GUI stays frozen).
Linux, Python 2.3.3, pygtk-0.6.9.
That's not a multithreading issue, but just the way the quit method works. 
Try:
-
import time
from Tkinter import *
root = Tk()
b = Button(root, text='Quit')
b.configure(command=root.quit)
b.pack()
root.mainloop()
time.sleep(2)
-
When you click the "Quit" button, the GUI stays there until the time.sleep ends. 
root.quit just goes out of the mainloop; it doesn't destroy the widgets. To do 
that, you have to add an explicit root.destroy() after root.mainloop()
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: scrollbar dependencies

2005-03-24 Thread Eric Brunel
On 24 Mar 2005 03:24:34 -0800, Marion <[EMAIL PROTECTED]> wrote:
Next mystery :
a picture drawn in the canvas c1 is scrollable.
a picture-containing canvas "grided" in the canvas c1 is not.
so why ???
Marion
---
[snip]
#---#
# this is not ! :
#---#
canvas=Canvas(self.c1,background="WHITE")
image  =Image.new("RGB",(100,100))
dessin = ImageDraw.Draw(image)
dessin.rectangle([(10,10),(50,50)],fill="rgb(255,0,0)")
photo=ImageTk.PhotoImage(image)
item = canvas.create_image(0,0,anchor=NW,image=photo)
canvas.grid()
You don't want to do that. Canvases are not meant to be containers where 
you can pack or grid items. They strangely accept it, but it will never do what 
you want. If you want to pack or grid items in a container, use a Frame. If you 
want to include a widget in a Canvas, use a canvas window:
c1 = Canvas(root)
c1.pack()
c2 = Canvas(c1, bd=2, relief=SUNKEN, width=50, height=50)
c1.create_window(20, 20, window=c2, anchor=NW)
Canvas windows are scollable; widgets packed or gridded in Canvases are 
not. So this really seems to be your problem here.
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to ensure Maximize button shows in Linux/Unix (Tkinter)

2005-03-29 Thread Eric Brunel
On 26 Mar 2005 08:19:07 -0800, Harlin Seritt <[EMAIL PROTECTED]> wrote:
Diez,
Thanks for the quick reply. I am running this under KDE. I actually
haven't tried doing so under any other wm for the moment. Any ideas how
to get it to show in KDE?
This is a tk bug; see:
http://sourceforge.net/tracker/index.php?func=detail&aid=922336&group_id=12997&atid=112997
and:
http://sourceforge.net/tracker/index.php?func=detail&aid=915350&group_id=12997&atid=112997
The latest tcl/tk 8.4 release may solve the problem, and a patch is provided 
for the second bug report if you don't want to upgrade.
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter destroy()

2005-03-29 Thread Eric Brunel
On Tue, 29 Mar 2005 10:37:10 GMT, max(01)* <[EMAIL PROTECTED]> wrote:
hi people.
when i create a widget, such as a toplevel window, and then i destroy
it, how can i test that it has been destroyed? the problem is that even
after it has been destroyed, the instance still exists and has a tkinter
name, so testing for None is not feasible:
 >>> import Tkinter
 >>> fin = None
 >>> fin1 = Tkinter.Toplevel()
 >>> fin1.destroy()
 >>> print fin1
.1075951116
The winfo_exists method is what you want:
print fin1.winfo_exists()
0
However, I'm curious about *why* you want to do that: since *you* made the call 
to destroy, what would you want to do anything with a widget you've already 
destroyed?
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with tkinter

2005-03-30 Thread Eric Brunel
On Tue, 29 Mar 2005 22:32:59 +0200, Pierre Quentel <[EMAIL PROTECTED]> wrote:
Instead of indexing self.lab by strings, you can index them by the
attributes themselves : self.lab[self.i], and change line 23 into
  for var in (self.s, self,i)
I really think this is asking for trouble: I suppose that the i and s 
attributes are meant to change at some point in the future, and you're mapping 
their *values* to the corresponding labels. So if the value changes, you won't 
be able to get the label again.
For your example, I wouldn't have used the "text" option in the
definition of the labels, then "textvariable" in the callback method
(procedi) ; I would have used only "text" and no IntVar or StringVar,
just an integer and a string :
I would have done exactly the contrary, as it is far more easier to use. 
Using the textvariable option in Label's does not require you to remember the 
labels, but only the variables used to hold their contents. I'd also use two 
mappings: the first mapping a name to a Tkinter variable for the label 
variables, and the second for the values to give to these variables later.
Here is my version of the class code:
class MiaApp:
 def __init__(self, genitore):
self.mioGenitore = genitore
## Mapping for variables
self.variables = {
  "i" : StringVar(),
  "s" : StringVar()
}
## Mapping for future variable values
self.values = {
  "i" : 42,
  "s" : "Baobab"
}
## Now, create the labels
for var in self.variables.values():
  ## Default text
  var.set("[vuota]")
  ## Create label
  lb = Label(self.mioGenitore, width=30, relief=RIDGE, textvariable=var)
  lb.pack()
## The button is no more remembered in an attribute, as it does not 
seem to be needed
but = Button(self.mioGenitore, text = "Vai!", command = self.procedi)
but.pack()
 def procedi(self):
   ## Just change the variable values
   for varName in self.variables.keys():
 self.variables[varName].set(self.values[varName])
Note that I only used StringVar's: since the variable holds the *text* for a 
Label, it is not a good idea to use anything else. I tend to use IntVar, 
BooleanVar or DoubleVar only when I'm sure it won't ever be set to anything 
else than an integer, a boolean or a float respectively. So for Label and Entry 
text variables, I always use a StringVar. In spite of their name, these 
variable can actually hold anything; you will just get the value you've given 
to them as text rather than as their original type:
v = StringVar()
v.set(42)
v.get()
'42'
So if you want to get the integer back, you'll need to convert the value 
explicitely. This is in fact what is done by Tkinter when using an IntVar, but 
by doing it yourself, you'll be able to decide what to do if the conversion 
fails instead of just getting a generic TclError.
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Things you shouldn't do

2005-03-30 Thread Eric Brunel
On Wed, 30 Mar 2005 07:02:57 GMT, Andrew Dalke <[EMAIL PROTECTED]> wrote:
Steve wrote:
[an anecdote on distinguishing l1 and 11]

What are some of other people's favourite tips for
avoiding bugs in the first place, as opposed to finding
them once you know they are there?
There's a good book on this topic - Writing Solid Code.
And there's an excellent website showing what *not* to do:
http://mindprod.com/unmain.html
The OP's point is paragraph 11 in the "Camouflage" section.
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python + Tk text editor

2005-04-14 Thread Eric Brunel
On Thu, 14 Apr 2005 06:41:26 +0100, Jonathan Fine <[EMAIL PROTECTED]> wrote:
[snip]
And for my project (integration of Python and TeX) there
is most unlikely to be a better one.
Do you know the (apparently dead) project named e:doc? You can find it here:
http://members.nextra.at/hfbuch/edoc/
It's a kind of word processor that can produce final documents to various 
formats using backends, and one of the backends is for LaTeX.
It's written in Perl, but with Perl::Tk as a tool-kit, so it is quite close to 
Tkinter. There may be some ideas to steal from it.
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter Event Types

2005-04-19 Thread Eric Brunel
On 18 Apr 2005 13:48:50 -0700, codecraig <[EMAIL PROTECTED]> wrote:
Hi,
  When I do something like.
s = Scale(master)
s.bind("", callback)
def callback(self, event):
print event.type
I see "7" printed out.  Where are these constants defined for various
event types?  Basically i want to do something like...
def callback(self, event):
if event.type == ENTER:
print "You entered"
The usual way is to bind different callbacks on different events. So you 
won't have to test the event type in your callback, since the callback itself 
will already have been selected from the event type. If you insist in doing it 
the way you mention, you can always do:
ENTER_EVENT = 1
KEYPRESS_EVENT = 2
# ...
def myCallback(evtType, evt):
  if evtType == ENTER_EVENT:
# some action...
  elif evtType == KEYPRESS_EVENT:
# some other action...
  # ...
myWidget.bind('', lambda evt: myCallback(ENTER_EVENT, evt))
myWidget.bind('', lambda evt: myCallback(KEYPRESS_EVENT, evt))
I can't really see what it will be good for however...
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: New to Tkinter...

2005-04-19 Thread Eric Brunel
On Tue, 19 Apr 2005 09:35:03 -0400, Peter G Carswell <[EMAIL PROTECTED]> wrote:
Good Morning.
I am new to Tkinter. I have been testing the installation of Tkinter
through the python web site. The first two test steps give no errors,
'import _tkinter' and 'import Tkinter'. However, the third step,
'Tkinter._test', gives the error:

This is not an error. It's just the value of the _test function in the 
Tkinter module. You don't give the URL where you found the installation/test 
instructions, but you probably want:
Tkinter._test()
which *calls* the function. Tkinter._test just returns its value (functions are 
first class objects in Python...)
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting the sender widget's name in function (Tkinter)

2005-04-27 Thread Eric Brunel
On 26 Apr 2005 13:37:29 -0700, infidel <[EMAIL PROTECTED]> wrote:
from Tkinter import Tk, Button
def say_hello(event):
print 'hello!'
print event.widget['text']
root = Tk()
button1 = Button(root, text='Button 1')
button1.bind('', say_hello)
button1.pack()
button2 = Button(root, text='Button 2')
button2.bind('', say_hello)
button2.pack()
root.mainloop()
Unfortunately, making a binding to  on Button widgets does not have the same 
behavior as setting their 'command' option. The binding will fire when the button is *pressed*; 
the command will be called when the button is *released*. So, binding to  
instead of  make things a little better, but still does not have the same effect, 
since ButtonPress and ButtonRelease events are balanced: the widget getting the ButtonRelease 
event is always the same as the one getting the ButtonPress event. So if the mouse button is 
pressed inside the Button, then the mouse pointer goes out of it, and then the mouse button is 
released, the Button will still get the ButtonRelease event and fire the binding. This is not the 
normal behavior for a button and this is not the behavior you get via the 'command' option (just 
try it...).
So having a different function for each button or using tiissa's solution is 
definitely better.
HTH
--
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\\'*9--56l7+-'])"
--
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter text width

2005-04-27 Thread Eric Brunel
On Tue, 26 Apr 2005 17:01:46 -0700, James Stroud <[EMAIL PROTECTED]> wrote:
Hello All,
I would like for a tkinter text widget to be aware of how big the frame that
contains it is, then I would like for it to reset its width to the
appropriate number of characters when this frame changes size.
Errr... This is supposed to be the regular behaviour. How do you create 
your Text widget? Do you specify a width and height? If you do not, the default 
width and height are 80 and 24 respectively, and the widget won't resize to 
less than that. If you want a Text widget to be the smallest as possible in its 
container, you can do something like:
-
from Tkinter import *
root = Tk()
t = Text(root, width=1, height=1)
t.pack(fill=BOTH, expand=1)
root.geometry('500x200')
root.mainloop()
-
The "trick" is to create the Text as small as possible (width=1, height=1), 
make it fill its whole container (pack(fill=BOTH, expand=1)), then set the dimensions for 
the container window (geometry('500x200')). You'll get a Text that will shrink and expand 
as much as you like.
Is it what you were after?
HTH
--
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\\'*9--56l7+-'])"
--
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter text width

2005-04-28 Thread Eric Brunel
On Wed, 27 Apr 2005 12:52:21 -0700, James Stroud <[EMAIL PROTECTED]> wrote:
[snip]
How might I query the size of a fixed-width font in pixles? It appears that
the width of the font in points does not correlate with its width in pixels
based on some simple expriments I have done.
This is the case on all platforms, but far more sensible on Windows: Windows attempts 
to be "clever" and corrects the font size you give depending on your screen 
resolution so that a 12 point font is supposed to be actually 12/72 inches *on screen* 
(obviously ignoring the fact that this is almost never what you want, since all other 
dimensions are in screen points by default...). Other platforms than Windows are supposed 
to do this too, but (fortunately) it seems to fail and the computed factor is very close 
to 1 (I got something like 1.04 on Linux, whatever the screen resolution was).
To avoid this, you can try to use the winfo_* methods to get the screen 
resolution (I thought there was a more straightforward way, but the only way I 
see is to do someWidget.winfo_screenwidth() / someWidget.winfo_screenmmwidth(), 
with the usual adjustement to get inches instead of millimeters). You can then 
use this adjustement on all the dimensions you compute so that it will be 
consistent with the font sizes you get.
The other solution is to turn the adjustement off. You can do this at tk level with the 
command "tk scaling 1". Unfortunately, this command does not seem to be 
directly available at Tkinter level, so you'll have to do:
someWidget.tk.call('tk', 'scaling', 1)
After doing that, all your font sizes should be in screen points. But be aware 
that *all* your fonts will seem to shrink (the screen resolutions these days 
are usually closer to 92 dpi than to 72...). So you may have to do some 
adjustements on other parts of your application (the biggest problem I got was 
with menu items).
HTH
--
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\\'*9--56l7+-'])"
--
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter text width

2005-04-29 Thread Eric Brunel
On Thu, 28 Apr 2005 16:14:02 GMT, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
On Thu, 28 Apr 2005 10:36:18 +0200, "Eric Brunel"
<[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
This is the case on all platforms, but far more sensible on Windows: Windows attempts to be "clever" and corrects the font size you give depending on your screen resolution so that a 12 point font is supposed to be actually 12/72 inches *on screen* (obviously ignoring the fact that this is almost never
Pardon? Since when has Windows attempted to scale fonts for
screen display based on screen resolution?
The older Macs were fixed at 72 pixels per inch -- with the
result that the /only/ way to increase the resolution was to physically
change to a larger monitor. This is why they were so popular for DTP --
the on-screen view WAS the same size as the printed view.
Windows display properties defaults to an /assumed/ 96 pixels
per inch regardless of the screen resolution (right-click the desktop
background, properties, Settings/Advanced, General). This is why
changing to a low-resolution (like the recovery mode screen on W98) on a
large monitor results in such a pixilated, large-character, display.
I'm currently running a 20" flat-panel at 1600x1200. It also
appears to be about 12" vertical display region, making for
100pixels/inch. If I set it to 800x600, it would be running at 50pixels
per inch -- even though Windows is still assuming 96ppi for rendering. A
12pt typeface would be just under 1/8" on normal, but 1/4" on the low
resolution setting.
Sorry for that: my mistake. Anyway, the problem remains; the ouput for the "tk 
scaling" command on Windows and Linux is as follows:
[Windows]
% tk scaling
1.33202228777
[Linux]
% tk scaling
1.04285347703
(all of this tested with tcl/tk 8.3 - Windows is Win2k, Linux is an old 
Mandrake 8.0).
So this means that when you ask for a 12 point font, Windows will give you a 12 * 
1.33202228777 = 16 screen pixels font and Linux a 12 * 1.04285347703 = 12 or 13 screen 
pixels font, depending on how the size is rounded. But the dimensions you set for all 
widgets are in screen pixels, unless explicitely given in another unit. So either you do 
a "tk scaling 1" at the beginning of all your apps, or you specify all widget 
diemnsions as '100p' instead of just 100 for example. If you don't do either, all your 
texts will look really bigger on Windows than on Linux.
--
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\\'*9--56l7+-'])"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Set initial size in TKinter

2011-12-20 Thread Eric Brunel
In article ,
 Gabor Urban  wrote:
> Hi,
> 
> I am quite newbie with Tkinter and I could not find the way to set the
> size of the application. (I could find the method to make it
> resizeable, though :-)) ) Any ideas, suggestions or links to
> references are wellcome.

Usually, the best way is to use the geometry method on instances of Tk 
or Toplevel. For example, if you have a variable named root which is the 
instance of Tk, you can do:

root.geometry('500x400')

This will make the window 500 pixels wide and 400 pixels high.

> Here is my code:
> 
> from Tkinter import *
> 
> class Application(Frame):
> def say_hi(self):
>   self.db += 1
> print 'hi there, -->> UG everyone! db = %d'%self.db
> 
> ## TODO: meretezhetoseg
> def createWidgets(self):
>   top = self.winfo_toplevel()
>   top.rowconfigure(0,weight = 1)
>   top.columnconfigure(0,weight = 1)
>   self.rowconfigure(0,weight = 1)
>   self.columnconfigure(0,weight = 1)
>   self.QUIT = Button(self)
>   self.QUIT["text"] = "QUIT"
>   self.QUIT["fg"]   = "red"
>   self.QUIT["command"] =  self.quit
> 
>   self.QUIT.pack({"side": "left"})
> 
>   self.hi_there = Button(self)
>   self.hi_there["text"] = "Hello",
>   self.hi_there["command"] = self.say_hi
> 
>   self.hi_there.pack({"side": "left"})
> 
> def __init__(self, master=None):
> Frame.__init__(self, master)
> self.pack()
> self.createWidgets()
>   self.db = 0
> 
> app = Application()
> app.master.title('UG test')
> app.mainloop()

Where did you find an example code looking like this? This looks like 
veery old conventions for Tkinter programsŠ

For example, there's no need at all to do:

self.QUIT = Button(self)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"]   = "red"
self.QUIT["command"] =  self.quit

This can be done in a single line:

self.QUIT = Button(self, text='QUIT', fg='red', command=self.quit)

The same goes for self.QUIT.pack({"side": "left"}). Nowadays, this is 
always written self.QUIT.pack(side="left").

And you should avoid creating only an instance of Frame. This actually 
creates a window, but it's a side-effect. Windows are created by 
instantiating Tk for the main one, and Toplevel for all others. Having 
only a Frame will cause problems later, for example if you want to add a 
menu to the window: You can do so on instances of Tk or Toplevel, but 
not on framesŠ

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


Re: Changing fill in tkinter

2006-01-13 Thread Eric Brunel
On 13 Jan 2006 01:43:42 -0800, venk <[EMAIL PROTECTED]> wrote:

> Hi,
>  I would like to know how to change the fill of things we put in a
> tkinter's canvas. for example, if i create a rectangle and i would want
> to change the fill of the rectangle once it is clicked... can we do
> that?

Not sure if I correctly understand your question, but you seem to look for  
itemconfigure:

>>> from Tkinter import *
>>> root = Tk()
>>> c = Canvas(root)
>>> c.pack()
>>> r = c.create_rectangle(20, 20, 60, 60)
>>> c.itemconfigure(r, fill='blue')

Is that what you were after?

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with Tkinter and threads

2006-07-17 Thread Eric Brunel
On Mon, 17 Jul 2006 12:58:08 +0200, Claus Tondering  
<[EMAIL PROTECTED]> wrote:

> My Tkinter application has to receive events from a TCP connection. I
> have chosen to do this in the following manner:
>
> The TCP communication takes place in a separate thread. When I receive
> data, I generate an event in the Python application thus:
>
> app.event_generate("<>")

This is where the problem is: if you do just a event_generate without  
specifying the 'when' option, the binding is fired immediately in the  
current thread. To be sure that an event is created and that the thread  
switch actually happens, do:

app.event_generate("<>", when='tail')

and things should work fine.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with Tkinter and threads

2006-07-17 Thread Eric Brunel
On Mon, 17 Jul 2006 15:20:46 +0200, Claus Tondering  
<[EMAIL PROTECTED]> wrote:

> Eric Brunel wrote:
>> This is where the problem is: if you do just a event_generate without
>> specifying the 'when' option, the binding is fired immediately in the
>> current thread. To be sure that an event is created and that the thread
>> switch actually happens, do:
>>
>> app.event_generate("<>", when='tail')
>>
>> and things should work fine.
>
> Nice!
>
> Obviously, there are important things that I don't know about Tkinter.
> Unless I'm much mistaken, neither Fredrik Lundh's "An Introduction to
> Tkinter" nor John W. Shipman's "Tkinter reference: a GUI for Python"
> mentions the when='tail' option.

The ultimate documentation is unfortunately still the tcl/tk man pages.  
There is an on-line version here:

http://www.tcl.tk/man/

Once you've understood how to convert the tcl syntax to Python/Tkinter,  
it's always the most up-to-date source of information.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter wm_delete_window

2006-07-18 Thread Eric Brunel
On Tue, 18 Jul 2006 11:16:04 +0200, yvesd <[EMAIL PROTECTED]> wrote:
> hello i want to intercept tkinter python system events like
> wm_delete_window
> and if possible for any window, but the newest code I've produced give
> me
> an error :
> Traceback (most recent call last):
>   File "C:\Documents and Settings\yvesd\Bureau\protowin.py", line 36,
> in ?
> b1 = Tkinter.Button (win1)
>   File "C:\Python24\lib\lib-tk\Tkinter.py", line 1933, in __init__
> Widget.__init__(self, master, 'button', cnf, kw)
>   File "C:\Python24\lib\lib-tk\Tkinter.py", line 1856, in __init__
> BaseWidget._setup(self, master, cnf)
>   File "C:\Python24\lib\lib-tk\Tkinter.py", line 1834, in _setup
> self.tk = master.tk
> AttributeError: MyDlg instance has no attribute 'tk'
> thanks a lot for the help answer.
> here is my code :
> import Tkinter
> from Tkinter import *

Do not import the same module twice: either use "import Tkinter" and  
prefix everything in it with 'Tkinter.', or use "from Tkinter import *"  
and don't specify any prefix. You're mixing both here.

> class MyDlg(Toplevel):
>   def ma_fonction():

You must specify 'self' as first parameter here. Or put 'ma_fonction'  
outside the class.

>   print "my function is finished."
>   def __init__(arg1, arg2):
>   arg1.protocol("WM_DELETE_WINDOW", arg1.ma_fonction)

Please don't use anything else than 'self' as the name for methods' first  
parameter. It will confuse everyone who knows Python. And your mistake is  
here: the constructor for the super-class (Toplevel) is not called  
automatically by the sub-class constructor; so you have to do it yourself.  
So just rewrite these two lines as:

def __init__(self):
   Toplevel.__init__(self)
   self.protocol("WM_DELETE_WINDOW", self.ma_fonction)

and everything should work fine. BTW, I've removed the parameter arg2 that  
you didn't use at all.

> root = Tkinter.Tk ()
> #win1 = Tkinter.Toplevel (root)
> win1 = MyDlg(root)

Replace that with:

win1 = MyDlg()

> b1 = Tkinter.Button (win1)
> b1.config (text="hello")

An additional small note: you can write the last two lines as a single one:

b1 = Tkinter.Button(win1, text='hello')

And you also must call:
- b1.pack, b1.grid or b1.place to put your button somewhere in your window.
- root.mainloop() in the end or your window will never appear.

If you want to do Tkinter the OO way, you may also create the button in  
the dialog's constructor.

So here would be my version of your program:

--
 from Tkinter import *

class MyDlg(Toplevel):
   def __init__(self):
 Toplevel.__init__(self)
 b1 = Button(self, text='hello')
 b1.pack()
 self.protocol("WM_DELETE_WINDOW", self.ma_fonction)
   def ma_fonction(self):
 print "my function is finished."

root = Tk()
win1 = MyDlg()
root.mainloop()
--

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter pack Problem

2006-07-26 Thread Eric Brunel
On Wed, 26 Jul 2006 12:46:39 +0200, H J van Rooyen <[EMAIL PROTECTED]>  
wrote:

> Hi,
>
> I am struggling to get the pack method to do what I intend.
> I am trying to display user input in a seperate window, along with
> a little description of the field, something like this:
>
>  Current entry
> Company :   entered co. name
> First entry :   entered stuff
> The second entry: more entered stuff
> Entry number three :  Last entered stuff

You won't be able to do that kind of layout with pack. This is - quite  
obviously IMHO - a job for grid, since your widgets are arranged in a grid.

According to my experience, pack should only be used for *very* simple  
layouts, such as all widgets in a single row or in a single column. Trying  
to do anything else will very soon end up being a nightmare, with unneeded  
frames everywhere. Learn to use grid and life will be far easier for you.

[snip]

A few comments on your code:

> #!/usr/bin/python
> #   The original of this module is supposed to do an accounting entry -
>
> #   we get the gui stuff
>
> from Tkinter import *
>
> class Entryscreen(Frame):

Why do you inherit from Frame? Apparently, you're trying to do a window. A  
Frame is not a window; it's a general-purpose container for widgets. If  
you want to do a window, inherit from Tk (for a main window) or from  
Toplevel (for any other).

> """This screen is used to construct a new Entry."""
>
> #   we define the variables we use
>
> des_string = '' # Description of what we want to do
> req_string = '' # Prompt string
> dis_string = '' # Description of field for display
>
> Company =  "New Entry Screen"   # we dont have a company yet
> Entry_1 = ''# or any entries
> Entry_2 = ''
> Entry_3 = ''
>
> def start_new(self):
> """This is the routine that assembles a new record"""
>
> if self.Company == "New Entry Screen":  # if its the first time,
>
> #   we make a new window
>
> show = Tk()

No, we don't. We actually create a whole new tcl/tk interpreter  
environment, completely independent from the one we already have, which  
happens to create a new main window. Doing so is bound to cause problems  
later. If you want to create a new window, instantiate Toplevel.

> show.title('Accounting entry display window')
>
> #   we get an instance to display results in
>
> self.disp = Showscreen("Current entry",master=show)
>
> #   then we ask for the company:
>
> des_string = "Getting the Company "
> req_string = "Enter the Company for this session"
> dis_string = 'Company:'
> error = self.GetEntry(des_string, req_string, dis_string,  
> self.disp)
> self.Company = self.Amount
>
> #   Then or else we ask for entry details
>
> des_string = "Getting first entry"
> req_string = "Enter first field"
> dis_string = "First entry:"
> error = self.GetEntry(des_string, req_string, dis_string,  
> self.disp)
>
> des_string = "Getting second entry"
> req_string = "Enter second field"
> dis_string = "The second entry:"
> error = self.GetEntry(des_string, req_string, dis_string,  
> self.disp)
>
> des_string = "Getting third entry"
> req_string = "Enter third field"
> dis_string = "Entry number three:"
> error = self.GetEntry(des_string, req_string, dis_string,  
> self.disp)

This is not important, but why do you always create variables for your  
strings instead of passing them directly? For example, the previous 4  
lines can be written:

error = self.GetEntry("Getting third entry", "Enter third field", "Entry  
number three:", self.disp)

This would shorten your code a lot. And why do you always pass self.disp  
as the last argument? This is an attribute, so using it directly inside  
the GetEntry method is not a problem.

> def GetEntry(self, des_string, req_string, dis_string, disp):
> """Entry routine for one field"""
>
> line = Entryline(des_string, req_string, dis_string, disp,  
> master=root)
> error = line.mainloop()

*Never* call mainloop twice in an application! This is not the way to go.  
If you want to do a modal dialog, you have to use the wait_window method,  
which waits for a given window to be closed.

> self.Amount = line.retstring
> line.destroy()
>
> def say_bye(self):
> print 'Have a nice day, Bye!'
> self.quit()
>
> def createWidgets(self):
>
> self.descr = Label(self)
> self.descr["text"] = self.Company
> self.descr["fg"] = 'purple'
> self.descr['bg'] = 'yellow'
> self.descr.pack({'expand': 'yes', 'fill': 'both', "side": "top"})

This can be written:

self.descr.pack(side=TOP, fill=BOTH, expand=1)

which is shorter and IMHO clearer. TOP and BOTH are constants defined in  
the Tkinter mod

Re: Strange Tkinter Grid behaviour Problem

2006-08-01 Thread Eric Brunel
On Tue, 01 Aug 2006 14:14:51 +0200, H J van Rooyen <[EMAIL PROTECTED]>  
wrote:

> Hi,
>
> Still struggling with my GUI exercise -
>
> I have the following lines of code in a routine that is bound at  
>  to
> an instance of Entry :
>
> self.disp.Amount_des = Label(self.disp, text = self.dis_string,  
> fg =
> 'black', bg = 'yellow')
> self.disp.Amount_des.grid(row = self.rownum, column=0, sticky =  
> 'nesw')
>
> self.disp.Amount = Label(self.disp, text = self.retstring, fg =  
> 'black',
> bg = 'green')
> self.disp.Amount.grid(row = self.rownum, column=1, sticky =  
> N+S+E+W)
>
> The second call to the grid method fails as follows:
>
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "E:\PYTHON24\lib\lib-tk\Tkinter.py", line 1345, in __call__
> return self.func(*args)
>   File "C:\WINDOWS\DESKTOP\Entry1.py", line 243, in entryend
> self.disp.Amount.grid(row = self.rownum, column=1, sticky = N+S+E+W)
> TypeError: cannot concatenate 'str' and 'instance' objects
>
> If I change the N+S+E+W to the 'nsew' form, it works no problem...
>
> Weird - at other places in the program the form:  sticky = N+S+E+W works  
> without
> a problem.

Simple: you have in this context a local or global variable named either  
N, S, W or E, shadowing the constant defined in the Tkinter module. You  
can find it by inserting a line like:

print repr(N), repr(S), repr(W), repr(E)

before your self.disp.Amount.grid in your code. This line should print:

'n' 's' 'w' 'e'

but I guess it won't...

The solutions are:
- Rename your variable.
- Always use the string form, i.e 'nswe'. This is the standard in native  
tk. The N, S, W and E constants are just defined for convenience in  
Tkinter.
- Do not use "from Tkinter import *" to import the module, but something  
like "import Tkinter as tk", and then prefix all names in this module by  
'tk.'. So your code above becomes:

self.disp.Amount = tk.Label(self.disp, text = self.retstring, fg =   
'black', bg = 'green')
self.disp.Amount.grid(row = self.rownum, column=1, sticky =  
tk.N+tk.S+tk.E+tk.W)

(I'm personnally not a big fan of this last solution, since I find it  
clobbers the code a lot and decreases readability. But it's usually the  
best way to avoid name clashes...)

[snip]

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why the method get() of python Queue is hang on there?

2006-08-14 Thread Eric Brunel
On Mon, 14 Aug 2006 17:10:13 +0200, zxo102 <[EMAIL PROTECTED]> wrote:

> Hi,
>I am using Queue from python2.4. Here is what happen to me:
>
> import Queue
> b = Queue.Queue(0)
> b.put()
> b.get()   # this is ok, it pops out 
> b.get()   # this one does not return anything and is hang on there
>
> Anybody knows what is going on with the second b.get()?

What did you expect? Since you've done only one put in the Queue, there's  
nothing left in it. Since queues are meant to communicate between threads  
- and also often to synchronize them -, the default behaviour for the get  
when the queue is empty is to wait for something to be put in it. If you  
want your second get to fail, use the get_nowait method.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter prob

2006-08-21 Thread Eric Brunel
On Mon, 21 Aug 2006 08:50:29 +0200, JyotiC <[EMAIL PROTECTED]> wrote:

> i have tried it out but it's not working.
> this is the code
>
> from Tkinter import *
>
> class abc:
> def __init__(self,parent):
> #make container myparent
> self.myparent=parent
> self.myparent.geometry("500x200")
>
> #make the initial frame
> self.frame=Frame(self.myparent)
> self.frame.pack()
>
> self.var=IntVar()
> self.var.set(0)
>
> a=Button(self.frame,text="button")
> a.pack()
>
>
> Checkbutton(self.frame,text="hello",variable=self.var,command=self.com(a)).pack()

This *calls* self.com(a) and assigns its *results* (which happens to be  
None) to the command option in your button. So your button does nothing.

To do what you want, use:

  self.a = Button(self.frame,text="button")
  self.a.pack()
  
Checkbutton(self.frame,text="hello",variable=self.var,command=self.com).pack()

in __init__, then:

  def com(self):
  if self.var.get()==1:
  self.a.config(state=ENABLED)
  else:
  self.a.config(state=DISABLED)

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/Tkinter crash.

2006-10-04 Thread Eric Brunel
On Wed, 04 Oct 2006 10:33:55 +0200, Hendrik van Rooyen  
<[EMAIL PROTECTED]> wrote:

> Hi,
>
> I get the following:
>
> [EMAIL PROTECTED]:~/Controller/lib> python display.py
> UpdateStringProc should not be invoked for type font
> Aborted
>
> and I am back at the bash prompt - this is most frustrating, as there is  
> no
> friendly traceback to help me guess where its coming from.
>
> And what is worse, the script runs for a varying time before it simply  
> exits
> like this.
>
> What can I do to dig deeper to try to find a clue? - I don't even know  
> if its
> Python, Tkinter or Linux...

Neither of them: it's a tcl problem. The message you get is in the file  
generic/tclObj.c in the tcl source directory.

I know the problem happens sometimes on one of my Tkinter applications,  
but I never succeeded in reproducing it systematically. I've browsed the  
tcl bugs, but didn't find anything. Maybe you'll be luckier than I... If  
you are, I'm interested in any hint you can find.
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/Tkinter crash.

2006-10-05 Thread Eric Brunel
On Wed, 04 Oct 2006 20:02:56 +0200, Hendrik van Rooyen  
<[EMAIL PROTECTED]> wrote:
>  "Eric Brunel" <[EMAIL PROTECTED]> wrote:
>> I know the problem happens sometimes on one of my Tkinter applications,
>> but I never succeeded in reproducing it systematically. I've browsed the
>> tcl bugs, but didn't find anything. Maybe you'll be luckier than I... If
>> you are, I'm interested in any hint you can find.
>
> Ouch! - this is a bit the wrong answer...

Sorry for that. I realize I wasn't very helpful, here...

> What I have seen, in mucking about today, is that it seems to be related  
> to
> threading - I have a silly sort of thread that runs, updating my meters,  
> more or
> less continuously, to simulate data from the field - it just adds some  
> values to
> the seven display variables and calls the update methods that delete and  
> redraw
> the arcs representing the analogue style meters, deleting and replacing  
> the text
> objects that show the values, and then it sleeps for a while, and does  
> it all
> again.
>
> At the same time, one other thread (other than the main thread), can be  
> created
> to move a component on the canvas around by calling its delete and draw
> methods. - but this is also done more or less continuously, as a new  
> thread is
> created as soon as the previous one dies to move the next object around.
>
> Now these two things are asynchronous with each other, so that given  
> enough
> time, they are bound to make calls to Tkinter in a re-entrant fashion,  
> and I
> suspect that it is this that is causing the problem - my "evidence" for  
> this is
> that I implemented a boolean as a sort of "lock" and had the Meter  
> updating back
> down in favour of the other animation to try and avoid any sort of re -  
> entrancy
> to the Tkinter canvas object's  delete and draw methods...

AFAIK, Tkinter is not thread safe. Using some kind of lock to serialize  
the calls from different threads may seem to work (I never tested it  
actually), but the safest way I found to use threads with Tkinter was to  
call it only from the thread where the main loop executes. The only thing  
that seems to work reliably in secondary threads is to generate custom  
events (widget.event_generate('<>', when='tail')), and to  
treat them in Tkinter's thread via bindings  
(widget.bind('<>', treatment_command)). This makes things a  
bit messy, but it works quite well.

Now, as I said before, someone reported that he *did* get the error you  
got from time to time. So maybe the problem I have is not the same as  
yours, or maybe there are some cases in my application where Tkinter stuff  
still gets called directly from secondary threads. I'll try to investigate  
that when I've time and I'll keep you informed.

HTH a little this time...
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Long Tkinter Menu

2006-10-05 Thread Eric Brunel
On Thu, 05 Oct 2006 02:33:54 +0200, Dustan <[EMAIL PROTECTED]> wrote:

> I don't know if this is because of Tkinter (ie Tk) itself or the
> Windows default way of handling things, but when I create a very long
> menu (my test is shown below), the way it displays is rather sucky; the
> menu stretches from the top of the moniter's window to the bottom (no
> matter the size of the actual application).
>
> Is there any alternative format for how a long menu gets displayed? It
> would be nice if say, I could make the menu only go to the borders of
> the application itself (in this case, not that long).

To limit the menu in the application window, will be difficult. But here  
are two ways of automatically limiting the number of entries that can  
appear in a menu by specializing the Tkinter Menu class:

--
 from Tkinter import *

class LongMenu(Menu):
   """
   Automatically creates a cascade entry labelled 'More...' when the
   number of entries is above MAX_ENTRIES.
   """

   MAX_ENTRIES = 20

   def __init__(self, *args, **options):
 Menu.__init__(self, *args, **options)
 self.nextMenu = None

   def add(self, itemType, cnf={}, **kw):
 if self.nextMenu is not None:
   return self.nextMenu.add(itemType, cnf, **kw)
 nbEntries = self.index(END)
 if nbEntries < LongMenu.MAX_ENTRIES:
   return Menu.add(self, itemType, cnf, **kw)
 self.nextMenu = LongMenu(self)
 Menu.add(self, 'cascade', label='More...', menu=self.nextMenu)
 return self.nextMenu.add(itemType, cnf, **kw)


class AutoBreakMenu(Menu):
   """
   Automatically adds the 'columnbreak' option on menu entries to make
   sure that the menu won't get too high.
   """

   MAX_ENTRIES = 20

   def add(self, itemType, cnf={}, **kw):
 entryIndex =  1 + (self.index(END) or 0)
 if entryIndex % AutoBreakMenu.MAX_ENTRIES == 0:
   cnf.update(kw)
   cnf['columnbreak'] = 1
   kw = {}
 return Menu.add(self, itemType, cnf, **kw)



if __name__ == '__main__':
   root = Tk()

   menubar = Menu(root)

   def fillMenu(menu):
 for i in xrange(100):
   menu.add_command(label=str(i), command=root.quit)
 menu.add_command(label="Exit", command=root.quit)

   menu1 = LongMenu(menubar, tearoff=0)
   fillMenu(menu1)
   menu2 = AutoBreakMenu(menubar, tearoff=0)
   fillMenu(menu2)

   menubar.add_cascade(label="Test1", menu=menu1)
   menubar.add_cascade(label="Test2", menu=menu2)

   root.config(menu=menubar)

   root.mainloop()
--

If your application is more complicated than that (e.g if you insert menu  
entries after the first adds), you'll have to change the code above a bit,  
since it doesn't handle calls to insert at all. But you get the idea.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter: Making a window disappear

2006-10-10 Thread Eric Brunel
On Mon, 09 Oct 2006 11:08:39 +0200, Claus Tondering  
<[EMAIL PROTECTED]> wrote:

> I just solved the problem myself:
>
> I wrote:
>> self.destroy()
>
> Writing "self.master.destroy()" instead does the trick.

As an alternative (which is better IMHO), you may consider specializing  
Toplevel instead of Frame for your dialog:

class MyDialog(Toplevel):
   ...

In tk/Tkinter, a Frame is a generic container for widgets; it is not what  
is usually called a window. Creating an instance of Frame when there is no  
window to contain it happens to create a new one, but it is a side-effect,  
and you should not rely on it.

Once you've done that, you can simply write:

self.destroy()

to delete the window.

> Sorry for the inconvenience.

No problem.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter: populating Mac Help menu?

2006-10-11 Thread Eric Brunel
On Tue, 10 Oct 2006 14:29:46 +0200, Edward K. Ream <[EMAIL PROTECTED]>  
wrote:
[snip]
> So given x (a string), how does one create a widget whose name is  
> '%s.help'
> % x ?  This is a can of corn in Tk, but nothing comes to mind looking at  
> the
> Tkinter source code.

Use the 'name' keyword when creating the menu itself:


 from Tkinter import *

root = Tk()

mb = Menu(root)
root.configure(menu=mb)

## Normal menu
fm = Menu(mb)
fm.add_command(label='Quit', command=root.quit)
mb.add_cascade(label='File', menu=fm)

## Help menu with a specific name
hm = Menu(mb, name='help')
hm.add_command(label='About...')
mb.add_cascade(label='Help', menu=hm)

root.mainloop()


I didn't test it on MacOS-X, but the same trick should be used when  
creating help menus on Unix (this menu is supposed to appear at the right  
of the menubar according to Motif conventions).

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter question

2006-10-24 Thread Eric Brunel
On Tue, 24 Oct 2006 07:48:51 +0200, Hendrik van Rooyen  
<[EMAIL PROTECTED]> wrote:
>  Sorin Schwimmer  wrote:
> Hi All,
>
> Is it possible to have a widget id while it is created?
> Something like this:
>
> Button(root, text='...', command= lambda v=: fn(v)).grid()
>
> and then the function:
>
> def fn(v):
>   v['bg']='BLUE' # or maybe nametowidget(v)['bg']='BLUE'

This cannot be done this way: when you create your lambda passed to the  
'command' option, the widget itself is not yet created. So there's no way  
at all to get the 'id' it will have when created.

Alternatively, you can simply split the widget creation in several lines:

b = Button(root, text='...')
b.grid()
b.configure(command=lambda b=b: fn(b))


But Hendrik's solution is better, since it avoids the use of lambda, which  
is often difficult to understand.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python GUIs comparison (want)

2006-11-06 Thread Eric Brunel
On Wed, 25 Oct 2006 11:04:57 +0200, Christophe <[EMAIL PROTECTED]>  
wrote:
>>> And no modern layout manager available. Only those old school  
>>> left/right/up/down pack and anchors are available.
>>  huh?  when did you last look at Tk?  1994?
> Yesterday. In fact, I could find no mention at all of layout managers  
> others than those working with anchors. Anchors are s old school  
> nowadays :)

Being "old school" or "modern" is not an argument in itself. How do the  
so-called "modern" layout managers help you do the thing you want to do?

And the fact that you could find no mention of something does not mean  
that it doesn't exist. It may just be a documentation problem.

> Honestly, I can't stand using anchors or the Packer anymore. The systems  
> used in wx, Qt are much better. Use them once and you cannot live  
> without them anymore.

The "Packer" is very rarely used in Tkinter applications when the layout  
becomes complicated. Almost all applications I saw use the "grid" layout  
manager, except for very simple things (like buttons in a row or column,  
where the "pack" layout manager is just enough).
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem getting a file pathname with tkFileDialog

2006-11-09 Thread Eric Brunel
On Wed, 08 Nov 2006 20:01:08 +0100, <[EMAIL PROTECTED]> wrote:

> Hello,
> I am working on a school project that requires me to get the path of a
> filename for future treatment.
> I've tried getting a file with tkFileDialog.askopenfile.
>
>
> 
> import tkFileDialog
> file = tkFileDialog.askopenfile()
> print file
> 
>
>
> It prints the opened files stuff, but I just can not find how to get
> that path as a string. I've searched around google and the present
> group, and found no documentation on the file class used with
> tkFileDialog. Does someone have a solution for that?

Use tkFileDialog.askopenfilename?

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem getting a file pathname with tkFileDialog

2006-11-09 Thread Eric Brunel
On Wed, 08 Nov 2006 21:59:38 +0100, Tim Daneliuk <[EMAIL PROTECTED]>  
wrote:

> Sefyroth wrote:
>> Thanks,
>>  but I get this error when I try this.
>>  UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in
>> position 12: ordinal not in range(128)
>>   I had encountered it with the askdirectory method as well. Is there an
>> easy way to bypass this?
>>  Thanks again
>
> I believe you are running into a directory or file name that has
> non-ascii characters in it.  Python as shipped is set up to
> deal with ascii as its native encoding format.  You can change
> this by editing the "site.py" file - look in the Lib directory
> in your python installation.  Look for this code:
>
> ---
> def setencoding():
>  """Set the string encoding used by the Unicode implementation.  The
>  default is 'ascii', but if you're willing to experiment, you can
>  change this."""
>  encoding = "ascii" # Default value set by _PyUnicode_Init()
>  if 0:
>  # Enable to support locale aware default string encodings.
>  import locale
>  loc = locale.getdefaultlocale()
>  if loc[1]:
>  encoding = loc[1]
> ---
>
>
>
> Change the "if 0:" to "if 1:" and see if that doesn't fix the problem.

This is usually a bad idea, especially if the script must be distributed  
to other users in any way: since they probably never did this "trick", the  
code will fail when they use it.

I know it's a pain, but you *have* to deal with encodings yourself, and  
not let the system guess what you might want.

In the OP's case, the problem just lies in the 'print' statement, that  
tries to encode the file name in ASCII before printing it. So just doing:
print repr(file.name)
would solve the problem.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to choose the right GUI toolkit ?

2006-11-10 Thread Eric Brunel
On Thu, 09 Nov 2006 23:51:31 +0100, Dan Lenski <[EMAIL PROTECTED]> wrote:

> One other thing I'm wondering: how exactly does Tkinter work?  Is the
> whole Tk toolkit bound up as library of low-level C code, or does
> Tkinter sit on top of a Tcl interpreter?

The latter: there is a tiny C layer allowing Python to call an embedded  
tcl interpreter.

> If the latter, that might explain why it is frustratingly slow on
> Cygwin... since Cygwin is not very good at starting up new processes in
> a timely manner.

There is no other process involved: the interpreter is embedded, just as a  
Python interpreter can be embedded in a C application. If you want to work  
with Tkinter on Windows, you'd better avoid Cygwin. Python with Tkinter  
works just fine on Windows, just as it works on any other platform, and is  
fully portable, just as tcl/tk is.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to choose the right GUI toolkit ?

2006-11-10 Thread Eric Brunel
On Thu, 09 Nov 2006 22:01:51 +0100, Dan Lenski <[EMAIL PROTECTED]> wrote:
> Tk 8.4 appears to use native Win32 widgets under Cygwin and native
> WinXP.

It seems to depend on the widget type, and on what you call native... For  
example, tk menus are definitely the native ones; tk scrollbars are the  
native ones, but with the Win2k look (no XP look available yet); tk  
buttons do not seem to be the native ones, as they don't act like "normal"  
Windows buttons.

> But it definitely doesn't use GTK widgets under Ubuntu with
> Gnome desktop.

You seem to imply that GTK is "native" on Linux. It isn't, as can be seen  
with the echoes of the "holy war" between Gnome and KDE that we often see  
around here. As an aside, I personnally work on Linux and don't even use  
any of these environments (both are too much Windows-like to my taste...).

> Is there a way to get it to do so?

Not yet. But tcl/tk 8.5 will include the Tile extension including new  
themable widgets. See here:
http://tktable.sourceforge.net/tile/screenshots/unix.html

There is also a Tile/QT extension that allows the Tile widgets to use the  
QT library. See here:
http://www.ellogon.org/petasis/index.php?option=com_content&task=view&id=24&Itemid=40

AFAIK, nothing equivalent for GTK yet.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CORBA: Fnorb Problems

2006-11-13 Thread Eric Brunel
On Mon, 13 Nov 2006 16:16:37 +0100, rodmc <[EMAIL PROTECTED]>  
wrote:

> Hi,
>
> I have installed Fnorb and everything seems to have gone ok. However I
> keep getting the error message below. This is despite the fact that the
> MS CL c++ preprocessor seems to be in PATH. I can type "cl" and
> although I get nothing back in the DOS window, there is also no error
> message.
>
> Traceback (most recent call last):
>   File "C:\Python24\Lib\site-packages\Fnorb\script\cpp.py", line 53, in
> -toplevel-
> raise "No C/C++ pre-processor found in your PATH!"
> No C/C++ pre-processor found in your PATH!

You don't say *when* this error occurs, i.e. what is the command that  
returns the exception. Assuming it's when you try to compile an IDL file  
with fnidl, just try:
fnidl --internal-cpp ...

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CORBA: Fnorb Problems

2006-11-14 Thread Eric Brunel
On Tue, 14 Nov 2006 13:13:42 +0100, rodmc <[EMAIL PROTECTED]>  
wrote:

>> >
>> > Traceback (most recent call last):
>> >   File "C:\Python24\Lib\site-packages\Fnorb\script\cpp.py", line 53,  
>> in
>> > -toplevel-
>> > raise "No C/C++ pre-processor found in your PATH!"
>> > No C/C++ pre-processor found in your PATH!
>>
>> You don't say *when* this error occurs, i.e. what is the command that
>> returns the exception. Assuming it's when you try to compile an IDL file
>> with fnidl, just try:
>> fnidl --internal-cpp ...
>
> Sorry you are right I did not say, but you guessed correctly. However
> even when I try your advice I still receive the same error.

I took a look at the Fnorb sources and it appears you're right: even if  
the --internal-cpp flag is used, fnidl still tests if the MS compiler  
exists and breaks if it can't be called or if it doesn't return what fnidl  
expects. The actual test is whether the cl output contains the string  
"/link", whatever the character case. So as you said in your original post  
that cl can be run, but doesn't print anything, this seems to be the  
problem.

What you can do is the following: go to Fnorb's source directory and edit  
scripts/cpp.py; on line 53, replace the "raise ..." by:
COMMAND = None
with the same indent.

Then run fnidl again with the --internal-cpp flag. This should work and  
produce the expected files.

Note that this is a dirty hack: if you forget to specify the  
--internal-cpp flag, you'll get a nasty traceback. But it should work in  
your case.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2006-11-15 Thread Eric Brunel
On Tue, 14 Nov 2006 17:45:52 +0100, Mudcat <[EMAIL PROTECTED]> wrote:
> The problem is I need the ability to change it dynamically. I don't
> want the cursor to be the double_arrow the whole time the mouse hovers
> inside that frame. It's supposed to be a resize arrow when the mouse is
> on the frame border, and regular cursor once it passes to the inner
> part of the frame.

Why don't you create a Frame for the inside with no border, and another  
Frame for the border? This way, you can have a cursor setting for each of  
them, i.e one for the inside and one for the border.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use tk.call ?

2006-05-30 Thread Eric Brunel
On 29 May 2006 21:13:07 -0700, <[EMAIL PROTECTED]> wrote:

>>> self.table.bind("",self.table.tk.call(self.table._w,'yview','scroll',-5,'units')
>
>> I haven't used Table, but are you sure that what you are calling
>> "self.table" here actually has mouse focus?
>
>> James
>
> Yup, I click on the table, and then frantically work the mouse wheel to
> no
> effect...

... which is quite normal, since you actually didn't define any binding.  
What you did is:
- *Call* self.table.tk.call(self.table._w,'yview','scroll',-5,'units'),  
which did the scroll;
- Pass the *result* of this call (which is probably None or the empty  
string) as the second parameter of self.table.bind.
So no binding was defined.

One solution is to define the binding via a lambda, like this (untested):
self.table.bind("", lambda e, t=self.table: t.tk.call(t._w,  
'yview', 'scroll', -5, 'units'))

For more information on lambda, see here:
http://docs.python.org/tut/node6.html#SECTION00675

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use tk.call ?

2006-05-30 Thread Eric Brunel
On 30 May 2006 05:51:04 -0700, <[EMAIL PROTECTED]> wrote:

> Eric,
>
> Thanks, your tip did the trick... Is there someplace where tk.call is
> discussed?

I don't think so. I personnally never find any documentation on it. But  
there is not much to say: you can just pass regular tcl commands through  
it and that's all. The only thing to remember is to split your command in  
"words" as tcl expects them. But you seem to have figured out that  
already...
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Function mistaken for a method

2006-06-01 Thread Eric Brunel
Hi all,

I just stepped on a thing that I can't explain. Here is some code showing  
the problem:

-
class C:
   f = None
   def __init__(self):
 if self.f is not None:
   self.x = self.f(0)
 else:
   self.x = 0

class C1(C):
   f = int

class C2(C):
   f = lambda x: x != 0

o1 = C1()
print o1.x

o2 = C2()
print o2.x
-

Basically, I want an optional variant function across sub-classes of the  
same class. I did it like in C1 for a start, then I needed something like  
C2. The result is... surprising:

0
Traceback (most recent call last):
   File "func-vs-meth.py", line 18, in ?
 o2 = C2()
   File "func-vs-meth.py", line 5, in __init__
 self.x = self.f(0)
TypeError: () takes exactly 1 argument (2 given)

So the first works and o1.x is actually 0. But the second fails because  
self is also being passed as the first argument to the lambda. Defining a  
"real" function doesn't help: the error is the same.

My actual question is: why does it work in one case and not in the other?  
As I see it, int is just a function with one parameter, and the lambda is  
just another one. So why does the first work, and not the second? What  
'black magic' takes place so that int is not mistaken for a method in the  
first case?
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function mistaken for a method

2006-06-01 Thread Eric Brunel
On Thu, 01 Jun 2006 13:34:53 +0200, Peter Otten <[EMAIL PROTECTED]> wrote:

> Eric Brunel wrote:
>
>> My actual question is: why does it work in one case and not in the  
>> other?
>> As I see it, int is just a function with one parameter, and the lambda  
>> is
>> just another one. So why does the first work, and not the second? What
>> 'black magic' takes place so that int is not mistaken for a method in  
>> the
>> first case?
> A python-coded function has a __get__ attribute, a C-function doesn't.
> Therefore C1.f performs just the normal attribute lookup while C2.f also
> triggers the f.__get__(C2(), C2) call via the descriptor protocol which
> happens to return a bound method.

Thanks for your explanations, Peter. I'll have to find another way to do  
what I want...
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function mistaken for a method

2006-06-01 Thread Eric Brunel
On Thu, 01 Jun 2006 15:07:26 +0200, bruno at modulix <[EMAIL PROTECTED]>  
wrote:
> Do yourself a favour : use new-style classes.
> class C(object)

I would if I could: I'm stuck with Python 2.1 for the moment (I should  
have mentionned it; sorry for that).

[snip]
>> Basically, I want an optional variant function across sub-classes of
>> the  same class.
>>
>> I did it like in C1 for a start, then I needed
>> something like  C2. The result is... surprising:
>>
>> 0
>> Traceback (most recent call last):
>>   File "func-vs-meth.py", line 18, in ?
>> o2 = C2()
>>   File "func-vs-meth.py", line 5, in __init__
>> self.x = self.f(0)
>> TypeError: () takes exactly 1 argument (2 given)
>
> Not surprising at all.
>
> Functions implement the descriptor protocol[1]. When bound to a class
> and looked up via an instance, it's the __get__ method of the function
> object that get called - with the instance as param, as defined by the
> descriptor protocol. This method then return the function wrapped - with
> the instance - in an Method object - which itself, when called, returns
> the result of calling the function *with the instance as first
> parameter*. Which is how methods can work on the instance, and why one
> has to explicitly declare the instance parameter in "functions to be
> used as methods", but not explicitly pass it at call time.
>
> (please some guru correct me if I missed something here, but AFAIK it
> must be a correct enough description of method invocation mechanism in
> Python).
>
> [1] about descriptors, see:
> http://docs.python.org/ref/descriptors.html
> http://www.geocities.com/foetsch/python/new_style_classes.htm#descriptors
>
>> So the first works and o1.x is actually 0.
>
> int is not a function.
 type(int)
> 
>
> int is a type.

Python 2.1 again:
>>> type(int)


But as someone mentionned, the problem is the same with other built-in  
functions, such as chr, even in the latest Python version.

I still find that a little counter-intuitive to have different behaviours  
for a built-in function and a Python function. I really would expect them  
to work (or not to work) the same in all situations, even if I now  
understand better how all works behind the scenes. But I'll live with it...

[snip]
> If you understood all my explanations, you now know how to solve the
> problem.
>
> Else, here the solution:
>
> class C3(C):
>   f = lambda self, x: return x

This is actually the first thing I did, but it seemed a bit weird to me to  
have a - let's say - callable with one parameter in one case and another  
with two parameters in the other one. So I finally turned my callable  
attribute into a real instance method, just for consistency.

Anyway, thanks a lot for your explanations.
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GUI Program Error

2006-06-08 Thread Eric Brunel
On Wed, 07 Jun 2006 17:38:39 GMT, John Salerno <[EMAIL PROTECTED]>  
wrote:
[snip]
> But I will agree with you that it is confusing when it says, following  
> the top = Tk() line, "Notice that a new blank window has appeared",  
> because as you noticed, nothing appears yet. My only guess is that this  
> is either a mistake, or the tutorial is a little old, because I think  
> Tkinter used to behave differently in the interactive prompt than it  
> does now.

It may be a platform-specific issue: On Unix/Linux, a window *does* appear  
when you instantiate Tk, at least with tcl/tk 8.3 and 8.4 (which is the  
latest stable version AFAIK).
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making a Label that looks the same as a button.

2006-06-13 Thread Eric Brunel
On 13 Jun 2006 06:14:03 -0700, Dustan <[EMAIL PROTECTED]> wrote:

> I have a Button object that gets replaced by a Label when clicked.
>
> Button(buttonsframe,text=' ',command=c,font=buttonsFont)
> Note that the text is a single space. buttonsFont uses 'Courier New' as
> a family.
>
> When clicked, the Button is destroyed and replaced with a Label object:
> Label(buttonsframe,text=x,font=buttonsFont,relief=RAISED)
>
> The intent is for the Label object to look identical to the button
> object, except for the non-space character x. The Label object is a
> little smaller than the Button object. When I set borderwidth, the
> label object does increase in size, but that's not going to make it
> look the same, since it makes the border thicker.
>
> How do I get the Label object to look just like the Button object?

There is least two other options that are different for Labels and Buttons:

>>> b = Button(root)
>>> b.cget('padx')
'3m'
>>> b.cget('pady')
'1m'
>>> l = Label(root)
>>> l.cget('padx')
'1'
>>> l.cget('pady')
'1'

The padx and pady are the distance between the text and the widget  
borders. They are larger on a Button.

BTW, you can get all configuration options for any widget with:

for k in widget.configure().keys():
   print k, ':', widget.cget(k)

So you can easily compare common options between a standard Label and a  
standard Button.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter - Button Overrelief

2006-06-27 Thread Eric Brunel
On Tue, 27 Jun 2006 14:06:05 +0200, Fuzzyman <[EMAIL PROTECTED]> wrote:

> Hello all,
>
> I have some Tkinter buttons that display images. I would like to change
> these to 'active' images when the mouse is over the button.
>
> I see that the button widget can take an 'overrelief' argument in the
> constructor. What values can this take ?

The same as the 'relief' option, i.e the ones described here:
http://www.tcl.tk/man/tcl8.4/TkCmd/options.htm#M-relief

Note that Tkinter contains symbolic constants for these values: 'raised'  
is Tkinter.RAISED, 'flat' is Tkinter.FLAT, and so on.

> Also - can anyone provide an example of using the equivalent of a
> 'mouseover' event to change the image used by a button in Tkinter ? I'm
> afraid google has not helped me much here.

The events you're after are '' and ''; see here:
http://www.tcl.tk/man/tcl8.3/TkCmd/bind.htm#M7

Here is an example showing how to change the button text (changing the  
image is similar):


 from Tkinter import *

root = Tk()

b = Button(root, width=8, text='foo')
b.pack()

def enterB(event):
   b.configure(text='bar')

def leaveB(event):
   b.configure(text='foo')

b.bind('', enterB)
b.bind('', leaveB)

root.mainloop()


HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simple script - Tkinter question.

2006-07-03 Thread Eric Brunel
On Tue, 04 Jul 2006 05:02:39 +0200, jkuo22 <[EMAIL PROTECTED]> wrote:

> Hi everyone,
>
> Here is my simple Tkinter script:
>
> ## start of entry.py
> from Tkinter import *
> root=Tk()
> e1=Entry(root, width=16)
> e1.pack()
> e2=Entry(root, width=16)
> e2.pack()
> mainloop()
> ## end
>
> First, it works on win2k. When I run it as 'python entry.py' on linux,
> both 'e1' and 'e2' appear perfectly except I cannot enter any
> character in 'e1' entry, but 'e2' entry is ok.
>
> Second, when I run it in python interactive shell LINE BY LINE, then
> 'e1' and 'e2' entry both can accept user input, no problem! But when I
> copy and paste it into interactive shell, then the first situation
> happens again.
>
> So..., has anyone ever run into this problem like me? and how do you
> fix it? I use python2.3.4 now.

It works without problem for me... What is the Linux distribution you're  
using? And with which window manager? And what is your tcl/tk version? For  
the latter, you can get it with:

 from Tkinter import *
root = Tk()
root.tk.eval('puts $tk_patchLevel')
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help Needed !!! Browsing and Selecting More Than One File

2006-07-06 Thread Eric Brunel
(Please quote at least a significant part of the message you're replying  
to, or people will have trouble understanding what you're talking about...)

On Thu, 06 Jul 2006 15:42:28 +0200, Kilicaslan Fatih <[EMAIL PROTECTED]>  
wrote:
> Dear Diez B. Roggisch,
>
> After clicking a button on the GUI the user can browse
> and than select a ".c" file to assign to the other
> program I have mentioned.
>
> But in this way I can only select one file. I don't
> know how to implement this application for all of the
> "*.c" files in a folder. Do I need to write a for loop
> for this? Or maybe I can create a list after
> sequentially browsing files and than assign this list
> as a parameter to the function I am executing.

What has it to do with running your program with several file names as  
arguments? Is it two different ways to select several files in your  
application? Or do you want one or the other?

> Here is a part of the code, I am new to Python and
> OOP. Sorry for the ambiguity in my question.
>
> class App:
>
> #Browsing the file, this is triggered
> #through a menu
> def browseFile(self):
> global file

This is unrelated to your question, but why do you use a global variable  
in a class? Can't you use an instance attribute, or a class attribute? And  
BTW, file is the name of a built-in, so using it to name a variable is a  
bad idea.

> file = askopenfilename(filetypes = [("C source
> code", "*.c"), ("All Files", "*.*")])

So is it a third way of selecting multiple files? Anyway, if you want to  
be able to select multiple files via askopenfilename, use  
askopenfilename(..., multiple=1). The value returned by the function will  
then be a sequence of file names.

> #Running the CC program
> #This is triggered by a button push
>def runCC(self, event):
>if type(file)==str:

Unrelated to your question again, but explicitely testing the type of a  
variable is usually a bad idea. What can be stored in file? I'd set it to  
None in the beginning, then test "if file is not None:" instead of testing  
its type.

> dosya = file
> cmd = 'cc ' + dosya
> return os.system(cmd)
> else:
> message = tkMessageBox.showinfo("Window
> Text", "Please Browse a File Firstly")
> print message

This line will always print None (or an empty string maybe), as  
tkMessageBox.showinfo doesn't return anything. No print is needed here, as  
showinfo already displays the message in a dialog.

You also have a branch of the 'if' explicitely returning something (the  
result of the os.system call) and the other one not returning anything,  
i.e implicitely returning None. Is there a reason for that? This is -  
again - usually a bad idea as it makes your code difficult to understand.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and CORBA

2006-09-21 Thread Eric Brunel
On Thu, 21 Sep 2006 10:48:55 +0200, rodmc <[EMAIL PROTECTED]>  
wrote:

> Can anyone recommend an easy to install COBRA implementation which
> works with Python? I am using Windows XP.

I used to use fnorb (http://sourceforge.net/projects/fnorb), but the  
project seems to be dead. It still seems to work quite well, but I didn't  
test it on the latest Python versions.

And it does meet your requirements: since it's a Python-only ORB, it's  
really easy to install. You basically just have to put it somewhere in  
your PYTHONPATH.

> Thanks in advance.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and CORBA

2006-09-22 Thread Eric Brunel
On Thu, 21 Sep 2006 15:11:07 +0200, Diez B. Roggisch <[EMAIL PROTECTED]>  
wrote:
> AFAIK Fnorb also had license issues - I'm not entirely sure of that, but
> better check it.

The earlier versions seem to have been somewhat proprietary, but the  
latest one should be as free as Python is. Extract from the license  
agreement (just before the legalese starts):

"""
The intent of this license is to grant you the same freedoms to use fnOrb
that you enjoy under the Python 2.2 License  
(http://www.python.org/2.2/license.html).
"""

So there should be no problem with that (AFAICT, but I'm no lawyer...)

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to change menu text with Tkinter?

2006-09-27 Thread Eric Brunel
On Wed, 27 Sep 2006 15:29:32 +0200, Phil Schmidt  
<[EMAIL PROTECTED]> wrote:

> I am making a little Tkinter GUI app that needs to be in several
> languages (english, french, etc.), adjustable at runtime via a menu
> pick to select the language. The only way I can see to change text in
> the menus entries is to destroy them and recreate them usiing different
> labels. This seems very clunky though, and there must be a better way.
> Can anyone offer any pointers or a short example for how to do this?

Here is a way:

--
 from Tkinter import *

root = Tk()
mb = Menu(root)
root.configure(menu=mb)
fm = Menu(mb)
mb.add_cascade(label='File', menu=fm)

def chlg():
   mb.entryconfigure(1, label='Fichier')
   fm.entryconfigure(1, label='Changer de langue')
   fm.entryconfigure(2, label='Quitter')

fm.add_command(label='Change language', command=chlg)
fm.add_command(label='Quit', command=root.quit)

root.mainloop()
--

Note that the entry indices start at 1 because of the 'tearoff' entry that  
is always created in a menu. If you specify the option tearoff=0 when  
creating the menus, indices will start ot 0.

But Marc's answer still applies: it's a lot of work for something that  
will usually be configured once. So requiring to restart the tool when the  
UI language changes should be acceptable.

> Thanks,
> Phil

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >