billhett
billhett

Reputation: 13

Getting PySimpleGUI Listbox to list object attributes

I am trying to understand how to use objects in python with a PySimpleGUI application. I have a list of trip objects, each with three attributes - trip_no, date, driver.

class Trip:
def __init__(self,trip_no,date,driver):
    self.trip_no=trip_no
    self.date=date
    self.driver=driver

I create a list of trip objects:

trips=[Trip('1','11/22/12','Dave'),Trip('2','10/13/14','Joe'),Trip('3','12/14/16','Dave')]

I can search and retrieve the attributes for a given trip, but in the listbox I only get the references to the objects as in <main.Trip object at 0x10b2bacc0>. I can't work out how to list the attibutes (trip.trip_no, trip.date, trip.driver) in the listbox.

shot of form

The examples I have found work for a list with three lists, each with the three string elements:

[['1','11/22/12','Dave'],['2','10/13/14','Joe'],['3','12/14/16','Dave']]

but is there a way to display the attributes directly?

Thanks for any assistance.

Upvotes: 1

Views: 788

Answers (1)

Jason Yang
Jason Yang

Reputation: 13061

Define function __repr__ to show what the representation for an object.

import PySimpleGUI as sg

class Trip:

    def __init__(self,trip_no,date,driver):
        self.trip_no=trip_no
        self.date=date
        self.driver=driver

    def __repr__(self):
        return f"trip_no:{self.trip_no}, date:{self.date}, driver:{self.driver}"

trips=[Trip('1','11/22/12','Dave'),Trip('2','10/13/14','Joe'),Trip('3','12/14/16','Dave')]

sg.theme("DarkBlue3")
sg.set_options(font=("Courier New", 12))

layout = [[sg.Listbox(trips, size=(40, 3))]]
window = sg.Window('Title', layout, finalize=True)

while True:

    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    print(event, values)

window.close()

enter image description here

Upvotes: 2

Related Questions