How to access an external object in an event handler?

As the name says, I capture the location of the cursor in an event handler triggered by movement in Tkinter.

I want to update an existing location label shortcut. However, I can’t understand all my life how to edit the Label text field (or any external object, for that matter) in the event handler. From what I understand, the event is the only argument passed to the handler, which means that I cannot pass the label object.

How do I access objects outside the handler?

+4
source share
1 answer

Tkinter will not pass objects in the event handler, and no matter how it knows which object you are interested in?

Instead, you are responsible for accessing the objects you want to update from the event handler, for example. your event handler can be a simple function, and it can access a global object or it can be a method of an object and can access that object through self.

Here is a way to use 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() 

The 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() 
+3
source

Source: https://habr.com/ru/post/1307245/


All Articles