How to divide data into three lines?

Question:

I’m making a database for my cadet corps, because our officers’ organisation is a MESS and I want to organise things and I’m making a menu with buttons labeled after each master cadets. To make it aesthetically pleasing, I wanted to split it into three lines, but I keep messing it up.

Here’s the ̶s̶p̶a̶g̶h̶e̶t̶t̶i̶ code in question

import PySimpleGUI as sg

SO = ["LastName1","FirstName"]
Mettraux = ["LastName2","FirstName"]
JayForbes =["LastName3","FirstName"]
JacForbes =["LastName4","FirstName"]
Callahan = ["LastName5","FirstName"]
Foster = ["LastName6","FirstName"]
MB = ["LastName7","FirstName"]
Peever = ["LastName8","FirstName"]
Carron = ["LastName9","FirstName"]
Woodward = ["LastName10","FirstName"]
Poire = ["LastName11","FirstName"]
KA = ["LastName12","FirstName"]
Cabanaw = ["LastName13","FirstName"]
Veldman = ["LastName14","FirstName"]

MCadets = [SO,Mettraux,JayForbes,JacForbes,Callahan,Foster,MB,Peever,Carron,Woodward,Poire,KA,Cabanaw,Veldman]
MCadets = sorted(MCadets)

cadetsButtons = []
for i in MCadets:
    cadetsButtonsSection = []
    fullName = i[0],", ",i[1]
    fullName = "".join(fullName)
    cadetsButtonsSection.append(sg.Button(f"{fullName}"))
    cadetsButtons.append(cadetsButtonsSection)
    cadetsButtonsSection = []

mainMenu = [[sg.Text("Hello, who would you like to check?")],
            [cadetsButtons]
            ]

sg.Window("Master Cadets Database - Main Menu",mainMenu).read()

I tried a whole sort of blind tinkering without getting the wished result, which is to have the names as evenly split as possible between three lines.

Here’s what it currently looks like:
Names stacking on top of eachother

Asked By: Kevin Mettraux

||

Answers:

Confirm your layout is in list of lists of elements.

Check if next line by index of an element:

import PySimpleGUI as sg


names = [f'Lastname{i+1:0>2d}, Firstname{i+1:0>2d}' for i in range(14)]
total = len(names)
lines = 3
width = (total//lines + 1) if len(names) % lines else (total//lines)    # buttons per row

buttons, line = [], []
limit = total - 1
for i, name in enumerate(names):
    line.append(sg.Button(names[i]))
    if i % width == width-1 or i == limit:
        buttons.append(line)
        line = []

layout = [[sg.Text("Hello, who would you like to check?")]] + buttons
sg.Window("Master Cadets Database - Main Menu", layout).read(close=True)

enter image description here

Answered By: Jason Yang
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.