Kivy - 标签没有在UI上更新

时间:2016-02-20 05:23:16

标签: python kivy

当我点击左侧部分的按钮时,应该使用我点击的按钮文本更改标签“2015年十大剧本”。我可以看到变量更改文本,但标签没有更改文本。

这是我的工作:当我点击左侧的按钮时,中间的标题应该改变: screen shot

python

class MainApp(Screen, EventDispatcher):
    vid = StringProperty("Videos/Top 10 Plays of 2015.mp4")
    title = StringProperty("Top 10 Plays of 2015")

    def __init__(self,*args,**kwargs):
        super(MainApp,self).__init__(*args, **kwargs)
    pass

class OtherVideos(BoxLayout, EventDispatcher):
    root = MainApp
    def __init__(self, *args, **kwargs):
        super(OtherVideos,self).__init__(*args, **kwargs)
        self.loadVideos()

    def loadVideos(self):
        con = MongoClient()
        db = con.nba
        vids = db.videos.find()

        vidnum = 1
        for filename in vids:
            myid = "vid" + str(vidnum)
            getfilename = filename['filename']

            button = Button(id=myid,
                          text=getfilename,
                          color=[0,0.7,1],
                          bold=1)

            button.bind(on_release=lambda x:(self.change_Title(getfilename), self.change_Vid(getfilename)))
            self.add_widget(button)
            vidnum += 1

    def change_Title(self, title):
        self.root.title = title

    def change_Vid(self, myfilename):
        con = MongoClient()
        db = con.nba
        vids = db.videos.find()

        for filename in vids:
            file = os.path.basename(filename['video_path'])
            if myfilename == filename['filename']:
                self.root.vid = filename['video_path']
                break
    pass

kivy

BoxLayout:
            orientation: 'vertical'
            Label:
                id: lblTitle
                text: root.title
                size_hint_y: None
                height: 40
                font_size: 25
                bold: 1
                canvas.before:
                    Color:
                        rgba: 1, 0, 0, 0.7
                    Rectangle:
                        pos: self.pos
                        size: self.size
            VideoPlayer:
                id: activeVid
                source: root.vid
                state: 'play'

当我打印root.title时,它正在更改其文本,但标签没有改变它应该更改它应该是因为它从该变量获取其文本。

但是当我将change_title()方法放在__init__ OtherVideos这样的时候,标签正在改变:

class OtherVideos(BoxLayout, EventDispatcher):
    root = MainApp
    def __init__(self, *args, **kwargs):
        super(OtherVideos,self).__init__(*args, **kwargs)
        self.change_Title("my title")

这已经花了我几天的工作,任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您的代码存在一些问题:

  1. 每个小部件都继承自EventDispatcher,因此第二次继承它是毫无意义的。
  2. root = MainApp不是对MainApp(对象)的引用,而是对其类的引用。
  3. 您无需指定StringProperty来实现目标。
  4. 最简单的方法是在函数change_Title中添加要更改的标签的引用:

    def change_Title(self, title):
        # self.root.title = title
        self.ids.my_label_to_change.text = title