How to center launch second window in the middle of the main window with python 3 tkinter/guizero?

331 Views Asked by At

I am trying to open a second window in the center of the main window. It needs to work where ever the main window is located and for what ever the main window's size is. I have set up some some test widget to make sure that when the second window is close it enables all the main windows functionality.

What I'm using.

Example of what I'm trying to do.

enter image description here

My code.

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
    


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


app.display()
1

There are 1 best solutions below

1
On BEST ANSWER

This code creates a new window that is in the center of the old one. The problem is that it uses pure tkinter instead of guizero.

import tkinter as tk

def create_second_window():
    new_root = tk.Toplevel()
    new_root.update()
    x = root.winfo_rootx() + root.winfo_width()/2 - new_root.winfo_width()/2
    y = root.winfo_rooty() + root.winfo_width()/2 - new_root.winfo_height()/2

    new_root.geometry("+%i+%i" % (x, y))

root = tk.Tk()
root.geometry("500x500")

button = tk.Button(root, text="Click me", command=create_second_window)
button.pack()

root.mainloop()

Updated for 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'
    
    x = app.tk.winfo_rootx() + app.tk.winfo_width()/2 - secondWindow.tk.winfo_width()/2
    y = app.tk.winfo_rooty() + app.tk.winfo_width()/2 - secondWindow.tk.winfo_height()/2

    secondWindow.tk.geometry("+%i+%i" % (x, y))

    
    
    secondWindow.tk.grab_set()
    app.disable()
    secondWindow.when_closed=SecondWindow_closed
    


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





app.display()