working on it ...

Filters

Explore Public Snippets

Sort by

Found 7 snippets matching: "kivy python"

    public by dave83  5055  15  8  6

    Touch down event binding in Kivy framework

    This code shows how to handle a touch event in the python Kivy framework. This snippet will generate a simple GUI, with 2 standard buttons and a custom button, where to bind the press event. Any Kivy property has a default on_ event. This event is called when the value of the property is changed. In this case the on_touch_down(self, touch) meth
    from kivy.app import App
     from kivy.uix.widget import Widget
     from kivy.uix.button import Button
     from kivy.uix.boxlayout import BoxLayout
     from kivy.properties import ListProperty
    
     class RootWidget(BoxLayout):
    
         def __init__(self, **kwargs):
             super(RootWidget, self).__init__(**kwargs)
             self.add_widget(Button(text='btn 1'))
             cb = CustomBtn()
             cb.bind(pressed=self.btn_pressed)
             self.add_widget(cb)
             self.add_widget(Button(text='btn 2'))
    
         def btn_pressed(self, instance, pos):
             print ('pos: printed from root widget: {pos}'.format(pos=pos))
    
     class CustomBtn(Widget):
    
         pressed = ListProperty([0, 0])
    
         def on_touch_down(self, touch):
             if self.collide_point(*touch.pos):
                 self.pressed = touch.pos
                 # we consumed the touch. return False here to propagate
                 # the touch further to the children.
                 return True
             return super(CustomBtn, self).on_touch_down(touch)
    
         def on_pressed(self, instance, pos):
             print ('pressed at {pos}'.format(pos=pos))
    
     class TestApp(App):
    
         def build(self):
             return RootWidget()
    
    
     if __name__ == '__main__':
         TestApp().run()

    external by openp2pdesign  3427  28  3  0

    Drawing serial data with Kivy (Python)

    Drawing serial data with Kivy (Python): kivy-serialdata.py
    # -*- coding: utf8 -*-
    
    from kivy.app import App
    from kivy.uix.floatlayout import FloatLayout
    from kivy.graphics import Line
    from kivy.uix.label import Label
    from kivy.core.window import Window
    from kivy.clock import Clock
    
    import serial
    
    # Basic class Float Layout
    class Test1(FloatLayout):
    
        def __init__(self, **kwargs):
            super(Test1, self).__init__(**kwargs)
    
            # Set the timer for redrawing the screen
            refresh_time = 0.5
            Clock.schedule_interval(self.timer, refresh_time)
    
            with self.canvas:
                 self.centered_circle = Line(circle = (self.center_x, self.center_y, 50), width = 2)
    
        def timer(self, dt):
            # Get data from serial port
            value = arduino.readline()
    
            # Draw the circle according to the data
            self.centered_circle.circle = (self.center_x, self.center_y,value)
    
            # More about drawing in Kivy here: http://kivy.org/docs/api-kivy.graphics.html
    
    
    # Main App class
    class SerialDataApp(App):
        def build(self):
            return Test1()
    
    # Main program
    if __name__ == '__main__':
        # Connect to serial port first
        try:
            arduino = serial.Serial('/dev/tty.usbmodem1421', 9600)
        except:
            print "Failed to connect"
            exit()
    
        # Launch the app
        SerialDataApp().run()
    
        # Close serial communication
        arduino.close()
    
    
    

    external by Ryan Pessa  45  0  1  0

    Kivy: python-for-android cython package setup.py

    Kivy: python-for-android cython package setup.py: setup.py
    #!/usr/bin/env python
    
    package_name = 'mypkg'
    package_version = '1.0'
    
    import fnmatch, os, sys
    
    # -----------------------------------------------------------------------------
    # Determine on which platform we are
    
    platform = sys.platform
    
    # Detect Python for android project (http://github.com/kivy/python-for-android)
    ndkplatform = os.environ.get('NDKPLATFORM')
    if ndkplatform is not None and os.environ.get('LIBLINK'):
        platform = 'android'
    kivy_ios_root = os.environ.get('KIVYIOSROOT', None)
    if kivy_ios_root is not None:
        platform = 'ios'
    if os.path.exists('/opt/vc/include/bcm_host.h'):
        platform = 'rpi'
    
    # -----------------------------------------------------------------------------
    # Cython check
    # on python-for-android and kivy-ios, cython usage is external
    have_cython = False
    if platform in ('ios', 'android'):
        print('\nCython check avoided.')
    else:
        try:
            # check for cython
            from Cython.Distutils import build_ext
            have_cython = True
        except ImportError:
            print('\nCython is missing, it is required for compiling!\n\n')
            raise
    
    if not have_cython:
        from distutils.core import setup
        from distutils.extension import Extension
        from distutils.command.build_ext import build_ext
    else:
        from setuptools import setup, Extension
    
    # copied from setuptools
    from distutils.util import convert_path
    def find_packages(where='.', exclude=()):
        """Return a list all Python packages found within directory 'where'
    
        'where' should be supplied as a "cross-platform" (i.e. URL-style) path; it
        will be converted to the appropriate local path syntax.  'exclude' is a
        sequence of package names to exclude; '*' can be used as a wildcard in the
        names, such that 'foo.*' will exclude all subpackages of 'foo' (but not
        'foo' itself).
        """
        out = []
        stack=[(convert_path(where), '')]
        while stack:
            where,prefix = stack.pop(0)
            for name in os.listdir(where):
                fn = os.path.join(where,name)
                if ('.' not in name and os.path.isdir(fn) and
                    os.path.isfile(os.path.join(fn,'__init__.py'))
                ):
                    out.append(prefix+name); stack.append((fn,prefix+name+'.'))
        for pat in list(exclude)+['ez_setup', 'distribute_setup']:
            from fnmatch import fnmatchcase
            out = [item for item in out if not fnmatchcase(item,pat)]
        return out
    
    # copied from kivy
    class CythonExtension(Extension):
        def __init__(self, *args, **kwargs):
            Extension.__init__(self, *args, **kwargs)
            self.cython_directives = {
                'c_string_encoding': 'utf-8',
                'profile': 'USE_PROFILE' in os.environ,
                'embedsignature': 'USE_EMBEDSIGNATURE' in os.environ}
            # XXX with pip, setuptools is imported before distutils, and change
            # our pyx to c, then, cythonize doesn't happen. So force again our
            # sources
            self.sources = args[1]
    
    packages = [pkg for pkg in find_packages('.') if pkg.startswith(package_name)]
    
    def make_cy_ext(filename):
        modname = filename.replace('.pyx', '').replace('/', '.')
        srcname = filename if have_cython else (filename[:-4] + '.c')
        return CythonExtension(modname, [srcname])
    
    def find_cy_ext(path):
        ext = []
        for root, dirnames, filenames in os.walk(path):
            for filename in fnmatch.filter(filenames, '*.pyx'):
                ext.append(make_cy_ext(os.path.join(root, filename)))
        return ext
    
    cython_ext = find_cy_ext(package_name)
    
    setup_opts = {
        'name': package_name,
        'version': package_version,
        'packages': packages,
        'cmdclass': {
            'build_ext': build_ext,
        },
        'ext_modules': cython_ext,
    }
    
    setup(**setup_opts)
    
    

    external by hardinkm  810  3  3  0

    KIVY Python Issue with keyboard listener and control of text in TextInput object

    KIVY Python Issue with keyboard listener and control of text in TextInput object: textinsert.py
    from kivy.app import App
    from kivy.uix.floatlayout import FloatLayout
    from kivy.uix.textinput import TextInput
    from kivy.uix.widget import Widget
    from kivy.properties import StringProperty,ObjectProperty
    from kivy.core.window import Window, Keyboard
    
    class textInsert(FloatLayout):
       def __init__(self, **kwargs):
          super(textInsert, self).__init__(**kwargs)
          
          text = StringProperty()
          
          self.custom_insteresting_keys=["s","y","q","w"] ## replace with dic later
          
          ########################################
          keyboard = Window.request_keyboard(self._keyboard_released, self)
          self._keyboard = keyboard
          keyboard.bind(on_key_down=self._keyboard_on_key_down)
          ########################################
          
          self.textin=TextInput(
             size_hint_x=None,
             size_hint_y=None,
             height=30,
             width=120,
             multiline=False
          )
          
          self.textin.bind(text=self.onText)
          self.add_widget(self.textin)
       #end def __init__
       
       def _keyboard_released(self):
          self.focus = False
       #end def _keyboard_released
       
       def _keyboard_on_key_down(self, window, keycode, text, modifiers):
          is_shortcut = (modifiers == ['ctrl'])
          
          print('keycode[1]', keycode[1])
            
          #if keycode[1] in list(self.custom_insteresting_keys) and is_shortcut: 
          if keycode[1] in list(self.custom_insteresting_keys):
             print("CUSTOM SHORT CUT HAS BEEN MET, TEXT SHOULD NOT BE ENTERED INTO TEXTINPUT")
             return True
          else:
             print('returned false')
             return False
          #end if
       #end def _keyboard_on_key_down
       
       def onText(self,instance,value):
          print("ON TEXT", value)
          '''
          #print self.textin._key_down(self)
          if len(value) == 3:
             self.textin.select_text(
                (self.textin.cursor_index()-len(value)),
                self.textin.cursor
             )
             self.textin.delete_selection()'''
       #end def onText
       
    class ROOT(App):
       def build(self):
          return textInsert()
    
    if __name__ == '__main__':
       ROOT().run()
    
    

    external by c34s3r  867  0  3  0

    quadratic equations with kivy and python...

    quadratic equations with kivy and python...: gistfile1.txt
    I wrote a quadratic equations GUI based script..
    I used kivy and python, the formula is also the Almighty formula.. 
    I used the floatlayout so that it maintains it's look even on landscape...
    
    here's the code below...
    
    for the. py file.....
    
    #-*-coding:utf8;-*-
    #qpy:2
    #qpy:kivy
    
    from math import sqrt 
    from kivy.app import App
    from kivy.uix.floatlayout import FloatLayout 
    from kivy.lang import Builder 
    
    
    class for_quadratic(FloatLayout):
        def solve_solution(self):
            self.result_box= self.ids.result_label 
            self.value_a=self.ids.value_one.text 
            self.value_b=self.ids.value_two.text 
            self.value_c=self.ids.value_three.text
            
            if (self.value_a==""):
                self.value_a="1"
            if (self.value_b==""):
                self.value_b="1"
            if (self.value_c==""):
                self.value_c="1"
                
            self.a=int(self.value_a)**2
            self.b=int(self.value_b)
            self.c=int(self.value_c)
        
            self.g=self.b**2
            self.h=4*self.a*self.c
            self.I=abs(self.g-self.h)
            self.k=self.I 
            self.formula= sqrt(self.k)
            self.root_one=(-self.b-self.formula)/2*self.a
            self.root_two=(-self.b+self.formula)/2*self.a
            self.result_box.text=("the roots are \n {} and {}"
            .format(round(self.root_one),round(self.root_two)))
    
    
    
    
    class QuadraticApp(App):
        def build(self):
             return for_quadratic()
    
    
    
    
    
    QuadraticApp().run()
    
    
    
    and for the kv file....
    
    
    
    ###kivy for quadratuc 
    
    <for_quadratic>:
        FloatLayout:
    	    Label:
    	        id: main_label
    	        text:"QUADRATIC EQUATIONS"
    	        size_hint: None,None
    	        width: root.width/2
    	        height: 45
    	        font_size: 30
    	        bold: True
    	        pos_hint: {"x":.25,"top":1}
    	        
    	    Label:
    	        id: label_one
    	        text: "VALUE A"
    	        size_hint: None,None
    	        width:root.width/2
    	        font_size: 20
    	        height: 40
    	        bold: True
    	        pos_hint:{"x":0,"y":.8}
    	
    	    TextInput:
    	        id: value_one
    	        hint_text: "type"
    	        size_hint: None,None
    	        width: root.width/2
    	        height: 55
    	        font_size: 20
    	        bold: True
    	        multiline: False 
    	        padding: root.height/self.height
    	        pos_hint: {"x":.5,"y":.8}
    	        
    	    Label:
    	        id: label_two 
    	        text: "VALUE B"
    	        size_hint: None,None
    	        width:root.width/2
    	        font_size: 20
    	        height: 40
    	        bold: True
    	        pos_hint: {"x":0,"y":.7}
    	        
    	    TextInput:
    	        id: value_two 
    	        hint_text: "type"
    	        size_hint: None,None
    	        width: root.width/2
    	        height: 55
    	        font_size: 20
    	        bold: True
    	        multiline: False
    	        padding: root.height/self.height
    	        pos_hint: {"x":.5,"y":.7}
    	        
    	    Label:
    	        id: label_three 
    	        text: "VALUE C"
    	        size_hint: None,None
    	        width:root.width/2
    	        font_size: 20
    	        height: 40
    	        bold: True
    	        pos_hint: {"x":0,"y":.6}
    	        
    	    TextInput:
    	        id: value_three 
    	        hint_text: "type"
    	        size_hint: None,None
    	        width: root.width/2
    	        height: 55
    	        font_size: 20
    	        bold: True
    	        multiline: False
    	        padding: root.height/self.height
    	        pos_hint: {"x":.5,"y":.6}
    	        
    	    Button:
    	        id: submit_button 
    	        text: "CALCULATE"
    	        size_hint: None,None
    	        width: root.width/2
    	        font_size: 25
    	        height: 57
    	        italic: True
    	        pos_hint: {"x":.5,"y":.5}
    	        on_press: root.solve_solution()
    	        
    	    Label:
    	        id: result_label
    	        text:"...."
    	        size_hint: None,None
    	        width: root.width
    	        height: 100
    	        font_size: 25
    	        bold: True
    	        pos_hint: {"x":0,"y":.3}
    	               
    	    Label:
    	        text: " by vitriol"
    	        size_hint: None,None
    	        width: root.width/2
    	        font_size: 20
    	        color: 0,1,0,1
    	        pos_hint: {"x":.25,"y":0}
    	               
    
    
    
    
    

    external by tejastank  14  0  1  0

    python kivy android apps package, snippetbucket

    python kivy android apps package, snippetbucket: snippetbucket.kivy-python-apk-install.sh
    #p4a is now available on on Pypi, so you can install it using pip:
    
    pip install python-for-android
    #You can also test the master branch from Github using:
    pip install git+https://github.com/kivy/python-for-android.git
    
    #dependances
    sudo dpkg --add-architecture i386
    sudo apt-get update
    sudo apt-get install -y build-essential ccache git zlib1g-dev python2.7 python2.7-dev libncurses5:i386 libstdc++6:i386 zlib1g:i386 openjdk-7-jdk unzip ant ccache
    
    
    # apk need for build
    sudo pip install buildozer
    #Once you have it installed, go to your project directory and type:
    buildozer init
    # edit the buildozer.spec, then
    buildozer android_new debug deploy run
    #https://github.com/kivy/buildozer       Generic Python packager for Android and iOS
    
    
    # more: https://python-for-android.readthedocs.io/en/latest/quickstart/
    
    
    
    
    
    
    
    
    

    external by Enteleform  8  0  1  0

    [Python] Kivy - Key Codes

    [Python] Kivy - Key Codes: key_codes.py
    # source:  kivy-master\kivy\core\window\__init__.py
    
    
    
    class Modifier:
    	SHIFT = "shift"
    	CTRL  = "ctrl"
    	ALT   = "alt"
    	SUPER = "meta"
    
    
    
    class Key:
    
    ########################################################################################################################################################################################################################################################################################################~{#
    #//////|   System   |///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////g2#
    ########################################################################################################################################################################################################################################################################################################~}#
    
    	###  Modifiers  ###
    	L_ALT   = 308
    	R_ALT   = 307
    	L_CTRL  = 305
    	R_CTRL  = 306
    	L_SHIFT = 304
    	R_SHIFT = 303
    	L_SUPER = 309
    	R_SUPER = 1073742055
    	MODIFIERS = [L_ALT,R_ALT,L_CTRL,R_CTRL,L_SHIFT,R_SHIFT,L_SUPER, R_SUPER]
    
    	###  Navigation > Primary  ###
    	UP       = 273
    	DOWN     = 274
    	LEFT     = 276
    	RIGHT    = 275
    	NAVIGATION_PRIMARY = [UP,DOWN,LEFT,RIGHT]
    
    	###  Navigation > Page  ###
    	PAGE_UP   = 280
    	PAGE_DOWN = 281
    	NAVIGATION_PAGE = [PAGE_UP,PAGE_DOWN]
    
    	###  Navigation > Line  ###
    	HOME = 278
    	END  = 279
    	NAVIGATION_LINE = [HOME,END]
    
    	NAVIGATION = NAVIGATION_PRIMARY + NAVIGATION_PAGE + NAVIGATION_LINE
    
    	###  State Toggles  ###
    	CAPS_LOCK   = 301
    	NUM_LOCK    = 300
    	SCREEN_LOCK = 145
    	STATE_TOGGLES = [CAPS_LOCK,NUM_LOCK,SCREEN_LOCK]
    
    	###  Commands  ###
    	BACKSPACE = 8
    	COMPOSE   = 311
    	DELETE    = 127
    	ENTER     = 13
    	ESCAPE    = 27
    	INSERT    = 277
    	PAUSE     = 19
    	PRINT     = 144
    	COMMANDS = [BACKSPACE,COMPOSE,DELETE,ENTER,ESCAPE,INSERT,PAUSE,PRINT]
    
    	###  WhiteSpace  ###
    	SPACE = 32
    	TAB   = 9
    	WHITESPACE = [SPACE,TAB]
    
    	###  Unknown  ###
    	PIPE = 310
    
    ########################################################################################################################################################################################################################################################################################################~{#
    #//////|   Letters   |//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////g2#
    ########################################################################################################################################################################################################################################################################################################~}#
    
    	A = 97
    	B = 98
    	C = 99
    	D = 100
    	E = 101
    	F = 102
    	G = 103
    	H = 104
    	I = 105
    	J = 106
    	K = 107
    	L = 108
    	M = 109
    	N = 110
    	O = 111
    	P = 112
    	Q = 113
    	R = 114
    	S = 115
    	T = 116
    	U = 117
    	V = 118
    	W = 119
    	X = 120
    	Y = 121
    	Z = 122
    	LETTERS = [A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z]
    
    	###  Accented_Letters  ###
    	A_GRAVE = 224  #  À
    	E_ACUTE = 233  #  É
    	E_GRAVE = 232  #  È
    	U_GRAVE = 249  #  Ù
    	ACCENTED_LETTERS = [A_GRAVE,E_ACUTE,E_GRAVE,U_GRAVE]
    
    ########################################################################################################################################################################################################################################################################################################~{#
    #//////|   Numbers   |//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////g2#
    ########################################################################################################################################################################################################################################################################################################~}#
    
    	NUM_0 = 48
    	NUM_1 = 49
    	NUM_2 = 50
    	NUM_3 = 51
    	NUM_4 = 52
    	NUM_5 = 53
    	NUM_6 = 54
    	NUM_7 = 55
    	NUM_8 = 56
    	NUM_9 = 57
    	NUMBERS = [NUM_0,NUM_1,NUM_2,NUM_3,NUM_4,NUM_5,NUM_6,NUM_7,NUM_8,NUM_9]
    
    ########################################################################################################################################################################################################################################################################################################~{#
    #//////|   Numpad   |///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////g2#
    ########################################################################################################################################################################################################################################################################################################~}#
    
    	NUMPAD_0 = 256
    	NUMPAD_1 = 257
    	NUMPAD_2 = 258
    	NUMPAD_3 = 259
    	NUMPAD_4 = 260
    	NUMPAD_5 = 261
    	NUMPAD_6 = 262
    	NUMPAD_7 = 263
    	NUMPAD_8 = 264
    	NUMPAD_9 = 265
    	NUMPAD_KEYS = [NUMPAD_0,NUMPAD_1,NUMPAD_2,NUMPAD_3,NUMPAD_4,NUMPAD_5,NUMPAD_6,NUMPAD_7,NUMPAD_8,NUMPAD_9]
    
    	NUMPAD_ADD      = 270
    	NUMPAD_DECIMAL  = 266
    	NUMPAD_DIVIDE   = 267
    	NUMPAD_ENTER    = 271
    	NUMPAD_MULTIPLY = 268
    	NUMPAD_SUBTRACT = 269
    	NUMPAD_SYMBOLS = [NUMPAD_ADD,NUMPAD_DECIMAL,NUMPAD_DIVIDE,NUMPAD_ENTER,NUMPAD_MULTIPLY,NUMPAD_SUBTRACT]
    
    ########################################################################################################################################################################################################################################################################################################~{#
    #//////|   F1 - F15   |/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////g2#
    ########################################################################################################################################################################################################################################################################################################~}#
    
    	F1  = 282
    	F2  = 283
    	F3  = 284
    	F4  = 285
    	F5  = 286
    	F6  = 287
    	F7  = 288
    	F8  = 289
    	F9  = 290
    	F10 = 291
    	F11 = 292
    	F12 = 293
    	F13 = 294
    	F14 = 295
    	F15 = 296
    	F_KEYS = [F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12,F13,F14,F15]
    
    ########################################################################################################################################################################################################################################################################################################~{#
    #//////|   Symbols   |//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////g2#
    ########################################################################################################################################################################################################################################################################################################~}#
    
    	###  Brackets  ###
    	L_ANGLE   = 60   #  <
    	R_ANGLE   = 62   #  >
    	L_BRACE   = 123  #  {
    	R_BRACE   = 125  #  }
    	L_BRACKET = 91   #  [
    	R_BRACKET = 93   #  ]
    	L_PAREN   = 40   #  (
    	R_PAREN   = 41   #  )
    	BRACKETS = [L_ANGLE,R_ANGLE,L_BRACE,R_BRACE,L_BRACKET,R_BRACKET,L_PAREN,R_PAREN]
    
    	###  Symbols  ###
    	ACUTE_ACCENT = 180   #  ´
    	AMPERSAND    = 38    #  &
    	ASTERISK     = 42    #  *
    	AT           = 64    #  @
    	BACKSLASH    = 92    #  \
    	BACKTICK     = 96    #  `
    	BAR          = 124   #  |
    	BROKEN_BAR   = 166   #  ¦
    	CARET        = 94    #  ^
    	COLON        = 58    #  :
    	COMMA        = 44    #  ,
    	DASH         = 45    #  -
    	DIAERESIS    = 168   #  ¨
    	DOLLAR       = 36    #  $
    	ELLIPSIS     = 8230  #  …
    	EQUALS       = 61    #  =
    	EXCLAMATION  = 33    #  !
    	FORWARDSLASH = 47    #  /
    	NOT          = 172   #  ¬
    	PERCENT      = 37    #  %
    	PERIOD       = 46    #  .
    	PLUS         = 43    #  +
    	POUND        = 35    #  #
    	QUESTION     = 47    #  ?
    	QUOTE        = 34    #  "
    	SEMICOLON    = 59    #  ;
    	SINGLEQUOTE  = 39    #  '
    	TILDE        = 126   #  ~
    	UNDERSCORE   = 95    #  _
    	SYMBOLS = BRACKETS + [ACUTE_ACCENT,AMPERSAND,ASTERISK,AT,BACKSLASH,BACKTICK,BAR,BROKEN_BAR,CARET,COLON,COMMA,DASH,DIAERESIS,DOLLAR,ELLIPSIS,EQUALS,EXCLAMATION,FORWARDSLASH,NOT,PERCENT,PERIOD,PLUS,POUND,QUESTION,QUOTE,SEMICOLON,SINGLEQUOTE,TILDE,UNDERSCORE]
    
    
    

    List Complete ( 7 snippets total )

    • Public Snippets
    • Channels Snippets