【问题标题】:How to bind buttons to screens that was created in a for loop?如何将按钮绑定到在 for 循环中创建的屏幕?
【发布时间】:2019-02-23 02:26:49
【问题描述】:

我想创建一组按钮来控制在同一个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) ???

【问题讨论】:

  • 什么是AccManagement
  • @eyllanesc 它是一个 ScreenManager

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


【解决方案1】:

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

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

这是因为on_press 只希望调用函数的名称(注意在 on_press 回调中调用函数时没有括号)。

【讨论】:

    猜你喜欢
    • 2020-10-06
    • 2016-09-27
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多