Saurabh Shrivastava
Saurabh Shrivastava

Reputation: 1484

How to change popup label in kivy

My application appends a variable score by one on each click. I want to display a popup after each click to show score.

My attempt:

#!/usr/bin/kivy
import kivy
kivy.require('1.7.2')

from random import random
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from random import random
from random import choice
from kivy.properties import StringProperty
import time

score=0

my_popup = Popup(title='Test popup',
    content=Label(text=str(score)),
    size_hint=(None, None))


Builder.load_string("""
<Highest>:
    GridLayout:
        cols: 1
        Button:
            id: btn_0
            text: "0"
            on_press: root.new()
        Label:
""")

class Highest(Screen):
    def new(self):
        global score
        score=score+1
        self.ids['btn_0'].text = str(score)
        my_popup.open()


# Create the screen manager
sm = ScreenManager()
sm.add_widget(Highest(name='Highest'))

class TestApp(App):

    def build(self):
        return sm

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

However, score is always displayed as 0. Score is increasing correctly and can be seen on button text.

Upvotes: 0

Views: 751

Answers (1)

Yuri
Yuri

Reputation: 11

You would probably need to define my_popup as a function with score as argument:

def my_popup(updated_score):
    pop = Popup(title='Test popup', content=Label(text=str(updated_score)),
            size_hint=(None,None))
    pop.open()

Then call it at function "new" passing the updated score:

class Highest(Screen):
    def new(self):
        global score
        score += 1
        self.ids['btn_0'].text = str(score)
        my_popup(score)

Upvotes: 1

Related Questions