I am somewhat new to python still, and am working on a project including a GUI. I using with Tkinter and buttons a lot, and am curious if there was a way to run a function with a bind because I want one thing to happen when it is presses and something else when it is released.
s = str(x+1) + ":" + str(y+1) img = ImageTk.PhotoImage(Image.open('button.png')) b = Tkinter.Button(field_hid, image=img, borderwidth=0, highlightthickness=0, background='grey') b.bind("<ButtonPress-1>", lambda s=s, button=b: location_down(event,s,button)) b.bind("<ButtonRelease-1>", lambda s=s, button=b: location_up(event,s,button)) b.img = img b.pack() b.grid(row=x, column=y)
I don’t understand how I am to do this, as the only thing that can be passed to the function is the event, but my program requires the arguments.
Advertisement
Answer
The only way to use bind is to have it call a function. When you use lambda
you are just creating an anonymous function. You can easily do:
b.bind("<ButtonPress-1>", self.SomeOtherFunction)
lambda
is useful when you want to pass additional arguments to the function. Unlike when using the command
option, with bindings you get an event object with lots of useful information so you may not need to pass any additional information.
For example, you could do this:
def OnPress(event): print "widget %s was pressed" % event.widget def OnRelease(event): print "widget %s was released" % event.widget b = Button(...) b.bind("<ButtonPress-1>", OnPress) b.bind("<ButtonRelease-1>", OnRelease)
For a good introduction to binding see Events and Bindings on effbot.org.