首页 > 解决方案 > 如何使 Tkinter 的弹出窗口的位置在主窗口的中心?

问题描述

我想知道如何使弹出窗口相对于主窗口的位置。当我尝试它时,弹出窗口会出现在我电脑屏幕的一角。这是我的代码。

def popup_bonus(self):
        win = tk.Toplevel()
        win.wm_title("Error")
        win.configure(bd=0, highlightthickness=0)
        win.overrideredirect(1)
        l = ttk.Label(win, text="Already Exists")
        l.grid(row=0, column=0)

        b = tk.Button(win, text="Okay", command=win.destroy)
        b.grid(row=1, column=0)

标签: pythontkinter

解决方案


首先获取主窗口位置

    root_x = root.winfo_rootx()
    root_y = root.winfo_rooty()

接下来向这个位置添加偏移量

    win_x = root_x + 300
    win_y = root_y + 100

最后使用新位置移动顶层窗口

    win.geometry(f'+{win_x}+{win_y}')

Doc effbot.org:基本小部件方法


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

推荐阅读