【问题标题】:Calling Function in a Different Class Through Kivy Button通过 Kivy 按钮调用不同类中的函数
【发布时间】:2017-07-11 01:54:55
【问题描述】:

我正在尝试在 kivy 中调用按钮按下时的函数,该函数位于与按钮所在的不同的类屏幕中。我也尝试在应用程序类中运行该函数并在那里遇到问题。这是我试图调用的函数所在的类:

# Main screen with button layout
class LandingScreen(Screen):
    def __init__(self, **kwargs):
        super(LandingScreen, self).__init__(**kwargs)
        self.buttons = [] # add references to all buttons here
        Clock.schedule_once(self._finish_init)

    def ChangePic(self):
        self.buttons[1].background_normal = 'folder.png'

这是我试图调用它的按钮:

<InputScreen@Screen>:
    name: 'input_sc'
    FloatLayout:
        size: 800, 480
        id: anchor_1
        Label: 
            text: "What would you like to bind to this button?"
            size_hint: (1,.15)
            text_size: self.size
            pos_hint: {'x': 0.11, 'top': 1}
            font_size: 28
            font_name: 'Montserrat-Bold.ttf'
        Button:
            root: 'landing_sc'
            id: filebutton
            size: 150, 150
            size_hint: None, None
            background_normal: 'folder.png'
            background_down: 'opacity.png'
            pos_hint: {'x': 0.11, 'top': .7}
            on_release: 
                root.manager.transition = FadeTransition()
                root.manager.transition.duration = 1.5
                app.MakeFolder()
                root.IfFolder()
                root.ChangeToSlide()

我必须在 ChangePic() 前面加上什么前缀才能从这个位置调用它?

或者,有没有一种方法可以从 InputScreen 类内部轻松使用 LandingScreen 类内部的按钮?

谢谢!

【问题讨论】:

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


    【解决方案1】:

    你可以在你的 App Class 中创建一个变量:

    some_variable = LandingScreen()
    

    然后在您的按钮中调用 ChangePic(),如下所示:

    on_release: app.some_variable.ChangePic()
    

    另外,这可以帮助您:StackOverflowKivy's Google GroupIntroduction to properties

    【讨论】:

    • 这个变量是否需要在方法内部创建?如果我不把它放在一个里面,我会得到一个错误,如果我把它放在一个里面,app.variable 就找不到它?
    • 引用 LandingScreen() 的变量需要在您的 App 类中创建:class AppClass: some_variable = LandingScreen() def MakeFolder(self): #your code here 所以,some_variables 具有 LandingScreen() 的方法。您可以在 AppClass() 中使用“some_variable”调用 LandingScreen() 的任何方法,只需执行 some_variable.ChangePic() 但是,您想从您的 kv 调用 ChangePic(),因此您需要将 app.some_variable.ChangePic()与您在 kv 中使用 app.MakeFolder() 所做的相同,但是使用 ChangePic() 您需要使用 some_variable
    猜你喜欢
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2020-07-29
    相关资源
    最近更新 更多