python 如何将数据分成三行?

c8ib6hqw  于 2023-03-07  发布在  Python
关注(0)|答案(1)|浏览(180)

我正在为我的学员团制作一个数据库,因为我们的军官组织是一个混乱的组织,我想把事情组织起来,我正在制作一个菜单,每个按钮都标在每个高级学员的名字后面。为了美观,我想把它分成三行,但我总是把它弄乱。
以下是所讨论的s p a g h e t i代码

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()

我尝试了一整套盲目的修修补补,但没有得到希望的结果,那就是让名字尽可能均匀地分在三行中。
以下是它当前的样子:Names stacking on top of eachother

5kgi1eie

5kgi1eie1#

确认布局在list of lists of elements中。
检查元素索引的下一行:

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)

相关问题