kivytoast.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from kivy.uix.label import Label
  2. from kivy.clock import Clock
  3. from kivy.lang import Builder
  4. from kivy.core.window import Window
  5. from kivy.properties import NumericProperty
  6. TOAST_KV='''
  7. <_Toast@Label>:
  8. size_hint: (None, None)
  9. halign: 'center'
  10. valign: 'middle'
  11. color: (1.0, 1.0, 1.0, self._transparency)
  12. canvas:
  13. Color:
  14. rgba: (0.5, 0.5, 0.5, self._transparency)
  15. Rectangle:
  16. size: self.size
  17. pos: self.pos
  18. Color:
  19. rgba: (0.0, 0.0, 0.0, 1.0)
  20. Rectangle:
  21. size: (self.size[0] - 2, self.size[1] - 2)
  22. pos: (self.pos[0] + 1, self.pos[1] + 1)
  23. Color:
  24. rgba: self.color
  25. Rectangle:
  26. texture: self.texture
  27. size: self.texture_size
  28. pos: int(self.center_x - self.texture_size[0] / 2.), int(self.center_y - self.texture_size[1] / 2.)
  29. '''
  30. Builder.load_string(TOAST_KV)
  31. class _Toast(Label):
  32. _transparency = NumericProperty(1.0)
  33. def __init__(self, text, *args, **kwargs):
  34. '''Show the toast in the main window. The attatch_to logic from
  35. :class:`~kivy.uix.modalview` isn't necessary because a toast really
  36. does need to go on top of everything.
  37. '''
  38. self._bound = False
  39. super(_Toast, self).__init__(text=text, *args, **kwargs)
  40. def show(self, length_long, *largs):
  41. duration = 5000 if length_long else 1000
  42. rampdown = duration * 0.1
  43. if rampdown > 500:
  44. rampdown = 500
  45. if rampdown < 100:
  46. rampdown = 100
  47. self._rampdown = rampdown
  48. self._duration = duration - rampdown
  49. Window.add_widget(self)
  50. Clock.schedule_interval(self._in_out, 1/60.0)
  51. def on_texture_size(self, instance, size):
  52. self.size = map(lambda i: i * 1.3, size)
  53. if not self._bound:
  54. Window.bind(on_resize=self._align)
  55. self._bound = True
  56. self._align(None, Window.size)
  57. def _align(self, win, size):
  58. self.x = (size[0] - self.width) / 2.0
  59. self.y = size[1] * 0.1
  60. def _in_out(self, dt):
  61. print dt
  62. self._duration -= dt * 1000
  63. if self._duration <= 0:
  64. self._transparency = 1.0 + (self._duration / self._rampdown)
  65. print self._transparency
  66. if -(self._duration) > self._rampdown:
  67. Window.remove_widget(self)
  68. return False
  69. def toast(text, length_long=False):
  70. _Toast(text=text).show(length_long)