dimanche 3 mai 2015

How to reset widget in Kivy

I have a very simple application having one button and one label. Label have value 0 initially. On each button press, label increase by 1. When label becomes 3, i show a popup with a "play again" button.

Now, i want to reset label to 0.

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.boxlayout import BoxLayout
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
from kivy.clock import Clock

s=0

def my_callback(dt):
    mypopup = MyPopup()
    return mypopup.show_popup()

def go_to_main(self):
    sm.current = 'menu'
    global s
    s=0

def test(self):
    global s
    s=0
    print s

class MyPopup(Popup): 
    def show_popup(self):
        mytext= str(s)
        content = BoxLayout(orientation="vertical")
        content.add_widget(Label(text="Game Over", font_size=20))
        content.add_widget(Label(text="Score", font_size=20))
        content.add_widget(Label(text=mytext, font_size=20))
        mybutton_cancel = Button(text="Play Again", size_hint_y=None, height=40)
        content.add_widget(mybutton_cancel)
        mypopup = Popup(content = content,              
            title = "oops",     
            auto_dismiss = False,         
            size_hint = (.5, .5))
        mybutton_cancel.bind(on_release=mypopup.dismiss)
        mybutton_cancel.bind(on_release=test) 
        mypopup.open()

Builder.load_string("""
<MenuScreen>:
    GridLayout:
        cols: 1
        Button:
            id: btn_0
            text: "press me to increase score"
            on_press: root.val0()
        Label:
            id: score
            text:root.get_score()
""")

class MenuScreen(Screen):
    def get_score(self):
        return str(s)
    #on_click of button code
    def val0(self):
        global s
        s=s+1
        self.ids['score'].text=str(s)
        if(s==3):
            Clock.schedule_once(my_callback, 0)

sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))

class TestApp(App):

    def build(self):
        return sm

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

It resets to 0 successfully, i printed it on console to check, but still display as 3. On button press, changes to 1. I want to show it as 0 instead of 3.

Aucun commentaire:

Enregistrer un commentaire