如何将按钮绑定到在 for 循环中创建的屏幕?

How to bind buttons to screens that was created in a for loop?

我想创建一组按钮来控制在同一个 for loop 中创建的 current 屏幕。

我的 .py 文件

class Profiles(Screen):
    #create button and screens based on items in acc_abr 
    def create_butt(self):
        for i in acc_abr:
            self.ids.sm.add_widget(Screen(name = i))
            self.ids.pro.add_widget(Button(text=i, id=i, on_press = self.switching_function(screename=i)))

    #set current screen
    def switching_function(self, screename):
        self.ids.sm.current = screename

我的 .kv 文件

<Profiles>:
    name: "prof"
    on_enter: self.create_butt()
    BoxLayout:
        orientation: "vertical"
        GridLayout:
            rows:1
            id: pro
            size_hint_y: .16
        BoxLayout:
            AccManagement:
                id: sm

create_butt 功能下,我为 acc_abr 中的每个项目添加了一个屏幕和按钮(到适当的位置)。

问题是,当我尝试将 on_press 绑定到 switching_function 时。出于某种原因,当我 运行 kivy 应用程序并调用 Profile 时,我得到 AssertionError: None is not callable

  1. 为什么这是一个有效的错误?
  2. 如何在 for 循环中正确地将按钮绑定到屏幕?
  3. 在 .kv 文件中,带有 on_press 命令的按钮在屏幕管理器 (sm) 中更改当前屏幕看起来像这样: on_press: sm.current = "screen1" 所以我的最后一个问题是,这将如何写入 python 文件?不起作用,但是 Button(on_press=(self.ids.sm.current=i) ???

要在 .py 文件中使用 on_press 并传递参数,您需要使用 lambda 函数或 functools.partial.

from functools import partial
...
something.add_widget(Button(on_press = partial(self.switching_function, i))
...

这是因为 on_press 只需要函数的 name 调用(注意在 on_press 回调中调用函数时没有括号).