获取一个kivy应用程序来更新可见界面(没有小部件)

时间:2017-10-09 18:18:06

标签: python kivy

我使用的是kivy,无法让kivy界面更新。

我基于current_node的布局,这是一个填写其他变量的字典条目。理想情况下,布局应取决于当前节点。

当我运行应用程序时,current_node及其所有子变量在MyApp类中更新,在python代码中 - 但不在kivy接口上。有什么想法吗?

我尝试过的东西没有用过:

  • 为布局创建单独的类(无法动态更改按钮数)
  • update_node函数更改为包含MyApp.build()(缺少位置参数self)

提前感谢任何建议。

tree = {
    '0' : ['Hi!', 'A', 'B'],
    'A' : ['Yes', 'AA', 'AB','AC'],
    'AA': ['Seneca', 'AAA', 'AAB'],
    'AAA': ['Yes', 'AAA', 'AAB'],
    'AAB': ['No', 'AAA', 'AAB'],
    'AB' : ['Cato', "AA", "AB"],
    'AC' : ['Neither'],
    'B' : ["No",'BA','BB'],
    'BA': ['xx'],
    'BB': ['xxx']
}

class MyApp(App):
    current_node = '0'

    def update_node(self, *args):
        self.current_node = args[0]
        self.build()

    def build(self):
        layout = FloatLayout()
        child_nodes = tree[self.current_node][1:]
        j = len(child_nodes)
        # Answer Buttons
        for i in child_nodes:
            answer_button = Button(
                    text=tree[i][0],
                    pos=(100, j*75),
                    size_hint = (0.8, 0.1),
                    )
            button_callback = partial(self.update_node, i)
            answer_button.bind(on_release=button_callback)
            layout.add_widget(answer_button)
            j -= 1
            print(i)
        return layout

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

1 个答案:

答案 0 :(得分:0)

def update_node(self, *args):
    self.current_node = args[0]
    self.build()

self.build() - is App自身调用以获取根小部件的方法。你不应该手动调用它,你不能用它重新创建它。

您应该改变根小部件的子节点:

from functools import partial

from kivy.app import App

from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout


tree = {
    '0':   ['Hi!', 'A', 'B'],
    'A':   ['Yes', 'AA', 'AB','AC'],
    'AA':  ['Seneca', 'AAA', 'AAB'],
    'AAA': ['Yes', 'AAA', 'AAB'],
    'AAB': ['No', 'AAA', 'AAB'],
    'AB':  ['Cato', "AA", "AB"],
    'AC':  ['Neither'],
    'B':   ["No",'BA','BB'],
    'BA':  ['xx'],
    'BB':  ['xxx']
}


class RootWidget(FloatLayout):
    current_node = '0'

    def __init__(self, **kwargs):
        super(FloatLayout, self).__init__(**kwargs)
        self._rebuild()

    def update_node(self, i, *args):
        self.current_node = i
        self._rebuild()

    def _rebuild(self, *args):
        self.clear_widgets()  # clear current buttons

        child_nodes = tree[self.current_node][1:]
        j = len(child_nodes)
        # Answer Buttons
        for i in child_nodes:
            answer_button = Button(
                pos=(100, j*75),
                size_hint=(0.8, 0.1),
                text=tree[i][0],
            )
            answer_button.bind(
                on_release=partial(self.update_node, i)
            )
            j -= 1
            print(i)
            self.add_widget(answer_button)


class MyApp(App):
    def build(self):
        return RootWidget()


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