Button

Buttons are used to initialize an action. Button labels express what action will occur when the user interacts with it.

Overview

Carbon Design Button

Carbon Design Buttons Overview

Buttons are clickable elements that are used to trigger actions. They communicate calls to action to the user and allow users to interact with pages in a variety of ways. Button labels express what action will occur when the user interacts with it.

By the latest CarbonKivy provides 3 types of button styles by default, however it holds the ability for developers to create thier own style customized buttons.

Live demo

Click the below buttons to test user interactivity.

Note

This live demo contains only a preview of functionality and styles available for this component. Actual widgets may not show the exact same behavior but similar to expected.

CButtonPrimary:
    text: "Button"
    role: "Large Productive"
    # icon: "add"
CButtonSecondary:
    text: "Button"
    role: "Large Productive"
    # icon: "add"
CButtonGhost:
    text: "Button"
    role: "Large Productive"
    # icon: "add"
CButtonTertiary:
    text: "Button"
    role: "Large Productive"
    # icon: "add"
CButtonDanger:
    text: "Button"
    variant: "Primary" # Primary (default), Tertiary, Ghost
    role: "Large Productive"
    # icon: "add"

Size

There are six available size tokens for a button:

  • Small

  • Medium

  • Large Productive

  • Large Expressive

  • Extra Large

  • 2XL

The Large Expressive button is used in editorial and digital marketing experiences.

Use the role property to define the token for the button size.

CButtonPrimary:
    text: "Button"
    role: "Extra Large" # Define the specific size token here (capitalized first letter of every word.)
Carbon Design Button Sizes

Sizes of buttons in relation to its usage.

Custom Button

To create a custom button using the CButton you have certain properties and methods which needs to be customized.

The CButton class inherits certain behaviors to enable smooth user interactivity during different interactive states. It also holds some pre-defined properties like padding, spacing, font_size, text_color, bg_color, inset_color, cstate, etc.

Let’s start with an example code:

CButton:
    text: "Button"
    text_color: "blue_60"
    icon: "add"
    cstate: "normal" # active, disabled, normal
    pos_hint: {"center_x" : 0.5, "center_y" : 0.5}

Appearance of Button in different interactive states is shown below:

../../_images/cbuttonnormal.png

normal

../../_images/cbuttonhover.png

hover

../../_images/cbuttonfocus.png

focus

../../_images/cbuttondisabled.png

disabled

To create an active state button you have to define the active_color, the color that appears when the button state is down.

../../_images/cbuttonactive.png

active

CButton:
    text: "Button"
    icon: "add"
    active_color: app.button_primary_active
    cstate: "active" # active, disabled, normal
    pos_hint: {"center_x" : 0.5, "center_y" : 0.5}

Let’s create a button similar to CButtonPrimary by defining the color properties by ourselves.

../../_images/cbuttoncustom.png
<MyPrimaryButton@CButton>:
    bg_color: app.button_primary
    hover_color: app.button_primary_hover
    active_color: app.button_primary_active

MyPrimaryButton:
    text: "My Primary Button"
    # cstate: "active" # active, disabled, normal (`default`)
    role: "2XL"
    icon: "add"
    pos_hint: {"center_x" : 0.5, "center_y" : 0.5}

Icon Button

To add icons to the button you have to define the icon, the icon that would appear at the specific slot aside the label or centralized in Icon Only Buttons.

../../_images/normal.png
CButtonPrimary:
    text: "Button"
    icon: "add"
    role: "Large Productive"
    icon: "add"

../../_images/iconnormal.png
CButtonPrimary:
    icon: "add"
    role: "Large Productive"
    spacing: 0

Note

For an Icon Only Button you have to only define the icon property and set the button spacing to 0 for centralized icon slot.

Example

Run the below python script for a full-fledged running Example.

from kivy.core.window import Window
from kivy.clock import Clock


def set_softinput(*args) -> None:
    Window.keyboard_anim_args = {"d": 0.2, "t": "in_out_expo"}
    Window.softinput_mode = "below_target"


Window.on_restore(Clock.schedule_once(set_softinput, 0.1))

appkv = """
CScreen:

    CButtonPrimary:
        text: "Primary Button"
        role: "Large Productive"
        icon: "add"
        pos_hint: {'center_y': 0.9, 'center_x': 0.35}

    CButtonPrimary:
        icon: "add"
        role: "2XL"
        spacing: 0
        pos_hint: {'center_y': 0.9, 'center_x': 0.8}

    CButtonSecondary:
        text: "Secondary Button"
        role: "Large Productive"
        icon: "add"
        pos_hint: {'center_y': 0.7, 'center_x': 0.35}

    CButtonSecondary:
        icon: "add"
        role: "2XL"
        spacing: 0
        pos_hint: {'center_y': 0.7, 'center_x': 0.8}

    CButtonTertiary:
        text: "Tertiary Button"
        role: "Large Productive"
        icon: "add"
        pos_hint: {'center_y': 0.5, 'center_x': 0.35}

    CButtonTertiary:
        icon: "add"
        role: "2XL"
        spacing: 0
        pos_hint: {'center_y': 0.5, 'center_x': 0.8}

    CButtonGhost:
        text: "Ghost Button"
        role: "Large Productive"
        icon: "add"
        pos_hint: {'center_y': 0.3,  'center_x': 0.35}

    CButtonGhost:
        icon: "add"
        role: "2XL"
        spacing: 0
        pos_hint: {'center_y': 0.3, 'center_x': 0.8}

    CButtonDanger:
        text: "Danger Button"
        role: "Large Productive"
        icon: "add"
        pos_hint: {'center_y': 0.1,  'center_x': 0.35}

    CButtonDanger:
        icon: "add"
        role: "2XL"
        spacing: 0
        pos_hint: {'center_y': 0.1, 'center_x': 0.8}
"""

from kivy.lang import Builder
from carbonkivy.app import CarbonApp


class myapp(CarbonApp):
    def __init__(self, *args, **kwargs):
        super(myapp, self).__init__(*args, **kwargs)

    def build(self, *args) -> None:
        screen = Builder.load_string(appkv)
        return screen


if __name__ == "__main__":
    myapp().run()

API

class carbonkivy.uix.button.button.CButton(*args: Any, **kwargs: Any)[source]

Bases: AdaptiveBehavior, BackgroundColorBehaviorRectangular, StateFocusBehavior, ButtonBehavior, DeclarativeBehavior, HoverBehavior, RelativeLayout

actual_width

NumericProperty(defaultvalue=0, **kw) Property that represents a numeric value.

It only accepts the int or float numeric data type or a string that can be converted to a number as shown below. For other numeric types use ObjectProperty or use errorhandler to convert it to an int/float.

It does not support numpy numbers so they must be manually converted to int/float. E.g. widget.num = np.arange(4)[0] will raise an exception. Numpy arrays are not supported at all, even by ObjectProperty because their comparison does not return a bool. But if you must use a Kivy property, use a ObjectProperty with comparator set to np.array_equal. E.g.:

>>> class A(EventDispatcher):
...     data = ObjectProperty(comparator=np.array_equal)
>>> a = A()
>>> a.bind(data=print)
>>> a.data = np.arange(2)
<__main__.A object at 0x000001C839B50208> [0 1]
>>> a.data = np.arange(3)
<__main__.A object at 0x000001C839B50208> [0 1 2]
Parameters:
defaultvalue: int or float, defaults to 0

Specifies the default value of the property.

>>> wid = Widget()
>>> wid.x = 42
>>> print(wid.x)
42
>>> wid.x = "plop"
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "properties.pyx", line 93, in kivy.properties.Property.__set__
   File "properties.pyx", line 111, in kivy.properties.Property.set
   File "properties.pyx", line 159, in kivy.properties.NumericProperty.check
 ValueError: NumericProperty accept only int/float

Changed in version 1.4.1: NumericProperty can now accept custom text and tuple value to indicate a type, like “in”, “pt”, “px”, “cm”, “mm”, in the format: ‘10pt’ or (10, ‘pt’).

cbutton_layout

ObjectProperty(defaultvalue=None, rebind=False, **kw) Property that represents a Python object.

Parameters:
defaultvalue: object type

Specifies the default value of the property.

rebind: bool, defaults to False

Whether kv rules using this object as an intermediate attribute in a kv rule, will update the bound property when this object changes.

That is the standard behavior is that if there’s a kv rule text: self.a.b.c.d, where a, b, and c are properties with rebind False and d is a StringProperty. Then when the rule is applied, text becomes bound only to d. If a, b, or c change, text still remains bound to d. Furthermore, if any of them were None when the rule was initially evaluated, e.g. b was None; then text is bound to b and will not become bound to d even when b is changed to not be None.

By setting rebind to True, however, the rule will be re-evaluated and all the properties rebound when that intermediate property changes. E.g. in the example above, whenever b changes or becomes not None if it was None before, text is evaluated again and becomes rebound to d. The overall result is that text is now bound to all the properties among a, b, or c that have rebind set to True.

**kwargs: a list of keyword arguments
baseclass

If kwargs includes a baseclass argument, this value will be used for validation: isinstance(value, kwargs[‘baseclass’]).

Warning

To mark the property as changed, you must reassign a new python object.

Changed in version 1.9.0: rebind has been introduced.

Changed in version 1.7.0: baseclass parameter added.

font_size

NumericProperty(defaultvalue=0, **kw) Property that represents a numeric value.

It only accepts the int or float numeric data type or a string that can be converted to a number as shown below. For other numeric types use ObjectProperty or use errorhandler to convert it to an int/float.

It does not support numpy numbers so they must be manually converted to int/float. E.g. widget.num = np.arange(4)[0] will raise an exception. Numpy arrays are not supported at all, even by ObjectProperty because their comparison does not return a bool. But if you must use a Kivy property, use a ObjectProperty with comparator set to np.array_equal. E.g.:

>>> class A(EventDispatcher):
...     data = ObjectProperty(comparator=np.array_equal)
>>> a = A()
>>> a.bind(data=print)
>>> a.data = np.arange(2)
<__main__.A object at 0x000001C839B50208> [0 1]
>>> a.data = np.arange(3)
<__main__.A object at 0x000001C839B50208> [0 1 2]
Parameters:
defaultvalue: int or float, defaults to 0

Specifies the default value of the property.

>>> wid = Widget()
>>> wid.x = 42
>>> print(wid.x)
42
>>> wid.x = "plop"
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "properties.pyx", line 93, in kivy.properties.Property.__set__
   File "properties.pyx", line 111, in kivy.properties.Property.set
   File "properties.pyx", line 159, in kivy.properties.NumericProperty.check
 ValueError: NumericProperty accept only int/float

Changed in version 1.4.1: NumericProperty can now accept custom text and tuple value to indicate a type, like “in”, “pt”, “px”, “cm”, “mm”, in the format: ‘10pt’ or (10, ‘pt’).

icon

StringProperty(defaultvalue=u’’, **kw) Property that represents a string value.

Parameters:
defaultvalue: string, defaults to ‘’

Specifies the default value of the property.

icon_color

ColorProperty(defaultvalue=0, **kw) Property that represents a color. The assignment can take either:

  • a collection of 3 or 4 float values between 0-1 (kivy default)

  • a string in the format #rrggbb or #rrggbbaa

  • a string representing color name (eg. ‘red’, ‘yellow’, ‘green’)

Object colormap is used to retrieve color from color name and names definitions can be found at this link. Color can be assigned in different formats, but it will be returned as ObservableList of 4 float elements with values between 0-1.

Parameters:
defaultvalue: list or string, defaults to [1.0, 1.0, 1.0, 1.0]

Specifies the default value of the property.

Added in version 1.10.0.

Changed in version 2.0.0: Color value will be dispatched when set through indexing or slicing, but when setting with slice you must ensure that slice has 4 components with float values between 0-1. Assingning color name as value is now supported. Value None is allowed as default value for property.

on_focus(*args) None[source]
on_font_size(*args) None[source]
on_hover(*args) None[source]
on_icon(*args) None[source]
on_icon_color(*args) None[source]
on_role(*args) None[source]
on_state(*args) None[source]
on_text(*args) None[source]
on_text_color(instance: object, color: list | str) None[source]
padding

VariableListProperty(defaultvalue=None, length=4, **kw) A ListProperty that allows you to work with a variable amount of

list items and to expand them to the desired list size.

For example, GridLayout’s padding used to just accept one numeric value which was applied equally to the left, top, right and bottom of the GridLayout. Now padding can be given one, two or four values, which are expanded into a length four list [left, top, right, bottom] and stored in the property.

Parameters:
default: a default list of values

Specifies the default values for the list.

length: int, one of 2 or 4.

Specifies the length of the final list. The default list will be expanded to match a list of this length.

**kwargs: a list of keyword arguments

Not currently used.

Keeping in mind that the default list is expanded to a list of length 4, here are some examples of how VariableListProperty is handled.

  • VariableListProperty([1]) represents [1, 1, 1, 1].

  • VariableListProperty([1, 2]) represents [1, 2, 1, 2].

  • VariableListProperty([‘1px’, (2, ‘px’), 3, 4.0]) represents [1, 2, 3, 4.0].

  • VariableListProperty(5) represents [5, 5, 5, 5].

  • VariableListProperty(3, length=2) represents [3, 3].

Added in version 1.7.0.

role

OptionProperty(*largs, **kw) Property that represents a string from a predefined list of valid

options.

If the string set in the property is not in the list of valid options (passed at property creation time), a ValueError exception will be raised.

Parameters:
default: any valid type in the list of options

Specifies the default value of the property.

**kwargs: a list of keyword arguments

Should include an options parameter specifying a list (not tuple) of valid options.

For example:

class MyWidget(Widget):
    state = OptionProperty("None", options=["On", "Off", "None"])
text

StringProperty(defaultvalue=u’’, **kw) Property that represents a string value.

Parameters:
defaultvalue: string, defaults to ‘’

Specifies the default value of the property.

text_color

ColorProperty(defaultvalue=0, **kw) Property that represents a color. The assignment can take either:

  • a collection of 3 or 4 float values between 0-1 (kivy default)

  • a string in the format #rrggbb or #rrggbbaa

  • a string representing color name (eg. ‘red’, ‘yellow’, ‘green’)

Object colormap is used to retrieve color from color name and names definitions can be found at this link. Color can be assigned in different formats, but it will be returned as ObservableList of 4 float elements with values between 0-1.

Parameters:
defaultvalue: list or string, defaults to [1.0, 1.0, 1.0, 1.0]

Specifies the default value of the property.

Added in version 1.10.0.

Changed in version 2.0.0: Color value will be dispatched when set through indexing or slicing, but when setting with slice you must ensure that slice has 4 components with float values between 0-1. Assingning color name as value is now supported. Value None is allowed as default value for property.

text_color_disabled

ColorProperty(defaultvalue=0, **kw) Property that represents a color. The assignment can take either:

  • a collection of 3 or 4 float values between 0-1 (kivy default)

  • a string in the format #rrggbb or #rrggbbaa

  • a string representing color name (eg. ‘red’, ‘yellow’, ‘green’)

Object colormap is used to retrieve color from color name and names definitions can be found at this link. Color can be assigned in different formats, but it will be returned as ObservableList of 4 float elements with values between 0-1.

Parameters:
defaultvalue: list or string, defaults to [1.0, 1.0, 1.0, 1.0]

Specifies the default value of the property.

Added in version 1.10.0.

Changed in version 2.0.0: Color value will be dispatched when set through indexing or slicing, but when setting with slice you must ensure that slice has 4 components with float values between 0-1. Assingning color name as value is now supported. Value None is allowed as default value for property.

text_color_focus

ColorProperty(defaultvalue=0, **kw) Property that represents a color. The assignment can take either:

  • a collection of 3 or 4 float values between 0-1 (kivy default)

  • a string in the format #rrggbb or #rrggbbaa

  • a string representing color name (eg. ‘red’, ‘yellow’, ‘green’)

Object colormap is used to retrieve color from color name and names definitions can be found at this link. Color can be assigned in different formats, but it will be returned as ObservableList of 4 float elements with values between 0-1.

Parameters:
defaultvalue: list or string, defaults to [1.0, 1.0, 1.0, 1.0]

Specifies the default value of the property.

Added in version 1.10.0.

Changed in version 2.0.0: Color value will be dispatched when set through indexing or slicing, but when setting with slice you must ensure that slice has 4 components with float values between 0-1. Assingning color name as value is now supported. Value None is allowed as default value for property.

text_color_hover

ColorProperty(defaultvalue=0, **kw) Property that represents a color. The assignment can take either:

  • a collection of 3 or 4 float values between 0-1 (kivy default)

  • a string in the format #rrggbb or #rrggbbaa

  • a string representing color name (eg. ‘red’, ‘yellow’, ‘green’)

Object colormap is used to retrieve color from color name and names definitions can be found at this link. Color can be assigned in different formats, but it will be returned as ObservableList of 4 float elements with values between 0-1.

Parameters:
defaultvalue: list or string, defaults to [1.0, 1.0, 1.0, 1.0]

Specifies the default value of the property.

Added in version 1.10.0.

Changed in version 2.0.0: Color value will be dispatched when set through indexing or slicing, but when setting with slice you must ensure that slice has 4 components with float values between 0-1. Assingning color name as value is now supported. Value None is allowed as default value for property.

update_specs(*args) None[source]
class carbonkivy.uix.button.button.CButtonDanger(*args: Any, **kwargs: Any)[source]

Bases: CButton

cstate

OptionProperty(*largs, **kw) Property that represents a string from a predefined list of valid

options.

If the string set in the property is not in the list of valid options (passed at property creation time), a ValueError exception will be raised.

Parameters:
default: any valid type in the list of options

Specifies the default value of the property.

**kwargs: a list of keyword arguments

Should include an options parameter specifying a list (not tuple) of valid options.

For example:

class MyWidget(Widget):
    state = OptionProperty("None", options=["On", "Off", "None"])
on_focus(*args) None[source]
variant

OptionProperty(*largs, **kw) Property that represents a string from a predefined list of valid

options.

If the string set in the property is not in the list of valid options (passed at property creation time), a ValueError exception will be raised.

Parameters:
default: any valid type in the list of options

Specifies the default value of the property.

**kwargs: a list of keyword arguments

Should include an options parameter specifying a list (not tuple) of valid options.

For example:

class MyWidget(Widget):
    state = OptionProperty("None", options=["On", "Off", "None"])
class carbonkivy.uix.button.button.CButtonGhost(*args: Any, **kwargs: Any)[source]

Bases: CButton

class carbonkivy.uix.button.button.CButtonPrimary(*args: Any, **kwargs: Any)[source]

Bases: CButton

class carbonkivy.uix.button.button.CButtonSecondary(*args: Any, **kwargs: Any)[source]

Bases: CButton

class carbonkivy.uix.button.button.CButtonTertiary(*args: Any, **kwargs: Any)[source]

Bases: CButton

on_focus(*args) None[source]