Invalid indentation, must be a multiple of 8 spaces, rounded button kivy .kv file - kivy

so yeah I was learning kivy - "rounded buttons" and when I ran the tutorial's program ---------------
ERROR:
https://i.stack.imgur.com/rGhSa.png
python:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.core.window import Window
Builder.load_file("my.kv")
class MyLayout(Widget,App):
def __init__(self,*args,**kwargs):
super(MyLayout, self).__init__(**kwargs)
class AwesomeApp(App):
def build(self):
Window.clearcolor = (1,1,1,1)
return MyLayout()
if __name__ == '__main__':
AwesomeApp().run()
.kv
<MyLayout>
BoxLayout:
orientation: "vertical"
size: root.width, root.height
padding: 50
spacing: 20
Button:
text: "Hello World!"
RoundedButton:
text: "Goodbye World!"
pos_hint: {'center_x': 0.5}
size_hint: (1, .3)
#background_color: (0/255,255/255,203/255,1)
#background_normal: ''
<RoundedButton#Button>
background_color: (0,0,0,0)
background_normal: ''
canvas.before:
Color:
rgba: (0/255,255/255,203/255,1)
RoundedRectangle:
size: self.size
pos: self.pos
radius: [58]
thanks,can anyone help, don't like these errors,
indentation error it seems like

You are not doing proper indentation you must use only one type of indentation in a file but you are using 8 spaces and 4 spaces both as indentation that is why error is coming.
Here,I have used 4 spaces as indentation in whole code that is why its working fine.
<MyLayout>
BoxLayout:
orientation: "vertical"
size: root.width, root.height
padding: 50
spacing: 20
Button:
text: "Hello World!"
RoundedButton:
text: "Goodbye World!"
pos_hint: {'center_x': 0.5}
size_hint: (1, .3)
#background_color: (0/255,255/255,203/255,1)
#background_normal: ''
<RoundedButton#Button>
background_color: (0,0,0,0)
background_normal: ''
canvas.before:
Color:
rgba: (0/255,255/255,203/255,1)
RoundedRectangle:
size: self.size
pos: self.pos
radius: [58]

Related

Kivy AnchorPoint is not in the right place

I am trying to just put a piece of text centred in the top on the window but it ends up truncated in the bottom left.
I have the following python code:
# anchortest.py
from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.widget import Widget
class Root(Widget):
pass
class TextTitle(AnchorLayout):
pass
class AnchorTestApp(App):
def build(self):
return Root()
AnchorTestApp().run()
and it's associated kv file.
# anchortest.kv
<Root>
TextTitle:
<TextTitle>
anchor_x: 'center'
anchor_y: 'top'
Label:
id: score
text: 'Hello World'
font_name: 'Courier New'
font_size: 40
pad_x: 10
pad_y: 10
When I run the app I get this:
Don't use AnchorLayout for this case, just use BoxLayout with
pos_hint: {'top': 1}
size_hint_y: None
from kivy.app import App
from kivy.lang.builder import Builder
KV = """
Screen:
BoxLayout:
orientation: 'vertical'
BoxLayout:
pos_hint: {'top': 1}
size_hint_y: None
canvas.before:
Color:
rgba: [0.5, 0, 1, 1]
Rectangle:
pos: self.pos
size: self.size
Label:
text: 'Hello World'
font_size: sp(60)
BoxLayout:
Label:
text: 'Screen text'
"""
class TestApp(App):
def build(self):
return Builder.load_string(KV)
TestApp().run()
You also can use Label parametrs valign and halign:
KV = """
Screen:
Label:
text: 'Hello World'
font_size: sp(60)
text_size: self.size
halign: 'center'
valign: 'top'
"""
In order to control sizing, you must specify text_size to constrain
the text and/or bind size to texture_size to grow with the text.
If you really want to use AnchorLayout for some reason, it's done this way. Following the kivy documentation, in order for the AnchorLayout rules to apply, the Label must be set with
size_hint_y: None
height: self.height
The size_hint is a tuple of values used by layouts to manage the sizes
of their children. It indicates the size relative to the layout’s size
instead of an absolute size (in pixels/points/cm/etc)
KV = """
AnchorLayout:
anchor_x: 'center'
anchor_y: 'top'
Label:
text: 'Hello World'
font_size: sp(60)
size_hint_y: None
height: self.height
"""

KV file popup does not respond with proper action

My popup.KV file content:
<ConfirmPopup>:
cols:1
Label:
text: root.text
canvas.before:
Color:
rgba: 1, 0, 1, 0.4
Rectangle:
size: self.size
pos: self.pos
GridLayout:
cols: 2
size_hint_y: None
height: '44sp'
Button:
text: 'Yes'
canvas.before:
Color:
rgba: 0, 1, 0, 1
Rectangle:
size: self.size
pos: self.pos
on_release: root.dispatch('on_answer','yes')
Button:
text: 'No'
canvas.before:
Color:
rgba: 1, 0, 0, 1
Rectangle:
size: self.size
pos: self.pos
on_release: root.dispatch('on_answer', 'no')
and the popup.PY file:
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.popup import Popup
from kivy.properties import StringProperty
class ConfirmPopup(GridLayout):
text = StringProperty('AAAA')
def __init__(self, **kwargs):
self.register_event_type('on_answer')
super(ConfirmPopup, self).__init__(**kwargs)
def on_answer(self, *args):
pass
class PopupTest():
def __init__(self):
self.popup = None
def build(self):
Builder.load_file('popup.kv')
content = ConfirmPopup(text='Do You Love Kivy?')
content.bind(on_answer=self._on_answer)
self.popup = Popup(title="Answer Question",
content=content,
size_hint=(None, None),
size=(480, 400),
auto_dismiss=False)
self.popup.open()
def _on_answer(self, instance, answer):
print("USER ANSWER: ", repr(answer))
self.popup.dismiss()
def show():
pop = PopupTest()
pop.build()
THis is the app.py file that uses the popup
import kivy
from kivy.app import App
from popup import *
class PopTest(App):
show()
if __name__ == '__main__':
PopTest().run()
My problem is that the popup displays correctly, the buttons blink when clicked BUT the appropriate message is not printed and the popup is not dismissed when a button is clicked. To me it looks like the button event is not bound to the actions. How do I fix it.
Thanks for a fix and any explanations.
Your PopupTest class must be an EventDispatcher in order for your code to work as you want. Just modify PopupTest slightly:
class PopupTest(Widget):
def __init__(self):
super(PopupTest, self).__init__()
self.popup = None

Kivy: Don't know how to update "on_size: root.center = win.Window.center" in ScreenManager

I added the Kivy scatter example to a kivy screen. But it didn´t work properly. I have to reconfigure the center on the window. It's done in the kv-file. But I don´t know how to do it on a screen. See the code below.
python
class Picture(Scatter):
source = StringProperty(None)
class ScreenThree(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
root = BoxLayout() # instantiate BoxLayout
self.add_widget(root) # add BoxLayout to screen
curdir = dirname(__file__)
for filename in glob(join(curdir, 'images', '*')):
print(filename)
try:
picture = Picture(source=filename, rotation=randint(-30, 25))
root.add_widget(picture)
except Exception as e:
Logger.exception('Pictures: Unable to load <%s>' % filename)
def on_pause(self):
return True
class TestApp(App):
def build(self):
sm = ScreenManager()
sc1 = ScreenOne(name='screen1')
sc2 = ScreenTwo(name='screen2')
sc3 = ScreenThree(name='screen3')
sm.add_widget(sc1)
sm.add_widget(sc2)
sm.add_widget(sc3)
print (sm.screen_names)
return sm
if __name__ == '__main__':
TestApp().run()
kivy
#:kivy 1.0
#:import kivy kivy
#:import win kivy.core.window
FloatLayout:
canvas:
Color:
rgb: 1, 1, 1
Rectangle:
source: 'data/images/background.jpg'
size: root.size
BoxLayout:
padding: 10
spacing: 10
size_hint: 1, None
pos_hint: {'top': 1}
height: 44
Image:
size_hint: None, None
size: 24, 24
source: 'data/logo/kivy-icon-24.png'
Label:
height: 24
text_size: self.width, None
color: (1, 1, 1, .8)
text: 'Kivy %s - Pictures' % kivy.__version__
<Picture>:
on_size: root.center = win.Window.center <-- this is the question i guess
size: image.size
size_hint: None, None
Image:
id: image
source: root.source
# create initial image to be 400 pixels width
size: 400, 400 / self.image_ratio
# add shadow background
canvas.before:
Color:
rgba: 1,1,1,1
BorderImage:
source: 'shadow32.png'
border: (36,36,36,36)
size:(self.width+72, self.height+72)
pos: (-36,-36)
See the example here, Kivy Gallery of Examples » Basic Picture Viewer
In the kv file, on_size: root.center = win.Window.center will work fine, when you make the instantiated object, FloatLayout: as child of class rule, <ScreenThree>: plus some enhancements in Python script.
kv file
Replace #:kivy 1.0 with the Kivy version installed e.g. #:kivy 1.11.1
Add class rule, <ScreenThree>: and make FloatLayout: object as child of <ScreenThree>:
Snippets - kv file
<ScreenThree>:
FloatLayout:
canvas:
Color:
rgb: 1, 1, 1
Rectangle:
source: 'data/images/background.jpg'
size: root.size
BoxLayout:
padding: 10
spacing: 10
size_hint: 1, None
pos_hint: {'top': 1}
height: 44
Image:
size_hint: None, None
size: 24, 24
source: 'data/logo/kivy-icon-24.png'
Label:
height: 24
text_size: self.width, None
color: (1, 1, 1, .8)
text: 'Kivy %s - Pictures' % kivy.__version__
py file
Remove root = BoxLayout() and self.add_widget(root)
Replace root.add_widget(picture) with self.add_widget(picture)
Snippets - py file
class ScreenThree(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
curdir = dirname(__file__)
for filename in glob(join(curdir, 'images', '*')):
print(filename)
try:
picture = Picture(source=filename, rotation=randint(-30, 25))
self.add_widget(picture)
except Exception as e:
Logger.exception('Pictures: Unable to load <%s>' % filename)
Output

Kivy: How can I combine the two screens into one?

I am new to kivy. I have two screens and I want to combine them into one.
The code for the first screen:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.scrollview import ScrollView
from kivy.lang import Builder
Builder.load_string('''
<Button>:
font_size: 40
color: 0,1,0,1
<Widgets>:
Button:
size: root.width/2, 75
pos: root.x , root.top - self.height
text: 'OK'
Button:
size: root.width/2, 75
pos: root.x + root.width/2, root.top - self.height
text: 'Cancel'
Label:
text: "bbbbbaäa üß AäÄ"
size: root.width, 75
valign: 'middle'
halign: 'center'
anchor: 'left'
pos: root.x, root.top - 150
font_size: 50
height: 75
Label:
text: "Tssssssssssa #aaäa Äaaäa Üaa Maaäa a"
size: root.width, 75
valign: 'middle'
halign: 'left'
anchor: 'left'
pos: root.x, root.top - 150 - 50
font_size: 30
height: 50
''')
class ScrollableLabel(ScrollView):
pass
class Widgets(Widget):
def build(self):
return Widgets()
class MyApp(App):
def build(self):
return Widgets()
if __name__ == "__main__":
MyApp().run()
The code for the second screen is from Alexander Taylor: https://github.com/kivy/kivy/wiki/Scrollable-Label
I paste the code here again:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.properties import StringProperty
from kivy.lang import Builder
long_text = 'yay moo cow foo bar moo baa ' * 100
Builder.load_string('''
<ScrollableLabel>:
Label:
size_hint_y: None
height: self.texture_size[1]
text_size: self.width, None
text: root.text
''')
class ScrollableLabel(ScrollView):
text = StringProperty('')
class ScrollApp(App):
def build(self):
return ScrollableLabel(text=long_text)
if __name__ == "__main__":
ScrollApp().run()
Question one:
I want to combine those two screens into one, to have the Scrollbale Label from the second screen below the Label from the first screen. How can I do it?
Question two:
I want to have the Label text from first code started from left. Now the text is in the middle of the Label. It seems that anchor: 'left' is not working. How can I do it?
And help will be appreciated. Thanks.
You can do that like this:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from kivy.lang import Builder
from kivy.properties import StringProperty
Builder.load_string('''
<Button>:
font_size: 40
color: 0,1,0,1
<Widgets>:
GridLayout:
size_hint: 1,0.4
cols: 2
rows: 2
Button:
text: 'OK'
Button:
text: 'Cancel'
Label:
text: "bbbbb"
font_size: 50
halign: "left"
size: self.texture_size
text_size: root.width/2, None
Label:
text: "Tssssssssssa #aaäa Äaaäa Üaa Maaäa a"
font_size: 30
halign: "left"
size: self.texture_size
text_size: root.width/2, None
ScrollView:
Label:
size_hint_y: None
height: self.texture_size[1]
text_size: self.width, None
text: root.text
''')
class Widgets(BoxLayout):
text = StringProperty("")
def __init__(self,**kwargs):
super(Widgets,self).__init__(**kwargs)
self.orientation = "vertical"
self.text = 'yay moo cow foo bar moo baa ' * 100
class MyApp(App):
def build(self):
return Widgets()
if __name__ == "__main__":
MyApp().run()

Kivy app with .kv file doesn't display

I am trying to modify this example: https://github.com/inclement/kivycrashcourse/blob/master/video14-using_a_screenmanager/after.py to make it work with a .kv file. This is my myscreenmanager.py file:
from kivy.app import App
from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.properties import ListProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
import time
import random
class FirstScreen(Screen):
pass
class SecondScreen(Screen):
pass
class ColourScreen(Screen):
colour = ListProperty([1., 0., 0., 1.])
class MyScreenManager(ScreenManager):
def new_colour_screen(self):
name = str(time.time())
s = ColourScreen(name=name,
colour=[random.random() for _ in range(3)] + [1])
self.add_widget(s)
self.current = name
class MyScreenManagerApp(App):
def build(self):
return MyScreenManager()
if __name__ == "__main__":
MyScreenManagerApp().run()
And this is my myscreenmanager.kv file:
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
MyScreenManager:
transition: FadeTransition()
FirstScreen:
SecondScreen:
<FirstScreen>:
name: 'first'
BoxLayout:
orientation: 'vertical'
Label:
text: 'first screen!'
font_size: 30
BoxLayout:
Button:
text: 'goto second screen'
font_size: 30
on_release: app.root.current = 'second'
Button:
text: 'get random colour screen'
font_size: 30
on_release: app.root.new_colour_screen()
<SecondScreen>:
name: 'second'
BoxLayout:
orientation: 'vertical'
Label:
text: 'second screen!'
font_size: 30
BoxLayout:
Button:
text: 'goto first screen'
font_size: 30
on_release: app.root.current = 'first'
Button:
text: 'get random colour screen'
font_size: 30
on_release: app.root.new_colour_screen()
<ColourScreen>:
BoxLayout:
orientation: 'vertical'
Label:
text: 'colour {:.2},{:.2},{:.2} screen'.format(*root.colour[:3])
font_size: 30
Widget:
canvas:
Color:
rgba: root.colour
Ellipse:
pos: self.pos
size: self.size
BoxLayout:
Button:
text: 'goto first screen'
font_size: 30
on_release: app.root.current = 'first'
Button:
text: 'get random colour screen'
font_size: 30
on_release: app.root.new_colour_screen()
After running the app nothing is displayed on the screen. No errors in console. Switching back to Builder.load_string displays the app as expected.
Found my mistake: when using a .kv file the root widget needs to be surrounded in <>, like this:
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
<MyScreenManager>:
transition: FadeTransition()
FirstScreen:
SecondScreen:
Not sure why the discrepancy between load_string and .kv files, but it works now.

Resources