简体   繁体   中英

Kivy layouts don't display buttons correctly

I'm trying to make a keypad sort of thing in kivy, by arranging 9 buttons in a 3x3 GridLayout. However, after running the code, it only shows 1 button in the bottom right corner.

My code:

from kivy.uix.button import Button
from kivy.uix.boxlayout import GridLayout
from kivy.app import App

class root(GridLayout):
    def __init__(self, **kwargs):
        super(GridLayout, self).__init__(**kwargs)
        self.cols = 2
        self.rows = 2
        self.button1 = Button(text = '1')
        self.button2 = Button(text = '2')
        self.button3 = Button(text = '3')
        self.button4 = Button(text = '4')
        self.button5 = Button(text = '5')
        self.button6 = Button(text = '6')
        ...........
        self.add_widget(self.button1)
        self.add_widget(self.button2)
        self.add_widget(self.button3)
        self.add_widget(self.button4)
        ...........


class myApp(App):
    def build(self):
        l = root()
        return l

myApp().run()

Any help?

You have the following errors:

  • To import GridLayout you must use from kivy.uix.gridlayout import GridLayout
  • When you use super() you must pass as the first parameter the name of the class, that is, super(root, self).__init__(**kwargs) .
  • You say you want 3 rows and 3 columns, so you should use self.cols = 3 , self.rows = 3 .

Code:

from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.app import App

class root(GridLayout):
    def __init__(self, **kwargs):
        super(root, self).__init__(**kwargs)
        self.cols = 3
        self.rows = 3
        self.button1 = Button(text = '1')
        self.button2 = Button(text = '2')
        self.button3 = Button(text = '3')
        self.button4 = Button(text = '4')
        self.button5 = Button(text = '5')
        self.button6 = Button(text = '6')
        ...........
        self.add_widget(self.button1)
        self.add_widget(self.button2)
        self.add_widget(self.button3)
        self.add_widget(self.button4)
        ...........


class myApp(App):
    def build(self):
        l = root()
        return l

myApp().run()

A simpler and more elegant solution is to use a for-loop:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button


class Root(GridLayout):
    def __init__(self, **kwargs):
        super(Root, self).__init__(**kwargs, rows=3, cols=3)

        for i in range(1, 10):
            btn = Button(text=str(i))
            self.add_widget(btn)


class myApp(App):
    def build(self):
        l = Root()
        return l


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM