如何在python中访问类中的全局变量

时间:2018-01-20 18:09:49

标签: python-3.x kivy

我正在尝试访问索引变量。当我按下播放按钮时,会打印索引但按下上一个和下一个按钮时出现以下错误:

  

UnboundLocalError:局部变量' index'在转让前引用。

如何在类中使用全局变量?

示例代码:

from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class KivyGalleryApp(App):
    def build(self):
        class Musicscreens(Screen):
            def __init__(self, **kwargs):
                super(Musicscreens, self).__init__(**kwargs)
                index=0
                def Previous(self):
                    #global index
                    index=index-1
                    print (index)
                def play(self):
                    #global index
                    print (index)
                def next_index(self):
                    #global index
                    index=index+1
                    print (index)
                box1=BoxLayout()
                prev_button=Button(text='Previous')
                prev_button.bind(on_press=Previous)    
                play_button=Button(text='play')
                play_button.bind(on_press=play)
                next_button=Button(text='next')
                next_button.bind(on_press=next_index)  
                box1.add_widget(prev_button)
                box1.add_widget(play_button)
                box1.add_widget(next_button)
                self.add_widget(box1)

        sm=ScreenManager()
        sm.add_widget(Musicscreens(name='sample'))
        return sm

KivyGalleryApp().run()

1 个答案:

答案 0 :(得分:0)

您正在使用面向对象的编程,您可以简单地使index成为实例属性,并且每个回调都是实例方法:

from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button


class Musicscreens(Screen):
    def __init__(self, **kwargs):
        super(Musicscreens, self).__init__(**kwargs)
        self.index = 0

        prev_button = Button(text='Previous')
        prev_button.bind(on_press=self.previous)

        play_button = Button(text='play')
        play_button.bind(on_press=self.play)

        next_button = Button(text='next')
        next_button.bind(on_press=self.next_index)

        box1 = BoxLayout()
        box1.add_widget(prev_button)
        box1.add_widget(play_button)
        box1.add_widget(next_button)

        self.add_widget(box1)

    def previous(self, instance):
        self.index -= 1
        print(self.index)

    def play(self, instance):
        print(self.index)

    def next_index(self, instance):
        self.index += 1
        print(self.index)


class KivyGalleryApp(App):
    def build(self):
        sm = ScreenManager()
        sm.add_widget(Musicscreens(name='sample'))
        return sm

if __name__ == "__main__":
    KivyGalleryApp().run()