使用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
相关产品推荐
相关产品推荐

