Kivy create new instance of widget - python

I'm fairly new to Kivy and have a few questions about widgets.
I started out messing with Kivy a few months back. I've read some documentation but I might have missed out lots of stuff.
Is it possible to create multiple instances of the same widget class with their own properties?
My goal is to have a few rectangles that I can resize and drag around independently.
I'm taking a java class so I'll compare to what I learnt in that class:
For example, lets say I have a basic rect.java class set up to take in two variables for width and height.
So in my main .java code file I would write something like this to create a few instances of the rectangle class:
rect s1 = new rect(2,3); // width & height
rect s2 = new rect(5,4);
Then, s1.height and s2.height will have different values.
Is it possible to achieve something similar in Kivy? For now I have many classes with the same properties set up in my .kv file:
<rect1>:
canvas:
Color:
rgba: 1, 0, 1, 0.5
Rectangle:
pos: root.center_x - root.width/2,root.center_y - root.height/2
size: self.size
<rect2>:
canvas:
Color:
rgba: 1, 1, 0, 0.5
Rectangle:
pos: root.center_x - root.width/2,root.center_y - root.height/2
size: self.size
<rect3>:
canvas:
Color:
rgba: 0, 1, 0, 0.5
Rectangle:
pos: root.center_x - root.width/2,root.center_y - root.height/2
size: self.size
I've written code in my .py file for it to be resized and dragged around. For now, I copied/modified the code to work with each additional class.
For now, if I use:
Window.add_widget(rect1)
It will create a new instance directly on top of the older one but they still share the same coordinates and other properties etc. If I drag with my mouse, all the instances of that class follow the same coordinates. Once again, my goal is to have multiple rectangles that I can resize and drag around independently.

The Window should only have one widget (the application root widget). It's best to let this widget be added automatically by returning the root widget instance from App.build() or by including a root widget in your app's kv file.
In this case, a FloatLayout would make the most sense.
Also, you can use the Scatter widget to handle transformations - move (translate), resize and rotate - which might be easier than doing it yourself. Just wrap each widget in a Scatter, or make your widgets extend Scatter.

Each entry you define with the angle brackets (<, >) are class declarations not instances. If you want to instantiate a class in the kv file with different properties then use the name without the angle brackets.
Here's some working code based on the code fragments you supplied:
<MovableRect>:
size: 50, 50
canvas:
Color:
rgba: root.color
Rectangle:
size: self.size
pos: self.pos
<MyRoot#Widget>:
MovableRect:
id: rect1
color: 1, 0, 1, 0.5
pos: 5, 5
MovableRect:
id: rect2
color: 1, 1, 0, 0.5
pos: 130, 130
MovableRect:
id: rect3
color: 0, 1, 0, 0.5
pos: 250, 250
# instantiation of root widget
MyRoot:
Here's the python file (without your movement functionality because you didn't list it):
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import ScreenManager
from kivy.properties import ListProperty
class MovableRect(Widget):
color = ListProperty([1, 0, 1, 0.5])
class Test1App(App):
def build(self):
pass
if __name__ == '__main__':
Test1App().run()
For a more complete example you can refer to the excellent kivy crash course series on youtube. There's one example that's very similar to what you're trying to do:
https://www.youtube.com/watch?v=ChmfVOu9aIc

Related

How to make Kivy Checkbox a square

Is there any way to make a kivy checkbox from a circle checkbox to a square checkbox?
This is my code for my current checkbox:
CheckBox:
group: 'check'
id : chk
pos: 240,300
When you use group with a CheckBox, it changes to a circle. You can subclass CheckBox to avoid that behavior:
<MyCheckBox#CheckBox>:
canvas:
Clear:
Color:
rgba: self.color
Rectangle:
source: self._checkbox_image
size: sp(32), sp(32)
pos: int(self.center_x - sp(16)), int(self.center_y - sp(16))
This creates a MyCheckBox widget that does not display the circle behavior even when group is used. The above kv just defines the canvas by using Clear to remove the CheckBox canvas instructions, and replacing them with basically the same instructions, but eliminating the group reference.

How to make circular button in kivy using button behavior?

I think there is a way to do it in kivy rather than going round the python code.
my code in the kv file:
ButtonBehavior:
source: "round-icon.png"
the app crashes saying
AttributeError: 'ButtonBehavior' object has no attribute
'register_event_type'
round-icon.png is circular icon. The last thing that I will appreciate recommendation, How to set this button to certain size is the window?
Try importing Image also:
Image+ButtonBehavior:
source: "round-icon.png"
You need to make a custom rule(/class) that has the behavior and you need to include Image as el3phanten stated, yet it won't work only that way, because it'll return you a missing class.
Kv language creates a widget from either already registered classes, or custom classes, which may be Python + Kv (that thing you define in both files), or kv only(dynamic). I guess your intention is the dynamic one, so I'll go this way:
from kivy.app import App
from kivy.lang import Builder
kv = """
<Test#ButtonBehavior+Image>:
canvas:
Color:
rgba: 1, 0, 0, .3
Rectangle:
size: self.size
pos: self.pos
BoxLayout:
Button:
Test:
source: 'image.png'
"""
class TestApp(App):
def build(self):
return Builder.load_string(kv)
if __name__ == '__main__':
TestApp().run()
The behavior needs to be first similar to inheriting in Python, then you may add another parts, such as Image.
There's however a big problem for you in this implementation, which is visible with the Rectangle in my example. That is an area that captures every touch, which means you might have a circular image, yet the touch are is still a rectangle.
To get around that you'll need to check for a collision, thus you need to switch from dynamic class to the one that's defined even in Python, so that you can make custom collisions. Example.
That, however, might be really costly even for a single button, therefore a better solution is using something like this:
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import NumericProperty
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.image import Image
kv = """
<RoundButton>:
canvas:
Color:
rgba: 1, 0, 0, .3
Rectangle:
size: self.size
pos: self.pos
Color:
rgba: 0, 0, 1, 1
Rectangle:
size:
[self.size[0] - root.OFFSET_x,
self.size[1] - root.OFFSET_y]
pos:
[self.pos[0] + root.OFFSET_x / 2.0,
self.pos[1] + root.OFFSET_y / 2.0]
BoxLayout:
Button:
RoundButton:
source: 'image.png'
on_release: print('Release event!')
"""
class RoundButton(ButtonBehavior, Image):
OFFSET_x = NumericProperty(100)
OFFSET_y = NumericProperty(200)
def on_touch_down(self, touch):
left = touch.x >= self.pos[0] + self.OFFSET_x / 2.0
down = touch.y >= self.pos[1] + self.OFFSET_y / 2.0
up = touch.y <= self.pos[1] + self.size[1] - self.OFFSET_y / 2.0
right = touch.x <= self.pos[0] + self.size[0] - self.OFFSET_x / 2.0
if left and down and up and right:
print('collided!')
self.dispatch('on_release')
else:
print('outside of area!')
class TestApp(App):
def build(self):
return Builder.load_string(kv)
if __name__ == '__main__':
TestApp().run()
or a really low number of points to a better area coverage, yet higher than for a simple rectangle.
How to set this button to certain size is the window?
Use size_hint or directly Window.size to manipulate your widget's size. size_hint is definitely better unless you want to have everything in Window, i.e. without any proper Layout

Canvas instruction invisible in Kivy

I want to create a TextInput and modify its canvas to have a white RoundedRectangle in the background. I made the background_color transparent, but I don't see that rectangle behind the TextInput.
I've tried to instead draw on canvas.before and canvas.after. The both seemed to result in one thing: the expected Rectangle covered the cursor and the text. And while this would be expected for canvas.after, I thought canvas.before wouldn't cover anything? How to make a background through canvas instructions for a TextInput?
Here is the code:
from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.uix.textinput import TextInput
Builder.load_string('''
<Test>:
canvas: # no rectangle this way
Color:
rgba: 1, 1, 1, 1
RoundedRectangle:
pos: self.pos
size: self.size
background_color: 1, 1, 1, 0
''')
class Test(TextInput):
pass
runTouchApp(Test())
Simple! You set Color in canvas which is set to (some?) other components too (probably via OpenGL directly). Therefore you have to "unset" it - or better said set it to the default Color, which you have already access to:
from kivy.lang import Builder
from kivy.base import runTouchApp
from kivy.uix.textinput import TextInput
Builder.load_string('''
<Test>:
canvas.before:
Color:
rgba: 1, 0, 0, .5
Rectangle:
pos: self.pos
size: self.size
Color:
rgba: root.foreground_color
background_color: 1,1,1,0
''')
class Test(TextInput): pass
runTouchApp(Test())
You already have colors set in the default TextInput, so you can access them with root.
Also for more features play with background_* properties. Making an image with rounded corners will be probably better for a performance if you need it(mobiles) and you can switch between them just with setting those properties, because TextInput handles switchess automatically.

drawing in a widget contained by another widget

I'm trying to understand how kv files work.
So far, i've been able to tackle a couple errors, but I'm stuck with something that doesn't produces errors but doesn't produce the intended result.
Expected :
My goal is to create a parent widget containing two isntances of a sub-widget. The sub-widget contains a rectangle and a touch-move instruction. I want each instance to cover only part of the main widget (the rectangle is here for me to see where the sub-widget is). I assume the on-touch-move instructions should trigger only on the part of the screen where the sub-widget instance is.
Actual:
The sub-widget rectangles don't show, and the on-touch-move behaviour is triggered anywhere twice (which makes be think both sub-widgets span on the whole screen but the rectangle isn't shown).
Removing the parent widget canvas doesn't solve my problem, neither does adding only one sub-widget.
What am I doing wrong ?
python file :
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle
class MainWidget(Widget):
pass
class SubWidget(Widget):
def on_touch_move(self, touch):
self.center_x, self.center_y = (touch.x, touch.y)
print touch.x, touch.y
class testApp(App):
def build(self):
x = MainWidget()
return x
if __name__ == '__main__':
testApp().run()
kv file:
#:kivy 1.8.0
<MainWidget>:
canvas:
Color:
rgb: 0,1,0
Rectangle:
pos: self.center
size: 10,10
SubWidget:
pos: self.width - self.width/5 ,0
size: self.width/5 , self.height
SubWidget:
pos: 0, 0
size: self.width/5 , self.height
<SubWidget>:
canvas:
Color:
rgb: 1,0,0
Rectangle:
pos: self.pos
size: self.size
Thanks in advance for answers.
edit :
1) child widgets should be added within a layout. Still need to find a way to
position my widgets properly within the layout.
2) widgets' touch events are triggered even if the widget isn't directly clicked. Using widget.collide_point(*touch.pos) makes it work.
edit2 :
Fixed the .kv. Self.parent.pos/size didn't behave consistently so I moved to root.pos/size :
#:kivy 1.8.0
<MainWidget>:
canvas:
Color:
rgb: 0,1,0
Rectangle:
pos: self.center
size: 10,10
FloatLayout:
SubWidget:
pos: root.width - root.width/5 ,0
size: root.width/5 , root.height
SubWidget:
pos: 0, 0
size: root.width/5 , root.height
<SubWidget>:
canvas:
Color:
rgb: 1,0,0
Rectangle:
pos: self.pos
size: self.size
I believe you need to put the child elements into a box layout.
So it would be something like this.
<MainWidget>:
canvas:
...
BoxLayout:
SubWidget:
...
SubWidget:
...
The SubWidget elements' attributes (like pos) might need some changing.
Some more info here too.
I assume the on-touch-move instructions should trigger only on the part of the screen where the sub-widget instance is.
This assumption is incorrect. To check for the collision yourself, you can do if self.collide_point(*touch.pos): ... in your on_touch_move method.
Also, your positioning problems are caused by using only Widgets - these do not impose anything on their children, so everything except the root widget has the default pos of (0, 0) and size of (100, 100). You should use Layout classes to have widgets automatically resize and position their children.

Kivy roundish menu

I'd like to write a roundish menu with Kivy. At the end it should somehow look like this:
I've stumbled upon some problems at the early beginnings. I already created the "mainmenu"-button (0.1). Now I wanted to create 2 new menu-circles 2.1 + 2.2. The problem is that the events for the two new buttons occur when I click on the main-button but nothing happens by clicking on the new buttons.
I really appreciate any help. :)
menu.py
import kivy
kivy.require('1.8.0') # replace with your current kivy version !
from kivy.app import App
from kivy.uix.label import Label
from kivy.factory import Factory
from kivy.uix.scatter import Scatter
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
class menuApp(App):
print "test"
def secTouch(self):
print "sectouch"
class RootWidget(FloatLayout):
pass
class Menu (FloatLayout):
def newMenu(self):
dynamicMenu = Factory.First()
self.add_widget(dynamicMenu)
pass
class First(Scatter):
def firstTouch(self):
dynamicWidget = Factory.Second()
self.add_widget(dynamicWidget)
print "touch"
pass
if __name__ == '__main__':
menuApp().run()
menu.kv
#:kivy 1.8.0
#: set buttonSize 100, 100
#: set middleOfScreen 0,0
RootWidget:
<RootWidget>:
Menu
<Menu>
on_touch_down: root.newMenu()
<First>:
id: first
pos: root.size[0]/2-self.size[0]/2, root.size[1]/2-self.size[1]/2
size: 100, 100
size_hint: None, None
Widget:
on_touch_down: root.firstTouch()
id: me
size_hint: None, None
size: 100, 100
pos: root.size[0]/2-self.size[0]/2, root.size[1]/2-self.size[1]/2
canvas:
Color:
rgb: 1, 0, 0
Ellipse:
pos: me.pos
size: buttonSize
<Second#Scatter>:
pos: root.size[0]/2-self.size[0]/2+40, root.size[1]/2-self.size[1]/2+40
size: 100, 100
size_hint: None, None
on_touch_down: app.secTouch()
canvas:
Color:
rgb: 1, 0, 0
Ellipse:
pos: root.size[0]/2-self.size[0]/2+40, root.size[1]/2-self.size[1]/2+40
size: buttonSize
Every touch event is dispatched to the on_touch_down event handlers, not just touches in a given area (within the widget). Each time you touch the screen, regardless of where, the Menus on_touch_down is fired. You should use collide_point() to ensure the touch is within the given boundaries.
The Grabbing Touch Events section of the Kivy guide has an example of collide_point(), as well as some more info about touch events in general.
But, the basic idea:
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
# do stuff here
return True # 'handle' the event so it will not propagate

Categories