[Tutor] passing data to Python callback

Gregor Lingl glingl@aon.at
Fri Feb 21 16:05:03 2003


vicki@stanfield.net schrieb:

>First, I apologize for my errant post earlier and for
>the wrong subject on my follow-up message. I am not an
>idiot - I just play one on this list.
>
>Now my question:
>
>How do you pass data to a callback? Is it done in the
>bind statement? I have done this in Motif, but I am new
>to this Python/Tkinter thing.
>

I'll try to describe one way, how this can be done:

# (1) Bundle your data as attributes of some object:
# First you have to create a class:

class Xyz:
    def __init__(self, data1, data2, etc):
        self.data1 = data1
        self.data2 = data2
        self.etc = self.etc
# (2) Create a method as callback:
    def callback(self, event).
        #... the code
        # has access to all the data contained in the event-object (see 
Alan's statement)
        # but also to all the data, which are attributes of self ...

# (3)  Create an object (an instance of this class):
# with your data as arguments:

something = Xyz(value1, value2, more)

# Now something.callback is exacly what bind expects:
# ... a function-object with *one* parameter, to which an event is to be 
assigned ...
# as the first parameter is already assignet to *something* ;-)

CommandListbox.bind('<Button-1'>, something.callback)

Here a q&d example:

########################
from Tkinter import *

message="Hello World"

class Message:
    def __init__(self,message,label):
        self.message = message
        self.label = label
    def callback(self,event):
        self.label["text"] = self.message

root = Tk()
label = Label(root, width=20)
label.pack()
m = Message(message,label)
root.bind('<Button-1>', m.callback)

root.mainloop()
#########################

More on Tkinter you can find at "hinking in Tkinter":
http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html

Hope that helps,
Gregor



>
>Here is a code snippet:
>
>---------------
>CommandListbox = Listbox(Frame1) 
>CommandListbox.insert("end","First entry")
>CommandListbox.insert("end","Second entry")
>CommandListbox.pack()
>index = CommandListbox.index('active')
>CommandListbox.bind('<Button-1>',
>CommandListboxCallback)
>---------------
>
>What I would like to do is pass the index of the
>selected entry to the callback, so how do I pass
>additional information beyond the event?
>
>Thank you.
>
>--vicki
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>