Custom events can be added to guizero widgets to call functions when the user takes the following actions:
- when clicked -
- when double clicked -
- when the left mouse button is pressed -
- when the left mouse button is released -
- when the right mouse button is pressed -
- when the right mouse button is released -
- when a key is pressed -
- when a key is released -
- when the mouse enters a widget -
- when the mouse leaves a widget -
- when the mouse is dragged across a widget -
- when the widget is resized -
Events are set by assigning them to a function:
def do_this(): print("The widget was clicked") widget.when_clicked = do_this
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
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.
Note: only data relevant to the event will be returned. e.g.
key is only returned for
when_key_# events and
height are only returned for
def clicked(event_data): print("widget clicked = " + event_data.widget) print("mouse position = " + event_data.x + "." + event_data.y) widget.when_clicked = clicked
Highlight a text box widget by changing its background color (
bg) when the mouse is hovering over it.
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()