Search code examples
pythonuser-interfaceguizero

Python Guizero - How do you centre buttons to the middle of a window


I am coding in python using the guizero library. I have created two simple buttons; one for the menu and one for the stats. I would like to centre the two buttons within the window so that they will be in the top-middle area and sit next to each other side by side.

Current result and desired result

from guizero import *


def open_menu():
    print("Menu has been opened")
    Menu.disable()
    Stats.enable()


def open_stats():
    print("Stats has been opened")
    Menu.enable()
    Stats.disable()


app = App(layout="grid")
Menu = PushButton(app, command=open_menu, text="Menu", grid=[0, 1])
Stats = PushButton(app, command=open_stats, text="Stats", grid=[1, 1])
Stats.disable()
app.display()

Solution

  • You can do this by putting the buttons in a Box.

    app = App()
    center_box = Box(app, layout = "grid")
    Menu = PushButton(center_box, command=open_menu, text="Menu", grid=[0, 1])
    Stats = PushButton(center_box, command=open_stats, text="Stats", grid=[1, 1])
    

    The buttons inside the box have the grid layout, so display side by side like you want them to, but the box has auto layout, so is centred in the window.