Anonymous Coder
Anonymous Coder

Reputation: 542

Why are widget.winfo_rootx() and widget.winfo_rootx() always 0 in tkinter?

Here is my code:

from tkinter import *

root = Tk()
a = Button(text=str(1))
a.place(x=100, y=100)
widget_x, widget_y = a.winfo_rootx(), a.winfo_rooty()
print(widget_x, widget_y)
root.mainloop()

The output is always 0 0. Why is this and how can I fix it?

Upvotes: 3

Views: 5632

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386030

The value is zero because you're getting the coordinates before the window has been made visible. You can solve this one of two ways: don't get the coordinates until after mainloop has started (with after_idle), or force the window to be drawn to the screen by calling update.

Example:

from tkinter import *

root = Tk()
a = Button(text=str(1))
a.place(x=100, y=100)

root.update()
widget_x, widget_y = a.winfo_rootx(), a.winfo_rooty()
print(widget_x, widget_y)

root.mainloop()

Upvotes: 7

Related Questions