Alan Huang Alan Huang - 26 days ago 16
Python Question

Kivy add_widget only displays the last widget added

My problem in the following code is:

The screen only shows the last button added, when it should show them all side-by-side

What is the problem and what can be done to fix it?

Here is my code:

from kivy.uix.togglebutton import ToggleButton
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager,Screen
from kivy.uix.gridlayout import GridLayout

class check(Screen, GridLayout):
def __init__(self, **kwargs):
super(check, self).__init__(**kwargs)
self.cols=3
btn1 = ToggleButton(text='Male', group='sex',)
btn2 = ToggleButton(text='Female', group='sex', state='down')
btn3 = ToggleButton(text='Mixed', group='sex',)

self.add_widget(btn3)
self.add_widget(btn2)
self.add_widget(btn1)


class Bridges(App):
def build(self):
sm = ScreenManager()

newkid = check(name='newkid')
sm.add_widget(newkid)

return sm
Bridges().run()

Answer

The problem is in the order of inheritance.

Your class check inherits from two classes, Screen and GridLayout. And the position of the parent class matters, because the property and method inheritance goes left-to-right.

What I mean is - the methods that are responsible for the layout are inherited from Screen and not from GridLayout as you desire.
The fix is simple: swap the class order in the check definition:

class check(GridLayout, Screen):

instead of

class check(Screen, GridLayout):
Comments