简体   繁体   中英

Kivy: how to change widget size using numericproperty?

Trying to make a brick widget change size each time it respawns.

The py file has

class Game(FloatLayout):
    player = ObjectProperty(None)
    playbutton = ObjectProperty(None)
    ratebutton = ObjectProperty(None)
    brickg = ObjectProperty(None)
    ballsin = NumericProperty(0)
    bricklist = ListProperty([])
    score = NumericProperty(0)
    switch = NumericProperty(0)
    level = NumericProperty(0)

     def __init__(self, *args, **kwargs):
        super(Game, self).__init__(*args, **kwargs)
        Clock.schedule_interval(self.update, 1./60)

    def spawn_brick(self, *args):
        b2 = BrickGreen(x=randint(50, self.width - 50), \
        y=randint(self.height - self.height / 4, self.height - (self.height/13)))
        self.bricklist.append(b2)
        self.add_widget(b2)

    def check_brick_spawn(self, *args):

        if len(self.bricklist) == 0:
            if self.level == 0:
                BrickGreen.brickwidth = 100
                self.spawn_brick()
            elif self.level == 1:
                BrickGreen.brickwidth = 75
                self.spawn_brick()
            else:
                BrickGreen.brickwidth = 50
                self.spawn_brick()

class BrickGreen(Widget):
    def __init__(self, **kwargs):
        super(BrickGreen, self).__init__(**kwargs)

        brickwidth = NumericProperty(0)

and the kv file has

<BrickGreen>:
    size_hint: None, None
    size: self.brickwidth, 25
    canvas:
        Color:
            rgba: 0, 1, 0, 1
        Rectangle:
            pos: self.pos
            size: self.size

Essentially, level 0 should have bricks with length of 100, once it breaks it goes to level 1 and should spawn bricks with lenght of 75, but it's staying at 100

BrickGreen.brickwidth = 100

This replaces the NumericProperty at class level with the number 100. You need to set the value of brickwidth for instances of your objects, not the classes themselves. In this case, you could (for instance) pass the width you want to your spawn_brick method, and use it when instantiating the BrickGreen.

You also need to declare the NumericProperty at class level, not inside __init__ .

I suggest reading the kivy documentation on properties and going through the examples to see how these should be used.

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