Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Kivy widgets without using kv language?

How to create Kivy widgets without using kv language and .kv files? I am new to kivy. I usually use Tkinter, but i found out that Kivy is good for creating Android apps, so I am learning how to use it. I know that Kivy widgets are made using .kv files, but i would like to create them like widgets in Tkinter.

# Creating widgets in tkinter:
# We'll assume tkinter is imported as tk    

label_1 = tk.Label(text='Hello World', bg='white')
label_1.pack()

# Creating widgets using Kivy in .py file

label_1 = Label(text='Hello World')  # eg. Not able to set color!
add_widget(label_1)

# Creating widgets using kv language

Label:
    text: "Hello World"
    color: 1,0,0,1  

So, is there any way to make Kivy widgets completely in python? How could i set Kivy label color directly in python?

Thanks.

like image 827
pythoner Avatar asked Dec 08 '22 19:12

pythoner


1 Answers

Here's an example of Kivy application without using kv lang:

from kivy.app import App
from kivy.uix.label import Label


class TestApp(App):
    def build(self):
        return Label(
            text='Hello, world',
            color=(1, 0, 0, 1)
        )


TestApp().run()

Basically build method of kivy.app.App instance has return a main widget object, in this case a kivy.uix.Label instance. To have more complex widget you should create a subclass of some layout class and then add widgets using add_widget method.

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout


class TestWidget(BoxLayout):
    def __init__(self, **args):
        super(TestWidget, self).__init__(**args)
        label = Label(
            text='Hello, world',
            color=(1, 0, 0, 1))
        self.add_widget(label)


class TestApp(App):
    def build(self):
        return TestWidget()


TestApp().run()

I'd like to encourage you to use kv lang anyway, since it makes the code simplier.

like image 115
Nykakin Avatar answered Dec 22 '22 00:12

Nykakin