python-3.x kivy每个if语句加1

5n0oy7gb  于 2023-01-22  发布在  Python
关注(0)|答案(1)|浏览(145)

每次我按下plus_btn数字应该增加1,但它只增加了一次
我尝试使用全局变量并将函数放在类之外,但没有成功

import bidi.algorithm
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button

class RootWidget(App):
    def build(self):
        inside = FloatLayout()
        label1 = Label(text='hi', font_name='fnnt',pos_hint ={'x':.15, 'y':.15})
        def plus(instance):
            num = 0
            if label1.text == 'hi' and num <= 7:
                num += 1
                print(num)
        plus_btn = Button(text='+', on_press=plus)
        inside.add_widget(plus_btn)
        inside.add_widget(label1)
        return inside


if __name__ == '__main__':
    RootWidget().run()
hc2pp10m

hc2pp10m1#

plus()方法中的num变量是该方法的局部变量,每次执行该方法时,您都要将其重置为0。您可以通过多种方式更正此问题,但一种简单的方法是在RootWidget类中声明一个num变量,如下所示:

class RootWidget(App):
    def build(self):
        self.num = 0
        inside = FloatLayout()
        label1 = Label(text='hi',pos_hint ={'x':.15, 'y':.15})
        def plus(instance):
            # num = 0
            if label1.text == 'hi' and self.num <= 7:
                self.num += 1
                print(self.num)
        plus_btn = Button(text='+', on_press=plus)
        inside.add_widget(plus_btn)
        inside.add_widget(label1)
        return inside

相关问题