Popup中的Kivy Button没有调用函数

时间:2017-10-26 07:28:19

标签: python kivy

以下是有问题的代码:

Class Screen1(Screen):
    def win(self):
        if win == True:
             Self.open_popup()

    def open_popup(self):
        content = BoxLayout()
        button = Button(text="restart", on_press=self.retry(), 
        on_release=self.dismiss() )
        content.add_widget(button)
        self.popup = Popup(title="Popup", content=content)

    def retry(self):
        #resets game

它给出了错误“none is not callable”和“Screen1没有属性被忽略”我做错了什么?

此外,我不得不像这样调用弹出窗口而不是.kv文件,因为由于某种原因,它不适用于屏幕管理器

2 个答案:

答案 0 :(得分:2)

1)

on_press=self.retry()

您在此处调用self.retry函数并将其结果作为on_press传递。你应该自己传递函数:

on_press=self.retry

2)

self.dismiss()

您正尝试在self.dismiss对象上调用函数Screen。屏幕没有此方法,Popup可以。你可能想要这样的东西:

content = BoxLayout()
self.popup = Popup(
    title="Popup", 
    content=content
)
button = Button(
    text="restart",
    on_press=self.retry,
    on_release=self.popup.dismiss
)
content.add_widget(button)

答案 1 :(得分:2)

问题它给了我错误"没有人无法调用"和" Screen1没有属性消除"我做错了什么?

回答 Popup具有可绑定的功能,例如open和dismiss。

问题此外,我不得不像这样调用弹出窗口,而不是.kv文件,因为出于某种原因,它不能与屏幕管理器一起使用

回答您可以创建一个Popup窗口小部件类,并定义kv文件中的所有窗口小部件。有关详细信息,请参阅以下示例。

实施例

main.py

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import BooleanProperty
from kivy.uix.popup import Popup


class MessageBox(Popup):
    def __init__(self, obj, **kwargs):
        super(MessageBox, self).__init__(**kwargs)
        self.obj = obj


class Screen1(Screen):
    win = BooleanProperty(True)

    def __init__(self, **kwargs):
        super(Screen1, self).__init__(**kwargs)
        self.name = "screen1"
        self.display_winner()

    def display_winner(self):
        if self.win:
            popup = MessageBox(self)    # pass screen1 object
            popup.open()

    def retry(self):
        print("Reset Game")


class ScreenManagement(ScreenManager):
    pass


class TestApp(App):
    title = "Kivy Screen Manager & Popup Demo"

    def build(self):
        return ScreenManagement()


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

test.kv

#:kivy 1.10.0

<MessageBox>:
    title: "Popup"
    size_hint: None, None
    size: 400, 400
    auto_dismiss: False

    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Player 1 is the winner!"
        Button:
            size_hint: 1, 0.2
            text: "restart"
            on_press: root.obj.retry()
            on_release: root.dismiss()

<ScreenManagement>:
    Screen1:

<Screen1>:
    name: "screen1"

输出

enter image description here enter image description here