I have made an easy app where i try to show my issue. When using python to draw a line in kivy (using the with self.canvas method) the line gets drawn from a center_x and center_y of 50.
Using kivy Lang draws the line correctly in the center. Here is a simple code example:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line
class TestWidget(Widget):
def draw(self):
with self.canvas:
Line(points=[self.center_x,self.center_y,self.center_x,self.center_y+100], width=2)
class TestApp(App):
def build(self):
test = TestWidget()
test.draw()
return test
if __name__ == '__main__':
TestApp().run()
and the corresponding test.kv file:
#:kivy 1.11.1
<TestWidget>:
canvas:
Line:
width: 5
points: (self.center_x,self.center_y,self.center_x,self.center_y+100)
result is like this:
Any idea why using python code is not working?
Both codes are not equivalent, in the case of python you are only establishing that the position of the line is based on the center of the widget at that time, that is, at the beginning, instead in .kv it is indicating that the line position is always it will be with respect to the center of the Widget.
TL; DR;
Explanation:
In kv the binding is a natural and implicit process that in python is not doing it, besides that its implementation is simpler, for example the following code:
Foo:
property_i: other_object.property_j
In that case its equivalent in python is:
foo = ...
other_object = ...
other_object.bind(property_j=foo.setter("property_i"))
And it is not:
foo.property_i = other_object.property_j
Since with the bind you are indicating before a change of property_j update property_i with that value, but in the last code you only indicate at this moment copy the value of property_j in property_i.
In your particular case, the center you take is before displaying the widget and kivy taking default configurations and other properties into consideration, changes the geometry of the widget after it is displayed.
Solution
Making the necessary modifications taking into account the previous explanation the following code is an equivalent of the .kv code
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line
class TestWidget(Widget):
def __init__(self, **kwargs):
super(TestWidget, self).__init__(**kwargs)
with self.canvas:
self.line = Line(width=2)
self.bind(center=lambda *args: self.draw())
def draw(self):
self.line.points = [
self.center_x,
self.center_y,
self.center_x,
self.center_y + 100,
]
class TestApp(App):
def build(self):
test = TestWidget()
return test
if __name__ == "__main__":
TestApp().run()
With kv language your declarations automatically update when their dependencies change. That means that when the widget's centre goes from (50, 50) to something else, the line is redrawn in the new location.
Your Python code doesn't do this, it just draws the line once using whatever its centre is at the moment the code runs. That value is (50, 50), since that's the default before positioning has taken place.
The solution is to write code in Python that updates the line when the widget centre changes, something along the lines of declaring the line with self.line = Line(...) and self.bind(centre=some_function_that_updates_self_dot_line).
Related
I'm playing around with a Kivy Scrollview, adding scrollbars, etc, and getting a strange crash. I don't specifically think it's a bug, it's probably some configuration element on Scrollviews that I'm missing, but who knows?
Given this code:
"""
Source: https://stackoverflow.com/questions/35626320/kivy-image-scrolling
"""
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
class TutorialApp(App):
def build(self):
some_img = Image(source='/home/data/map/Map_07C.jpg', size_hint=(None, None),
keep_ratio=True, size=(Window.width * 2, Window.height * 2))
sv = ScrollView(size=Window.size, bar_width=50,
scroll_type=['bars', 'content'], effect_cls='ScrollEffect')
sv.add_widget(some_img)
return sv
if __name__ == "__main__":
TutorialApp().run()
if I click or touch the Scrollbars in any way, I get this error:
File "kivy_env/lib/python3.8/site-packages/kivy/uix/scrollview.py", line 908, in on_scroll_move
self.effect_x.update(touch.x)
File "kivy_env/lib/python3.8/site-packages/kivy/effects/scroll.py", line 116, in update
self.displacement += abs(val - self.history[-1][1])
IndexError: list index out of range
However - if I first click the bitmap being scrolled, I can use the scrollbars with no problem.
So what's up? Is there some Scrollview configuration I'm missing? (It took me a while to even find the scroll_type option to enable the bars, at first I could only mouse-drag the bitmap). Or is it a bug - given that it's referencing history[-1], maybe that doesn't exist yet?
Yep, it's a bug. Just searched the Kivy repo on Github, found:
Effects Scroll Exception
The link does have a "workaround" patch, that you can manually apply to the installed library. Just tested the patch, it fixes my problem. Basically puts a try/except/return block around the line with history[-1]
technically is a bug but we can note from the desktop and mobile apps that they use different scroll_type=['bars', 'content'] in the desktop app we use bars
and in the mobile app we use content so the bug only occurs when we use two types of scroll_type so we can say that the scrollview does not design to use two type of scroll_type in the same time
Another workaround is calling a function on_touch_down that checks the mouse's x-position and changes the scroll type to either only ['Bars'] or only ['Content'] accordingly. Note, I set mine to check Window.width - 12 as that is the width of scroll bar that I use. Default is 2.
# tutorial.kv
<SV>:
on_touch_down: self.check_pos()
bar_width: 12
# main.py
from kivy.uix.scrollview import ScrollView
class SV(ScrollView):
def check_pos(self):
if Window.mouse_pos[0] <= (Window.width - 12):
self.scroll_type = ['content']
else:
self.scroll_type = ['bars']
I am making a Kivy application right now, and in one part of it, I am getting data as an array of floating point numbers and I want to draw a line in Kivy using the data.
The problem is, I want it to constantly run, so I used threading, but Kivy would not draw the line. here is a stripped down version of the code that illustrates the problem:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line
from threading import Thread
class MyWidget(Widget):
def Draw(self):
with self.canvas:
Line(points=[100, 200, 300, 400])
class MainApp(App):
def build(self):
return MyWidget()
Thread(target=MyWidget().Draw).start()
MainApp().run()
I want this code to draw a line with points 100, 200, 300, 400.
but instead, the app opens and does nothing, help will be appreciated!
I modified your example a bit.
Try start the thread in the init method instead. Because when you do MyWidget().Draw, you do that with a new MyWidget object, and not the one you returned in your build method. So that line will never be drawn. But the line in another widget which is not on the screen.
Try like this:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line, InstructionGroup
from threading import Thread
from random import randint
import time
class MyWidget(Widget):
def __init__(self, **kwargs):
super(MyWidget, self).__init__(**kwargs)
self.ig = InstructionGroup()
self.line = Line(points=[100, 200, 300, 400])
self.ig.add(self.line)
self.canvas.add(self.ig)
Thread(target=self.draw).start()
def draw(self):
while True:
self.line.points = [randint(0,400) for i in range(4)]
time.sleep(0.5)
class MainApp(App):
def build(self):
return MyWidget()
MainApp().run()
I am trying to plot various line segments using kivy. The line appears really small (at one end of the screen) and I would like to scale it up. Ideally, I would like to specify coordinates from the center of screen and specify width and height so that the line segments appear well. Here is the code I wrote:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.graphics import Color, Ellipse, Line
class MyWidget(Widget):
def __init__(self, **kwargs):
super(MyWidget, self).__init__(**kwargs)
with self.canvas:
for obstacle in obstacles:
print obstacle
Line(points=[20, 5, 40, 5],width=1)
pass
# add your instruction for main canvas here
class MotionPlanningApp(App):
def build(self):
root = GridLayout(cols=1, padding=5, spacing=1)
root.add_widget(MyWidget())
return root
if __name__ == '__main__':
MotionPlanningApp().run()
Is there some way to do this in kivy?
You can use Translate instructions to move the line (effectively moving the origin of the canvas) and Scale instructions to stretch it.
For instance, you could have:
from kivy.core.window import Window
with self.canvas:
self.translate = Translate(Window.width / 2, Window.height / 2.)
You would also need to modify the translate instruction later if the window size changed, by binding a function to that.
Regardless, though, the coordinates are in screen pixels so the line is currently small just because you only made it 20 pixels long.
I'm just starting off with Kivy and it's different to what I'm used to, apologies if I'm making stupid mistakes!
Right now I'm trying to create an app that does the following:
Allows creation of Nodes (ellipses for now).
Allows the user to position the nodes by dragging.
Allows the user to connect the nodes with a line.
So far I've achieved the first, and the second somewhat.
Right now my dragging is not working too well. If I move the mouse too quickly it cancels the move method (as it is no longer in contact). Is there a better way to produce dragging or do I just increase the refresh rate (if so how?).
def on_touch_move(self, touch):
if self.collide_point(touch.x, touch.y):
self.pos=[touch.x-25, touch.y-25]
I've tried using Buttons instead, using the on_press method to track the moving better. However now I'm having difficulty updating the position of the button (mostly just syntax).
class GraphNode(Button):
background_disabled_down=1
background_disabled_normal=1
def moveNode(self):
with touch:
self.pos=[touch.x-25, touch.y-25]
I have no idea how to use the touch value, and keep getting an array of errors. (Obviously the current attempt doesn't work, I just thought it was funny).
As you could probably tell, I also don't know how to get rid of the button graphics, as I want to use the ellipse. As an added bonus if someone could show me how to change the colour of the ellipse on button press that would be cool!
The kv file:
<GraphNode>:
size: 50, 50
canvas:
Ellipse:
pos: self.pos
size: self.size
on_press:
root.moveNode()
I want to be able to use the touch information to update the position, but don't know how to implement it here.
Full core python code:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.properties import NumericProperty, ReferenceListProperty,\
ObjectProperty
from kivy.graphics import Color, Ellipse, Line
class GraphInterface(Widget):
node = ObjectProperty(None)
class GraphApp(App):
def build(self):
node = GraphNode()
game = GraphInterface()
createNodeButton = Button(text = 'CreateNode', pos=(100,0))
createEdgeButton = Button(text = 'CreateEdge')
game.add_widget(createNodeButton)
game.add_widget(createEdgeButton)
def createNode(instance):
game.add_widget(GraphNode())
print "Node Created"
def createEdge(instance):
game.add_widget(GraphEdge())
print "Edge Created"
createNodeButton.bind(on_press=createNode)
createEdgeButton.bind(on_press=createEdge)
return game
class GraphNode(Button):
def moveNode(self):
with touch:
self.pos=[touch.x-25, touch.y-25]
#def onTouchMove(self, touch):
# if self.collide_point(touch.x, touch.y):
# self.pos=[touch.x-25, touch.y-25]
pass
class GraphEdge(Widget):
def __init__(self, **kwargs):
super(GraphEdge, self).__init__(**kwargs)
with self.canvas:
Line(points=[100, 100, 200, 100, 100, 200], width=1)
pass
if __name__ == '__main__':
GraphApp().run()
If you need any other info, or anything is unclear, please let me know!
Edit: Second question moved to: Creating a dynamically drawn line in Kivy.
First, you should read up on touch events in Kivy. Of particular interest here is the section on grabbing touch events. Basically, you can "grab" a touch to ensure that the grabbing widget will always receive further events from that touch - in other words, the on_touch_move and on_touch_up following that touch event will be sent to your widget.
Basic example:
class MyWidget(Widget):
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
touch.grab(self)
# do whatever else here
def on_touch_move(self, touch):
if touch.grab_current is self:
# now we only handle moves which we have grabbed
def on_touch_up(self, touch):
if touch.grab_current is self:
touch.ungrab(self)
# and finish up here
But, even better! If you want to be able to drag widgets around, Kivy already has that: Scatter.
Just wrap your widget in a Scatter and you can drag it around. You can also use multitouch to rotate and scale a Scatter, but you can easily disable that (kv):
FloatLayout:
Scatter:
do_scale: False
do_rotation: False
MyWidget:
Side note - this is incorrect:
class GraphNode(Button):
background_disabled_down=1
background_disabled_normal=1
background_disabled_down and background_disabled_normal are Kivy properties - you should set those values in __init__.
Force these values:
class GraphNode(Button):
def __init__(self, **kwargs):
super(GraphNode, self).__init__(background_disabled_down='',
background_disabled_normal='', **kwargs)
Suggest these values (better option):
class GraphNode(Button):
def __init__(self, **kwargs):
kwargs.setdefault('background_disabled_down', '')
kwargs.setdefault('background_disabled_normal', '')
super(GraphNode, self).__init__(**kwargs)
Finally, note that these properties are filenames pointing to the images used for the disabled Button. If you remove these values, and disable your button, it will draw no background whatsoever.
I'm working through the Kivy tutorial, programming guide, and find the following code is not actually printing the button position anywhere, as far as I can tell---that is, the btn_pressed() method doesn't seem to do anything.
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()
Does anyone have any hints or ideas why this isn't working? Is this the intended behavior and I missed something or is there an error in the tutorial?
Specifically, while the instructions above produce buttons that can be clicked and flash---there doesn't seem to be any output corresponding to the method:
def btn_pressed(self, instance, pos):
print ('pos: printed from root widget: {pos}'.format(pos=pos))
Maybe it's printing black on black?
The seemingly blank, unlabeled spot in the middle is the button that accepts location and prints location to the console. I was clicking on the buttons labeled "btn" and didn't notice this place existed.
This part of the tutorial is demonstrating how you can make custom buttons that do stuff precisely like this. It would be more clear if this were labeled, but that should be doable by looking at the API.
Anyway, the code is working as expected.