views:

22

answers:

1

Hey all,

As the title says, I'm grabbing the cursor location within a motion triggered event handler in Tkinter. I'd like to update an existing label widget with the location, however I cannot for the life of me figure out how to edit the label's text field (or any external object for that matter) within the event handler. From what I understand, event is the only argument passed to the handler, which means I can't pass the label object. How do I access objects outside of the handler?

Apologize for the noobish question as I'm a C programmer new to Python. Thanks!

+1  A: 

Tkinter won't pass around objects in event handler, and anyway how it would know in which object you are interested in?

Instead it is your responsibility to access the objects you wish to update from event handler, e.g. your event handler could be simple function and it could access global object, or it can be a method of an object and can access that object via self.

Here is a way using global objects

from Tkinter import *

root = Tk()
frame = Frame(root)
frame.configure(width=300,height=300)

def onmotion(event):
    root.title("Mouse at %s,%s"%(event.x, event.y))

frame.bind("<Motion>", onmotion)
frame.pack()
root.title("Event test")
root.mainloop()

Same thing can be done in an object oriented way

from Tkinter import *

class MyFrame(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        self.parent = root
        self.configure(width=300,height=300)
        self.pack()
        self.bind("<Motion>", self.onmotion)

    def onmotion(self, event):
        self.parent.title("Mouse at %s,%s"%(event.x, event.y))

root = Tk()
frame = MyFrame(root)
root.title("Event test")
root.mainloop()
Anurag Uniyal