[SOLVED] How to press and drag to select a group of ToggleButtons with Kivy?


This Content is from Stack Overflow. Question asked by Ham789

I am hoping to implement some drag-select functionality to a grid of buttons in a GUI. I want to achieve something similar to a drag selection box on desktop operating systems. Can I accomplish this with Kivy?

All I can seem to find is drag and drop functionality or multi-select of buttons by holding the shift key but not the exact functionality I am looking for.

Ideally the app could remember which toggle buttons were toggled by which specific drags by the user. Please see my attached image. Thank you in advance, any help is appreciated.

enter image description here

Here is my code so far:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.togglebutton import ToggleButton 

class ButtonGridLayout(GridLayout):
    def __init__(self, **kwargs):
        for i in range(10 * 10):
            b = ToggleButton(text = str(i))

class mainApp(App):



    rows: 10
    cols: 10


That is a fairly complex coding exercise. But here are some hints to get you started.

  1. If you want to drag and drop Buttons in a Layout, you probably don’t want to use GridLayout, as that Layout does its own positioning of its children. Something a bit more flexible, like a FloatLayout will likely work better.
  2. You can use on_touch_down(), on_touch_move(), and on_touch_up() methods in your Layout to draw and save a selection Rectangle.
  3. You can use the pos and size of the Buttons to compare to the Rectangle and determine which Buttons have been selected, and save them in a list.
  4. You can then use the same methods (as in hint #2) to drag and drop the list of selected Buttons
  5. You will need to distinguish selection touches from drag and drop touches from the basic Button touches, in the on_touch methods. The touch object has a button attribute that tells which mouse button was pressed and can be used for some of this. You may need to bind keyboard events so that you can require, for example, holding the ctrl button down while making the selection. And then, perhaps, require using the right mouse button to do the actual drag and drop.
  6. The drag and drop of a list of selected Buttons can be accomplished in an on_touch_move() method by just adding the touch.dpos to the pos of each selected Button.
  7. Also note that you cannot use pos_hint in the Buttons as that will over-ride any pos change that you make as a result of the dragging.

This Question was asked in StackOverflow by Ham789 and Answered by John Anderson It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?