tkinter call backs

Timothy R Evans tre17 at pc142.cosc.canterbury.ac.nz
Tue Jul 20 20:40:25 EDT 1999


"Gordon Williams" <g_will at cyberus.ca> writes:

> I have a simple problem that I cant find the solution.  I have a menu item
> to open a file which has a command "openfile".  I would like to activate
> "tkFileDialog.askopenfilename" to get the name of the file.  This requires
> "parent=root" or something like that for the position of the message box.
> 
> How do I pass "root" into openfile?  
> 
> Thanks
> Gordon Williams
> 
> 
> 
> def openfile():
>     print "opening file"
>     fileName=tkFileDialog.askopenfilename(parent=root, title="Open")
>     if fileName:    #checks for cancel
>         print fileName  #name of file to open
>         file=open(fileName, 'r')
>         read='junk' #initialize read with something
>         while read != "":
>             read=file.readline()
>             print "number1",read[0:-1] # strips off line return character
> #       This has one more line than needed due to EOF line.
> #       Will use seek() to move to 2nd line
>         print "number of bytes ",file.tell()
>         file.close()

I get from this that you are wanting a Tkinter callback to execute
somthing like foo(bar) rather than just foo().  The Command class I
posted twice before does this:

class Command:
    def __init__(self, func, *args, **kw):
        self.func = func
        self.args = args
        self.kw = kw
                       
    def __call__(self, *args, **kw):
        args = self.args + args
        kw.update(self.kw)
        apply(self.func, args, kw)

Used as following:

...
Button(text='foo', command=Command(myfunction, myarg))
...

The args (including keywords) that are passed to the Command class are
passed on to myfunction when the callback is activated.

I'm wondering if this should be part of Tkinter in some way?

--
Tim Evans




More information about the Python-list mailing list