如何记住 python 3 中的 tkinter window 位置?

How to remember tkinter window position in python 3?

我有一个 tkinter gui,我希望它在重新启动时保留原来的 window 位置和大小。

这里有一个说明如何设置特定位置和尺寸的答案,但没有关于记住设置的说明:How to specify where a Tkinter window opens?

非常感谢任何帮助。

在会话之间记住设置的唯一方法是将它们写入文件。因此,获取根 window 几何图形(它是一个字符串)并将其写入文件。如果你想让函数作为一个钩子自动执行,将它绑定到“”事件:

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)

您稍后可以从文件中读取几何图形并恢复它。

我花了很多时间才真正理解这个的实际实现。所以我想分享我的最终代码。基于 DyZ 的建议。

我没有按照建议使用 <Configure> 事件,因为我只需要在退出前保存就足够了。

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