How to update the value of HTML element

Hi there,
I have a problem regarding update of the image path of my html.Img element. The logic of my app is as the follows:

  1. User needs to give some inputs.
  2. After fulfill the form, user has to click a button.
  3. After button click, a image will be generated and shown in a tab.

In the tab which contains the Img element, I’ve created a global variable which is the path of the generated image. And the initial value of it is empty. After step 2 (button click), this variable is assigned to a value. However, I don’t know why does the value of this variable is not updated.

Hi @KCL0827 welcome to the forums.

In general, the use of global variables should be omitted, have a read here:

That said, where exactly do you update your variable match_file?

Hi AIMPED,

Thank you for your reply. I think I should use call back which should return a updated value. Please see the following code

As you can see here, there is a callback of button click and in which the first output updates the content of tab, the second output should update the H1 value. However, I’ve got the following error which I don’t have any idea:

I expect that when I click the button, the value of my H1 will change. You can see my H1 as the follows:

Hello @KCL0827,

When posting code, you can use the preformatted text button </> and paste the code there. It will help us know your formatting and copy and paste it into our own troubleshooting mechanisms.

2 Likes

Hi @KCL0827,

I did not dig too much into your code, bot if you have to Output() in a callback, your function call_start_button needs to return two values.

Ask yourself: What is the value for the component load-output, what is the value for my-h1

Right now you are only returning sthe string ‘12345’

Please try to keep in mind @jinnyzor comment- it makes life easier for all people willing to help you :raised_hands:

1 Like

@jinnyzor @AIMPED Thank you for your help, I’ve solved my problem already. By modifying the callback of the button, the src of html.Img can be dynamically modifed:

</
@ app.callback(
Output(‘my-img’, ‘src’),
Input(‘start-button’, ‘n_clicks’),
def call_start_button(n_clicks):
.

encoded_image = base64.b64encode(open(path, ‘rb’).read())
p = ‘data:image/png;base64,{}’.format(encoded_image.decode())
return p
)

Here is my html.Img part:
</
result_card = html.Div([
html.Img(
id=‘my-img’)
])

This article also helps me a lot!

1 Like