pythonbeeware

on_double_click on table in python/beeware


I want to access data from a row of my table and display it in the terminal when that row is double-clicked.

import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW

class HelloWorld(toga.App):

    def startup(self):
        # Create a table with sample data
        data = [
            ['John', 'Doe', 30],
            ['Jane', 'Smith', 25],
            ['Alice', 'Johnson', 35]
        ]
        table = toga.Table(headings=['First Name', 'Last Name', 'Age'], data=data, on_double_click=self.clicked)

        # Create a main box and add the table to it
        main_box = toga.Box(children=[table], style=Pack(direction=COLUMN))

        self.main_window = toga.MainWindow(title=self.formal_name)
        self.main_window.content = main_box
        self.main_window.show()

    def clicked(self, table, row):
        print("Clicked row", row, "of table", table)


def main():
    app = HelloWorld()
    app.main_loop()

I have this output in the terminal, I need the line data and not just object numbers.

Clicked row <toga.sources.list_source.Row object at 0x000001E04101C750> of table Table:0x1e04100a850


Solution

  • I have not tried this, and I'm not willing to install toga to do so, but here is the kind of thing you need. Note the changes in main and the addition of the clicked method. Please check the documentation to learn how to use the parameters to the callback.

    import toga
    from toga.style import Pack
    from toga.style.pack import COLUMN, ROW
    
    
    class HelloWorld(toga.App):
    
        def startup(self):
            # Create a table with sample data
            data = [
                ['John', 'Doe', 30],
                ['Jane', 'Smith', 25],
                ['Alice', 'Johnson', 35]
            ]
            table = toga.Table(headings=['First Name', 'Last Name', 'Age'], data=data, on_double_click=self.clicked)
    
            # Create a main box and add the table to it
            main_box = toga.Box(children=[table], style=Pack(direction=COLUMN))
    
            self.main_window = toga.MainWindow(title=self.formal_name)
            self.main_window.content = main_box
            self.main_window.show()
    
        def clicked(self, table, row):
            print( "Clicked row", row, "of table" table )
    
    
    def main():
        app = HelloWorld()
        app.main_loop()