When you use buttons wired to the Live Python block, it is important to understand how the different button operating modes (toggle/momentary/string) affect the triggering of the Python script.
A toggle button will execute the Python code once when clicked. However, the state of a momentary button will change twice when it is clicked (from on and then back to off). This means the Python code inside the wired block will be executed twice. You can test out this behavior using an example that displays the value of the state variable, when a button wired to the Live Python block is clicked:
if inputs[0].changed_get():
state+=1
message.string_set( "This code has been executed " + str( state ) + " times" )
Clicking a momentary button will display a message showing the Python code has been executed twice.
If you want to use a momentary button, and ensure that the function is only called once, you need to add an extra if statement to the code:
if inputs[0].changed_get():
if inputs[0].value_get()==1:
state+=1
message.string_set( "This code has been executed " + str( state ) + " times" )
See also |