【问题标题】:kivyMD get ID of each button in a List ItemskivyMD 获取列表项中每个按钮的 ID
【发布时间】:2021-10-17 13:20:50
【问题描述】:

我正在使用 kivyMD 创建博客。

我用 ListItemWithCheckbox(或 OneLineListItem)显示我的帖子列表(这里没问题)。

现在我想获取用我的 boucle 创建的每个按钮的 id。

我分享下面的代码:

def show_records(self):
    
    connexion = config.connexion
    icons = list(md_icons.keys())
    
    try:  
        with connexion.cursor() as cursor: 

            sql = "SELECT ID, post_title, post_name, post_date FROM mod803_posts WHERE post_type='stock' AND post_status='publish' ORDER BY post_date DESC" 

            cursor.execute(sql) 
            for line in cursor:

                self.block_layout = ListItemWithCheckbox(text=f'{line}')
                
                self.strng.get_screen('accueilscreen').ids.scroll.add_widget(self.block_layout)
                self.block_layout.ids.text = str(line['post_name']).replace('-','')
                #print(self.block_layout)

    finally:     
        connexion.commit()


def get_id(self):
    print(self.block_layout.ids.text) HERE (It always prints the last post id)


def voir_unique(self):

    self.strng.get_screen('accueilscreen').ids.scr.current = 'stock'
    self.strng.get_screen('accueilscreen').ids.scr.transition.direction = 'left'
    

KV代码:

#The screen where the list of posts are created in the function show_records()
MDScreen:
    name: 'biens'

    ScrollView:
        MDList:
            id: scroll
    

和我的按钮的kv代码:

<ListItemWithCheckbox>:
    id: mesboxes
    on_press:
        app.voir_unique()
        app.get_id()

    IconLeftWidget:
        icon: root.icon

    RightCheckbox:

当我点击列表中的一篇文章时,屏幕会向左转至“库存”。 我想获取点击的帖子的 ID(或按钮),以显示我点击的帖子的所有值...

我希望有人可以帮助我。 谢谢 罗曼

【问题讨论】:

    标签: python-3.x kivy kivy-language kivymd


    【解决方案1】:

    您可以使用 MDList 小部件的子列表。

    for child in self.ids.scroll.children:
        print(f'{child}')
    

    【讨论】:

      【解决方案2】:

      我找到了解决问题的方法:

      for self.line in cursor:
      
          ID = self.line['ID']
                      
          title = self.line['post_title']
                  
      
          #i = NewApp()
          #j = i.stock_unique(ID, title)
      
          # here I SOLVED THE PROBLEM, so when I click on each OnlineListItem, I get the current ID 
      
          self.block_layout = OneLineListItem(text=f'{ID, title}', on_press=(lambda ID=ID: lambda x: print(ID))())
      
          self.strng.get_screen('accueilscreen').ids.scroll.add_widget(self.block_layout)
                      
                      print(ID, title)
      

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 2022-01-22
      相关资源
      最近更新 更多