【问题标题】:Kivy dynamic widget issueKivy 动态小部件问题
【发布时间】:2015-04-04 01:21:16
【问题描述】:

好吧,我是使用 kivy 框架的初学者,所以我认为这里有人可以帮助我。 我的问题是: 在我的应用程序中,用户输入一个数字 n,然后应用程序返回 n 个 TextInput 小部件。但是我怎样才能使用每个 TextInput 上插入的值呢?第一部分很容易做到,我是通过列表完成的。 (如果有人知道如何直接在 kv 文件上执行此操作,我将不胜感激)。我的问题在第二部分,我需要稍后使用和操作这些值(在 TextInputs 中),但我无法接触到它们。我的意思是,我为列表中的每个小部件设置了一个 id,但我无法访问它们的 .text 属性。这是我的一段代码:

class FirstLayout(BoxLayout):

   def next_layout(self):  
   self.clear_widgets()  
   secondLayout = Factory.SecondLayout()  
   number = NumericProperty()  
# This 'number' variable came from another widget on kv file

   textinput_list = []
# That list will receive as many TextInputs field as my variable 'number' said (by the loop for)

   for i in range(int(self.number.text)):
        textinput_list.append(TextInput())
        textinput_list[i].id = "input" + str(i + 1)
    # So for each textinput, i added a id named 'inputx' (where x is the number of the current
    # iteration) my question resides here. How could i use those values (inside of each textinput 
    # on this list
    # later? Because i'm not creating these widgets (TextInputs) on kv language so i don't know how to
    # bind the ids for a new variable directly in .py file
        secondLayout.container.add_widget(textinput_list[i]) 

    self.add_widget(secondLayout)

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    如果我正确理解您的问题,您只需将 textinput_list 设为类变量。所以这个。

    textinput_list = []
    

    变成

    self.textinput_list = []
    

    假设您首先调用了一个 FirstLayout 对象。使用first.textinput_list[0],您可以访问第一个文本输入等。

    如果您想通过 id 轻松访问文本输入,我建议您使用字典,键是 id,值是输入。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    相关资源
    最近更新 更多