How to create a running total of selections made by the user?

I have a dropdown menu and a button as follows:

import panel as pn
pn.extension()


select = pn.widgets.Select(options=["a", "b", "c"])
button = pn.widgets.Button(name='Confirm selection')

def add(event):
    choice = select.value
    return choice


selection = pn.bind(add, button)

panel = pn.WidgetBox(pn.Column(
    select,
    button,
    selection,
))

panel

I can show the most recent selection in a panel by using selection or access this value in python using selection().

The panel looks like this:

afbeelding

However, I now want to extend this code such that I can concatenate results. I tried the following code:

name = ""

def calculateTotal(event):
    name += selection()
    return name

button.on_click(calculateTotal)

But this generates the error: UnboundLocalError: local variable 'name' referenced before assignment

I managed to solve it with a global variable:

def calculateTotal(event):
    global name # this line solves the problem
    name += selection()
    return name

button.on_click(calculateTotal)

Instead of global variable, you may want to wrap everything in a class and use self.name

I have seen some people uses OOP, but I am still wraping my head around the callbacks. For example, I did not expect the functions add() and calculateTotal() to require an argument that is not (visibly) used in my code. In my opinion this is a little bit difficult when first starting out with Holoviz panels.

I will look into classes at a later time. Thanks for the tip!

1 Like