Binx
Binx

Reputation: 414

Creating a Button in Kivy

I've worked with Kivy a while back and am leaning on picking it up again. For some reason I am having trouble simply creating a button. The script runs with no errors, but is not producing anything (I get a black Screen). What am I missing?

main.py

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


class MainScreen(Widget):
    pass


class SimpleWidget(Widget):
    pass


class MyApp(App):
    def build(self):
        return MainScreen()


if __name__ == '__main__':
    MyApp().run()

main.kv

<SimpleWidget>
    Button:
        on_press: print('It's working')

<MainScreen>
    BoxLayout:
        orientation: 'vertical'
        SimpleWidget:
            text: 'Train & Model'
            color: 'red'
            background_color: 'grey'
            font_size: 30
        SimpleWidget:
            text: 'Model'
            color: 'blue'
            background_color: 'grey'
            font_size: 30

Upvotes: 0

Views: 84

Answers (1)

NameKhan72
NameKhan72

Reputation: 717

Your issue is, that the .kv-File is not loaded. Kivy says, that, if your kv-File is named "main.kv" and is located in the same directory as your main.py file, it should be loaded automatically. For me, this has never happened, so I like loading the file explicitly. Note: I also removed the "orientation" parameter of the boxlayout, as it was causing problems:

main.py:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.lang import Builder

class MainScreen(Widget):
    pass


class SimpleWidget(Widget):
    pass


class MyApp(App):
    def build(self):
        kv = Builder.load_file("main.kv")
        return MainScreen()


if __name__ == '__main__':
    MyApp().run()

main.kv:

<SimpleWidget>
    Button:
        on_press: print("It's working")

<MainScreen>
    BoxLayout:
        SimpleWidget:
            text: 'Train & Model'
            color: 'red'
            background_color: 'grey'
            font_size: 30
        SimpleWidget:
            text: 'Model'
            color: 'blue'
            background_color: 'grey'
            font_size: 30

Upvotes: 1

Related Questions