You need to enable JavaScript to run this app. 使用Python3 tkinter/guizero如何在主窗口中央居中弹出第二个窗口?
优惠活动
大模型
产品
解决方案
定价
更多

使用Python3 tkinter/guizero如何在主窗口中央居中弹出第二个窗口?

实现子窗口相对主窗口居中方案

只需要在你现有代码的子窗口创建逻辑中,新增位置计算代码即可,适配主窗口任意位置、任意尺寸的场景:

完整可运行代码

from guizero import *

app = App(bg='#121212',title='Main window',width=575,height=550)
app.tk.resizable(False, False)

def SecondWindow_closed():
    secondWindow.destroy()
    app.enable()
    app.focus()

def System_secondWindow():
    global secondWindow
    secondWindow = Window(app,bg='#121212',title='Settings window',width=355,height=425)
    secondWindow.tk.resizable(False, False)
    About_project=Text(secondWindow,text='About this project ',align='bottom')
    About_project.text_color='white'
    secondWindow.tk.grab_set()
    secondWindow.when_closed=SecondWindow_closed
    
    # 新增相对主窗口居中逻辑
    main_win_x = app.tk.winfo_x()
    main_win_y = app.tk.winfo_y()
    main_win_width = app.tk.winfo_width()
    main_win_height = app.tk.winfo_height()
    child_win_width = 355
    child_win_height = 425
    # 计算子窗口左上角坐标
    child_win_x = main_win_x + (main_win_width - child_win_width) // 2
    child_win_y = main_win_y + (main_win_height - child_win_height) // 2
    # 应用位置设置
    secondWindow.tk.geometry(f"{child_win_width}x{child_win_height}+{child_win_x}+{child_win_y}")


Settings_button = PushButton(app, text='Settings ⚙',command=System_secondWindow)
Settings_button.text_color='white'
Test_widget=TextBox(app,)
Test_widget.bg='white'


app.display()

实现说明

  • winfo_x()/winfo_y() 可以实时获取窗口当前在桌面的左上角坐标
  • winfo_width()/winfo_height() 可以实时获取窗口的当前尺寸
  • 计算得到子窗口居中所需的左上角坐标后,通过geometry方法直接设置即可生效

内容的提问来源于stack exchange,提问作者PurpleLlama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 11:54:07