简体   繁体   中英

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.

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.

#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)

It took me pretty much time to get my head around actual implementation of this. So I wanted to share my final code. Based on DyZ suggestion.

I didn't use <Configure> event as suggested because only saving before quit is enough for me.

class Window(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # ...
        # bla bla bla
        # My GUI codes came here
        # ...

        # Try to load last saved window data
        self.statusbar['text']="reading ini file..."
        ini_file_path = "mapedit.ini"
        try:
            # if the file is there
            # get geometry from file 
            ini_file = open(ini_file_path,'r')
            self.geometry(ini_file.read())
            self.statusbar['text']= "ini file read"
            ini_file.close()
        except:
            # if the file is not there, create the file and use default
            # then use default geometry.
            self.statusbar['text']="ini file not found. New file created."
            ini_file = open(ini_file_path, 'w')
            ini_file.close()
            self.geometry("640x400+100+200")

    def client_exit(self):
        self.save_geo()
        self.destroy()

    def save_geo(self):
        # save current geometry to the ini file 
        try:
            with open("mapedit.ini", 'w') as ini_file:
                ini_file.write(self.geometry())
                self.statusbar['text']="geo sv"
                ini_file.close()
        except:
            statusbar['text']="ini file not found"

'''
   This is where I created GUI instance
'''
if __name__ == "__main__":
    win = Window()
    # attach deletion handler to 'client_exit' method
    win.protocol("WM_DELETE_WINDOW", win.client_exit)
    win.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM