首页 > 解决方案 > 按下按钮时将 var +1 添加到标签(kivy)

问题描述

源函数 - add_click

通过按下按钮将 +1 添加到 self.click 到标签(self.RightBar)

我为游戏编写了一个函数(点击器),其本质是通过按下标签中的按钮添加了一个计数器。

    def add_click(self, instance):

        self.click += 1

    def build(self):

        self.click = "0"

        Body = BoxLayout(orientation = "vertical",
                                            size_hint = [1,.8],
                                            spacing = 0.7)

        Land = BoxLayout()

        LeftBar = Image(source = "/storage/emulated/0/kivy/image/84.jpg", size_hint = [None, None], size = [1080, 610])

        self.RightBar = Label(text = "MONEY:" + "\n" + "\nUNITS:" + "\n" + "\nDAY:" + "\n" + "\nCLICKS:" + "  " + self.click,
                                        size_hint = [.3,1],
                                        valign = "top",
                                        halign = "left",
                                        text_size = [750,900])

        Land.add_widget(LeftBar);
        Land.add_widget(self.RightBar);

        Body.add_widget(Land);

        NavBar = BoxLayout(size_hint = [1, .55],
                                                spacing = 0.8)

        Body.add_widget(NavBar);

        Body.add_widget(Button(text = "*click*",
                                        font_size = 20,                                                                 background_normal = "",
                                        background_color = [.11,.11,.10,.4],
                                        size_hint = [1,1.7],
                                        on_press = self.add_click));

        return Body

标签: pythonkivy

解决方案


我通过重写这样的函数找到了解决方案:

def add_click(self, instance):
    self.click = int(self.click)
    self.click += 1
    self.click = str(self.click)
    self.RightBar.text = str("MONEY:"+"\n"+"\nUNITS:"+"\n"+"\nDAY:"+"\n"+"\nCLICKS:"+" "+self.click)

推荐阅读