1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
## Events
Custom events can be added to guizero widgets to call functions when the user takes the following actions:
- when clicked - `when_clicked`
- when double clicked - `when_double_clicked`
- when the left mouse button is pressed - `when_left_button_pressed`
- when the left mouse button is released - `when_left_button_released`
- when the right mouse button is pressed - `when_right_button_pressed`
- when the right mouse button is released - `when_right_button_released`
- when a key is pressed - `when_key_pressed`
- when a key is released - `when_key_released`
- when the mouse enters a widget - `when_mouse_enters`
- when the mouse leaves a widget - `when_mouse_leaves`
- when the mouse is dragged across a widget - `when_mouse_dragged`
- when the widget is resized - `when_resized`
Events are set by assigning them to a function:
```python
def do_this():
print("The widget was clicked")
widget.when_clicked = do_this
```
### Event Data
The function which is called can also accept a parameter and will be passed data about the event which occurred.
The event data returned has:
- `widget` - the guizero widget which raised the event
- `tk_event` - the [tkinter event object](https://dafarry.github.io/tkinterbook/tkinter-events-and-bindings.htm)
- `key` - the key which raised the event
- `x` - the mouse's x position relative to the widget when the event occurred
- `y` - the mouse's y position relative to the widget when the event occurred
- `display_x` - the mouse's x position on the display when the event occurred
- `display_y` - the mouse's y position on the display when the event occurred
- `width` - the width of the widget.
- `height` - the height of the widget.
- `keycode` - the [keycode](https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/key-names.html) of the key which raised the event.
**Note:** only data relevant to the event will be returned. e.g. `key` is only returned for `when_key_#` events and `width` and `height` are only returned for `when_resized` events.
```python
def clicked(event_data):
print("widget clicked = ", event_data.widget)
print("mouse position = ", event_data.x, ".", event_data.y)
widget.when_clicked = clicked
```
### Example
Highlight a text box widget by changing its background color (`bg`) when the mouse is hovering over it.
```python
from guizero import App, TextBox
def highlight():
text_box.bg = "lightblue"
def lowlight():
text_box.bg = "white"
app = App()
text_box = TextBox(app)
# When the mouse enters the TextBox
text_box.when_mouse_enters = highlight
# When the mouse leaves the TextBox
text_box.when_mouse_leaves = lowlight
app.display()
```
|