Kivy如何删除标签并添加

时间:2018-04-18 21:46:03

标签: python kivy

我想制作一个简单的游戏,你可以点按并赚钱。我做了一些代码,但是我不知道如何删除标签。现在它所做的只是在money变量上加1并制作新标签。

的.py

money = 0

    class GameScreen(Screen):
        def money(self):
            global money
            money += 1
            self.add_widget(Label(text=str(money), color=(1,0,0,1), font_size=(45),size_hint=(0.2,0.1), pos_hint={"center_x":0.5, "center_y":0.9}))
            print(money)

.kv

<GameScreen>:
    name: "GameScreen"
    canvas:
        Color:
            rgb: 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size

    Button:
        size: self.texture_size
        on_release: root.money()
        text: "Press"
        font_size: 50
        color: 1,1,1,1
        background_color: (0,0,0,1)
        background_normal: ""
        background_down: ""
        size_hint: None, None
        pos_hint: {"center_x":0.5, "center_y":0.6}
        width: self.texture_size[0] + dp(10)
        height: self.texture_size[1] + dp(10)

1 个答案:

答案 0 :(得分:3)

删除标签以使用其他文本放置窗口小部件会以不可避免的方式消耗资源,您只需更新文本。因此,您必须在第一次添加标签,然后更新文本。另一方面,建议变量,类和函数的名称不相同。并尝试避免使用全局变量,因为它们很难调试。

进行这些更改后,我们获得以下代码:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.screenmanager import Screen

class GameScreen(Screen):
    def __init__(self, **args):
        Screen.__init__(self, **args)
        self.money = 0
        self.label = Label(text=str(self.money), color=(1,0,0,1), font_size=(45),size_hint=(0.2,0.1), pos_hint={"center_x":0.5, "center_y":0.9})
        self.add_widget(self.label)

    def add_money(self):
        self.money += 1
        self.label.text = str(self.money)

Builder.load_string('''
<GameScreen>:
    name: "GameScreen"
    canvas:
        Color:
            rgb: 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size

    Button:
        size: self.texture_size
        on_release: root.add_money()
        text: "Press"
        font_size: 50
        color: 1,1,1,1
        background_color: (0,0,0,1)
        background_normal: ""
        background_down: ""
        size_hint: None, None
        pos_hint: {"center_x":0.5, "center_y":0.6}
        width: self.texture_size[0] + dp(10)
        height: self.texture_size[1] + dp(10)
    ''')

class TestApp(App):
    def build(self):
        return GameScreen()

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