How to get the Tkinter widget's current x and y coordinates?


Tkinter is widely used to create GUI based applications. It has many toolkits and functions or modules available which can be used to define the different attributes of a particular application. For building GUI applications it provides some widgets including buttons, text boxes and labels. We can customize the position of the widget and its coordinates on the tkinter frame using other functions and libraries.

Let us suppose that we have created a text label widget which is having some position in the tkinter frame. Now, to get the actual coordinates of the widget, we can use the geometry methods available in the tkinter’s library.

We will use winfo_rootx() and winfo_rooty() functions which return the actual coordinates of the widget with respect to the frame or window.

Example

#Import the tkinter library
from tkinter import *

#Create an instance of the tkinter frame
win = Tk()

#Define the geometry of the frame
win.geometry("600x400")

#Define the text-widget
my_text= Text(win, height = 5, width = 52)

# Create label
lab = Label(win, text ="TutorialsPoint.com")

#Configure it using other properties
lab.config(font =("Helvetica", 20))

#Create a button widget
my_button = Button(text="Hello")

#Define the position of the widget
my_button.place(x=100, y=100)

#Update the coordinates with respect to the tkinter frame
win.update()

#Get the coordinates of both text widget and button widget
widget_x1, widget_y1 = my_button.winfo_rootx(),
my_button.winfo_rooty()
widget_x2, widget_y2 = my_text.winfo_rootx(),
my_button.winfo_rooty()

lab.pack()

print(widget_x1, widget_y1)
print(widget_x2, widget_y2)

#Keep the window running
win.mainloop()

Output

Running the above code snippet will print the current position of widget as,

134 157
0 157

Updated on: 06-Mar-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements