|
| 1 | +from rich.text import Text |
| 2 | +from textual import on |
| 3 | +from textual.app import App |
| 4 | +from textual.widgets import Button, Static |
| 5 | +from textual_pandas.widgets import DataFrameTable |
| 6 | +import pandas as pd |
| 7 | + |
| 8 | +df = pd.DataFrame() |
| 9 | +df["Name"] = ["Dan", "Ben", "Don", "John", "Jim", "Harry"] |
| 10 | +df["Score"] = [77, 56, 90, 99, 83, 69] |
| 11 | +df["Grade"] = ["C", "F", "A", "A", "B", "D"] |
| 12 | + |
| 13 | + |
| 14 | +class ClassApp(App): |
| 15 | + CSS = """ |
| 16 | + Button { margin: 1; } |
| 17 | + """ |
| 18 | + |
| 19 | + def compose(self): |
| 20 | + yield Static( |
| 21 | + Text("Press buttons to add and remove data.", style="bold orange1"), |
| 22 | + id="instruction_label", |
| 23 | + ) |
| 24 | + yield DataFrameTable() |
| 25 | + yield Button("Add Teachers", variant="success", id="add-btn") |
| 26 | + yield Button("Delete Teachers", variant="error", id="delete-btn") |
| 27 | + |
| 28 | + def on_mount(self): |
| 29 | + table = self.query_one(DataFrameTable) |
| 30 | + # Initially add DataFrame to DataFrameTable |
| 31 | + table.add_df(df) |
| 32 | + |
| 33 | + @on(Button.Pressed, "#add-btn") |
| 34 | + def add_to_df(self): |
| 35 | + """Add new column with data to DataFrameTable.""" |
| 36 | + col_name = "Teacher" |
| 37 | + try: |
| 38 | + df.insert( |
| 39 | + 1, |
| 40 | + "Teacher", |
| 41 | + [ |
| 42 | + "Mr. Smith", |
| 43 | + "Mr. Smith", |
| 44 | + "Mr. Smith", |
| 45 | + "Mr. Smith", |
| 46 | + "Mr. Smith", |
| 47 | + "Mr. Smith", |
| 48 | + ], |
| 49 | + ) |
| 50 | + table = self.query_one(DataFrameTable) |
| 51 | + # Update existing DataFrameTable with new DataFrame data |
| 52 | + table.update_df(df) |
| 53 | + except ValueError: |
| 54 | + self.query_one("#instruction_label", Static).update( |
| 55 | + Text(f"{col_name} column already exists!", style="bold red1") |
| 56 | + ) |
| 57 | + |
| 58 | + @on(Button.Pressed, "#delete-btn") |
| 59 | + def remove_df_col(self): |
| 60 | + """Delete column from DataFrameTable.""" |
| 61 | + try: |
| 62 | + col_name = "Teacher" |
| 63 | + df.drop(col_name, axis=1, inplace=True) |
| 64 | + table = self.query_one(DataFrameTable) |
| 65 | + # Update existing DataFrameTable with new DataFrame |
| 66 | + table.update_df(df) |
| 67 | + except KeyError: |
| 68 | + self.query_one("#instruction_label", Static).update( |
| 69 | + Text(f"{col_name} column does not exists!", style="bold red1") |
| 70 | + ) |
| 71 | + |
| 72 | + |
| 73 | +if __name__ == "__main__": |
| 74 | + app = ClassApp() |
| 75 | + app.run() |
0 commit comments