Popup中的Kivy Button在调用方法时无法传递变量

时间:2017-10-31 13:03:54

标签: python kivy

这是一个弹出窗口:

class TestScreen (Screen)
    def openpopup(self)
        popup = Popup()
        button = Button(on_press=self.method("1"))
        popup.add_widget(button)
        popup.open()

     def method(self, number)
        self.label.text = number

当弹出窗口被调用时(通过一个按钮),它会给我一个错误:" AssertionError: None is not callable ",它只有在我从("1")移除self.method时才有效。但是我想从弹出窗口中传递一个变量,所以我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

试试这个解决方案:

class TestScreen (Screen)
    def openpopup(self)
        popup = Popup()
        self.button = Button(on_press=self.method, text='1')
        popup.add_widget(button)
        popup.open()

    def method(self)
        self.label.text = self.button.text

答案 1 :(得分:1)

建议使用以下之一。有关详细信息,请参阅示例。

片段

Lambda函数

LocationGroup

部分功能

button = Button(text="Update Label's text", on_press=lambda number: self.method(number=1))

示例 - 使用Lambda函数

main.py

from functools import partial
...
button = Button(text="Update Label's text", on_press=partial(self.method, number=1))
...
    def method(self, *args, number):

test.kv

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty


class ScreenManagement(ScreenManager):
    pass


class TestScreen(Screen):
    label = ObjectProperty(None)

    def openpopup(self):
        content = BoxLayout(orientation="vertical")
        self.popup = Popup(title="Popup", size_hint=(None, None),
                           size=(400, 400), auto_dismiss=False, content=content)
        button = Button(text="Update Label's text", on_press=lambda x: self.method(x=1))
        close_btn = Button(text="Close", on_press=self.popup.dismiss)
        content.add_widget(button)
        content.add_widget(close_btn)
        self.popup.open()

    def method(self, number):
        self.label.text = str(number)


class TestApp(App):
    title = "Kivy Passing Arguments to Method - Using Lambda"

    def build(self):
        return ScreenManagement()


if __name__ == "__main__":
    TestApp().run()

输出 - 使用Lambda函数

enter image description here enter image description here enter image description here

示例 - 使用部分功能

main.py

#:kivy 1.10.0

<ScreenManagement>:
    TestScreen:
        name: "testscreen"

<TestScreen>:
    label: label
    BoxLayout:
        orientation: "vertical"
        Button:
            size_hint: 1, 0.2
            text: "Show Popup"
            on_release: root.openpopup()
        Label:
            id: label
            text: "Test Screen"

输出 - 使用部分功能

enter image description here enter image description here enter image description here