我想把分数设置为10,当一个按钮被点击,但它不工作。 当单击第一个按钮时,得分应从0增加到10,当使用kivy按下第二个按钮时,得分应从10增加到20
import kivy
from kivy.app import App
from kivy.uix.floatlayout import Floatlayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.label import Label
class LandingScreen(FloatLayout):
def __init__(self, **kwargs):
super(LandingScreen, self).__init__(**kwargs)
self.score=0
# put whatever pos_hint value you want.
self.add_widget(Label(text='SCORE: ' + str(score), size_hint=(0.5, 0.5)))
self.btn1=Button(text='button1 ', size_hint=(0.5, 0.5),
on_press=self.click_b1))
self.btn2=Button(text='button2', size_hint=(0.5, 0.5),
on_press=self.click_b2))
self.add_widget(self.btn1)
self.add_widget(self.btn2)
def click_b1(self, instance):
score +=10
def click_b2(self, instance):
score += 10
class SplashApp(App):
def build(self):
return LandingScreen()
if __name__ == '__main__':
SplashApp().run()
在Click_B1
和Click_B2
中,您丢失了自我。
访问Score
时。
使用self访问实例变量:
def click_b1(self, instance):
self.score +=10
def click_b2(self, instance):
self.score += 10
当您执行str(score)
时,也会遇到同样的问题,它应该是str(self.score)