How to get the exact coordinate of where a Tkinter widget begins and ends

Viewed 58

I want to find the exact coordinates of the following parts of widgets as shown in the image in blue circles. I cannot figure out how to do this I have tried the following:

self.winfo_x()
self.winfo_y()
self.winfo_xy()

All of these will not give the answer and I do not know any other ways after any of my research. I am making a custom way to drag widgets and I am creating a containment system and need the beginning and end points.

Image(I could not show, I don't have the reputation needed):https://i.stack.imgur.com/ID3kX.png EDIT: Here is the picture of my code, I implemented the answer below by using hypothetical button called s: https://i.stack.imgur.com/mnIaf.png

1 Answers

You can use the method winfo_x to get the x coordinate of the window relative to its parent. You can use winfo.parent to get the name of the parent window, and the method nametowidget to convert that to a widget. The solution is to combine those to recursively get the x or y coordinate of the widget and every parent.

It might look something like this:

def absolute_x(widget):
    if widget == widget.winfo_toplevel():
        # top of the widget hierarchy for this window
        return 0
    return widget.winfo_x() + absolute_x(widget.nametowidget(widget.winfo_parent()))
Related