Skip to content

Instantly share code, notes, and snippets.

@tito
Last active June 7, 2022 22:32
Show Gist options
  • Save tito/1339f6700197358133d9 to your computer and use it in GitHub Desktop.
Save tito/1339f6700197358133d9 to your computer and use it in GitHub Desktop.
Kivy focusable widgets
# coding=utf-8
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.checkbox import CheckBox
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.lang import Builder
Builder.load_string("""
#:import rgb kivy.utils.get_color_from_hex
<FocusableCheckBox,FocusableButton,FocusableTextInput>:
canvas.before:
Color:
rgba: rgb("#3bb1dd")[:3] + [.5 if self.focus else 0]
Line:
width: sp(1)
rectangle: self.x, self.y, self.width, self.height
Color:
rgb: 0, 0, 0
<FocusableTextInput>:
write_tab: False
canvas.before:
Color:
rgba: self.disabled_foreground_color if self.disabled else (self.hint_text_color if not self.text and not self.focus else self.foreground_color)
""")
class FocusableTextInput(TextInput):
pass
class FocusableCheckBox(FocusBehavior, CheckBox):
def keyboard_on_key_down(self, window, keycode, text, modifiers):
key = keycode[-1]
if key in ("spacebar", "enter"):
self.active = not self.active
return super(FocusableCheckBox, self).keyboard_on_key_down(window, keycode, text, modifiers)
class FocusableButton(FocusBehavior, Button):
def keyboard_on_key_down(self, window, keycode, text, modifiers):
key = keycode[-1]
if key in ("spacebar", "enter"):
self.trigger_action()
return super(FocusableButton, self).keyboard_on_key_down(window, keycode, text, modifiers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment