Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remember tkinter window position in python 3?

I have a tkinter gui and I would like it to retain the original window position and size upon relaunching.

Here is an answer that illustrates how to set a specific position and dimensions, but not a word about remembering the settings: How to specify where a Tkinter window opens?

Highly appreciate any help.

like image 985
Anonymous Avatar asked Feb 04 '23 18:02

Anonymous


2 Answers

The only way to remember settings from session to session is to write them into a file. So, get the root window geometry (it's a string) and write it into a file. If you want the function to be executed automatically as a hook, bind it to the "<Configure>" event:

def save_size(event):
  with open("myapp.conf", "w") as conf:
    conf.write(root.geometry()) # Assuming root is the root window

root.bind("<Configure>",save_size)

You can later read the geometry from the file and restore it.

like image 77
DYZ Avatar answered Feb 07 '23 07:02

DYZ


#Here I save the x and y position of the window to a file "myapp.conf"
#Here I see if the file exists.
if os.path.isfile("myapp.conf"): 
    #Here I read the X and Y positon of the window from when I last closed it.
    with open("myapp.conf", "r") as conf: 
        root.geometry(conf.read())
else:
    #Default window position.
    root.geometry('610x270+0+0')

def on_close():
     #custom close options, here's one example:
     #close = messagebox.askokcancel("Close", "Would you like to close the program?")
     #if close:
        #Here I write the X Y position of the window to a file "myapp.conf"
        with open("myapp.conf", "w") as conf: 
            conf.write(root.geometry())

        root.destroy()          

root.protocol("WM_DELETE_WINDOW",  on_close)
like image 31
Thomas Grant Avatar answered Feb 07 '23 06:02

Thomas Grant