Advertisement
furas

Python - Kivy - touch and collide_point

May 23rd, 2018
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. # Kivy sends `on_touch_down` events to all widgets
  2. # so every widget has to check if touch was made in widget's area.
  3. # Or you have to use `on_press` or `on_release` instead `on_touch_down`
  4. # https://stackoverflow.com/a/45942518/1832058
  5.  
  6.  
  7. #--- calc.kv ---
  8.  
  9. #:kivy 1.10.0
  10.  
  11. <Calculate>:
  12.     display: entry
  13.     rows: 5
  14.     padding: 10
  15.     spacing: 10
  16.  
  17.     BoxLayout:
  18.         TextInput:
  19.             id: entry
  20.             multiline: False
  21.             font_size: 32
  22.             text: "Kivy Touch: "
  23.  
  24.     BoxLayout:
  25.         spacing: 10
  26.  
  27.         Button:
  28.             font_size: 20
  29.             text: '7'
  30.             on_press: entry.text += self.text
  31.  
  32.         Button:
  33.             font_size: 20
  34.             text: '8'
  35.             on_release: entry.text += self.text
  36.  
  37.         Button:
  38.             font_size: 20
  39.             text: '9'
  40.             on_touch_down: root.touch_button(*args)
  41.  
  42.         Button:
  43.             font_size: 20
  44.             text: '+'
  45.             on_touch_down: root.touch_button(*args)
  46.  
  47. #--- calc.py ---
  48.  
  49. #!/usr/bin/env python3
  50.  
  51. from kivy.app import App
  52. from kivy.uix.gridlayout import GridLayout
  53.  
  54.  
  55. # kivy sends `on_touch_down` events to all widgets
  56. # so every widget has to check if touch was made in widget's area.
  57. # Or you have to use `on_press` or `on_release` instead `on_touch_down`
  58. # https://stackoverflow.com/a/45942518/1832058
  59.  
  60.  
  61. class Calculate(GridLayout):
  62.    
  63.     def touch_button(self, instance, touch, *args):
  64.         if instance.collide_point(*touch.pos):
  65.             self.ids.entry.text += instance.text
  66.             return False # don't send event to other buttons
  67.  
  68.  
  69. class CalcApp(App):
  70.     def build(self):
  71.         return Calculate()
  72.  
  73.  
  74. if __name__ == '__main__':
  75.     CalcApp().run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement