[Tutor] Testing for mouse clicks

Cameron Simpson cs at cskk.id.au
Sat Nov 7 19:16:27 EST 2020


On 08Nov2020 09:41, Phil <phillor9 at gmail.com> wrote:
>Spurred on by success with my recent project involving a grid of 
>lists, I now have another grid project in mind. If I want to test 
>whether the mouse is over, say one of six window locations, I would do 
>something like the following to test the mouse coordinates:
>
>if 136 <= x <= 156 and 370 <= y <= 390:
>    do_something
>elif 186 <= x <= 206 and 370 <= y <= 390:
>    do_something
>elif 236 <= x <= 256 and 370 <= y <= 390:
>     do_something
>elif etc
>
>Now, if I have a 15 * 15 grid of window locations that I want to test 
>then repeating the above 225 times becomes a bit untidy, and tedious.  
>How might I best attack this mouse_testing problem?

Can you inspect your grid widget to determine its coordinates? Or 
inspect the button for its coordinates? If so, measure, construct a 
mapping of bounds to actions to take. Example:


    widget_map = {}
    for my_widget in enumerate-your-widgets-here:
        x0, dx, y0, dy = my_widget.bounds()
        widget_map[x0, y0, x0+dx, y0+dy] = my_widget
    ...
    # find the widget and call its on_clicked method
    for (x0, x1, y0, y1), my_widget in widget_map.items():
        if x0 <= x < x1 and y0 < y <= y1:
            my_widget.on_clicked(...)
            break

Obviously you need the widgets to know their coordinates and have such a 
method, but that too can be arranged.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list