Reputation: 3584
What I try is part of a larger App but I posted here the minimum to understand my problem:
I want to change the size of a rectangle, and that this size depends on the root.height .
3 cases:
1) When I create a rectangle with "root.height/4" as a height, the size varies as I resize the root window. So far no problem
2) When I tried to assign "root.height/4" to an attribut and call this attribut when setting the size of my rectangle I get the following error: "TypeError: a float is required".
Python file:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle, Color
class BriqueApp(App):
def build(self):
return BriqueGUI()
class BriqueGUI(Widget):
pass
BriqueApp().run()
Kv file:
#:kivy 1.9.1
<BriqueGUI>:
h: root.height/4
color: (1,0,0,1)
canvas:
Color:
rgba: root.color
Rectangle:
size: (200, self.h)
pos: (0,0)
3) When I tried to reassign a value depending on, for example "root.height/2", when an event is call (here on_touch_down) : The size of my Rectangle changes but when I resize my windows my rectangle doesn't resize with it. You can see the problem here loading the file, clicking in the main window, and changing its size.
Python file:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle, Color
class BriqueApp(App):
def build(self):
return BriqueGUI()
class BriqueGUI(Widget):
def on_touch_down(self, touch):
self.h = self.height/2
BriqueApp().run()
Kv file:
#:kivy 1.9.1
<BriqueGUI>:
h: 20
color: (1,0,0,1)
canvas:
Color:
rgba: root.color
Rectangle:
size: (200, self.h)
pos: (0,0)
Upvotes: 1
Views: 2706
Reputation: 8747
2) You have to create property in your Python code as well:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle, Color
from kivy.properties import NumericProperty
from kivy.lang import Builder
Builder.load_string("""
<BriqueGUI>:
h: root.height/4
color: (1,0,0,1)
canvas:
Color:
rgba: root.color
Rectangle:
size: (200, self.h)
pos: (0,0)
""")
class BriqueApp(App):
def build(self):
return BriqueGUI()
class BriqueGUI(Widget):
h = NumericProperty(0.0)
BriqueApp().run()
3) You're only assigning once a value to your h
property. What you need is bind
method that allows you to associate a callback that will be called any time the property changes:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle, Color
from kivy.properties import NumericProperty
from kivy.lang import Builder
Builder.load_string("""
<BriqueGUI>:
h: 20
color: (1,0,0,1)
canvas:
Color:
rgba: root.color
Rectangle:
size: (200, self.h)
pos: (0,0)
""")
class BriqueApp(App):
def build(self):
return BriqueGUI()
class BriqueGUI(Widget):
def on_touch_down(self, touch):
self.h = self.height/2
self.bind(height=self.set_h)
def set_h(self, instance, value):
self.h = value/2
BriqueApp().run()
Upvotes: 6