The Button Widget
-
Prerequisite
Description
You can add buttons to the stage, and specify what happens when the user clicks on them.
Adding a Button
Parameters
- Text on Button: The text to be displayed on the button.
- Center Position: The x and y positions of the center point of the button.
- Size: The width and height of the button. Note that the button is limited to the stage window, which has a width of 480 and a height of 360.
- Tooltip: The text to be displayed when the mouse is hovering over the button. This is often useful when you want to show some information about what the button does before the user clicks on it.
- Button Name: A unique name to refer to this button later.
Handle the Button Click Event
This block allows you to run some code whenever the button is clicked.
Parameters
- Widget Name: You need to select the name of the button for which you are waiting for the click event. That button has to be added to the stage already for its name to show up in this list.
Demo
This screencast shows how to add a button, and then change the text on it whenever the user clicks on it.
To make the text toggle between “Start” and “Stop”, a variable “Command” is used to keep track of the current command. Each time the button is clicked, we change “Command” based on its current value.
Try it yourself:
https://play.creaticode.com/projects/11550cc1f7d8230ae73123af
When Any Button Clicked
Sometimes there are many buttons on the stage, and we don’t want to write a click-handler for each of them. Instead, we can use the following hat block to capture all button click events:
To use this block, a variable has to be defined first, such as “my variable”.With this block, when any button on the stage is clicked, this block will be triggered, and the name of the button will be stored in the variable we have specified.
Example
For example, in this program, we have 2 buttons named “button1” and “button2”. When I click on either one of them, the “when any button named ( ) clicked” block will be triggered, and the exact name of that button is stored in the “button name” variable.
Here is what we get when we run this program: -