10 Rep
10 Rep

Reputation: 2270

How to put two buttons in a kivy window?

I know this question may have been asked already, but I am a beginner to Kivy, so I would like for someone to explain how to put two buttons on the same screen.

The problem is I try to return the button variable, and it works. However, when I try to return two at the same time, it will give me an error.

here is my code:

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from functools import partial


class App(App):
    def com1(self, instance, *args):
        label1 = Label(text = "Hi")
        return label1
    def com2(self, instance, *args):
        label = Label(text= "Bye")
    def build(self):
        button1 = Button(text = "Hi", size_hint = (0.25, 0.18), pos = (350, 100))
        button1.bind(on_press=partial(self.com1, button1))
        button2 = Button(text = "Bye", size_hint = (0.25, 0.18), pos = (350, 200))
        button2.bind(on_press=partial(self.com2, button2))
        return button1, button2
App().run()

Upvotes: 3

Views: 1981

Answers (1)

eyllanesc
eyllanesc

Reputation: 243887

The build method must return a single widget, so depending on how you want the buttons to be arranged you have several options such as BoxLayout, RelativeLayout, FloatLayout, etc. In this case for simplicity I will use a BoxLayout:

# ... 
from kivy.uix.boxlayout import BoxLayout
# ...
class App(App):
    # ...
    def build(self):
        button1 = Button(text="Hi", size_hint=(0.25, 0.18), pos=(350, 100))
        button1.bind(on_press=partial(self.com1, button1))
        button2 = Button(text="Bye", size_hint=(0.25, 0.18), pos=(350, 200))
        button2.bind(on_press=partial(self.com2, button2))
        boxlayout = BoxLayout()
        boxlayout.add_widget(button1)
        boxlayout.add_widget(button2)
        return boxlayout
# ...

Upvotes: 4

Related Questions