Python Forum

Full Version: Tkinter positional information issue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi again, I am having issues getting the Tkinter window position. Here is the code example (very bare bones with print statements

import tkinter as tk
import re as regexp

class test_window(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.parent = parent
        self.parent.geometry("400x500")
        self.center_points()
    def center_points(self):
        #We have the height and width of the window, we know we need 10 Hexes vertical and 8 hexes horizontal. We need to get a size for the hexes, then we offset the first hex in the xy direction by 1/2 the respective length to position it properly
        
        self.geo = regexp.findall('\d+',self.parent.geometry())
        print(self.geo)
        print(self.parent.geometry())
        print(self.parent.winfo_reqheight())
        print(self.parent.winfo_reqwidth())
        

if __name__ == "__main__":
    root = tk.Tk()
    main = test_window(root)
    root.mainloop()
For the output I am getting:

['1', '1', '0', '0']
1x1+0+0
200
200

I set the window to be 400x500... This is not the first time a widget that I have tried to get positional information out of has given me wrong information. Could someone tell me if they can reproduce this result? I am using Tkinter version 8.6 with Spyder.
use: widget_name.cget("attribute")
Because of the position information was printed before mainloop is running, the value you get is initially "1x1+0+0'. You have to do self.update_idletasks() before using geometry() to get the correct value.

self.update_idletasks()
self.geo = .....
or so:
        self.parent.geometry("400x500")
        self.parent.update_idletasks()
wuf ;-)
So to prove the theory, try a button and see if clicking (i.e. after mainloop) will provide the measurements

import tkinter as tk
import re as regexp

class test_window():
    def __init__(self, parent, *args, **kwargs):
        self.parent = parent
        self.parent.geometry("400x500")
##        self.center_points()
        tk.Button(self.parent, text="Get dimensions",
                  command=self.center_points).grid()

    def center_points(self):
        #We have the height and width of the window, we know we need 10 Hexes vertical and 8 he
##        self.parent.update_idletasks()
##        print(self.geo)
        print(self.parent.geometry())
        print(self.parent.winfo_reqheight())
        print(self.parent.winfo_reqwidth())


if __name__ == "__main__":
    root = tk.Tk()
    main = test_window(root)
    root.mainloop()