Tkinter的弹出窗口位于主窗口的中心位置

import tkinter as tk

#  - functions  -

def on_click():
    # get main window position
    root_x = root.winfo_rootx()
    root_y = root.winfo_rooty()

    # add offset
    win_x = root_x + 300
    win_y = root_y + 100

    win = tk.Toplevel()

    # set toplevel in new position
    win.geometry(f'+{win_x}+{win_y}')

    button = tk.Button(win, text='OK', command=win.destroy)
    button.pack()

#  - main  -

root = tk.Tk()
root.geometry('800x600')           # only size
#root.geometry('+100+200')         # only position
#root.geometry('800x600+100+200')  # both: size and position

button = tk.Button(root, text='OK', command=on_click)
button.pack()

root.mainloop()   

评论