通过 Kivy 按钮调用不同类中的函数

Calling Function in a Different Class Through Kivy Button(通过 Kivy 按钮调用不同类中的函数)

本文介绍了通过 Kivy 按钮调用不同类中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to call a function on button press in kivy, that is located in a different class screen than the button is located in. I tried running the function in the app class as well and ran into issues there. Here is the class where the function I am trying to call lies:

# 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'

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

And here is the button that I am trying to call it with:

<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() 前面加上什么前缀才能从这个位置调用它?

What do I have to prefix ChangePic() with in order to call it from this location?

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

Alternatively- is there a way to easily work with the buttons inside of the LandingScreen class from inside of the InputScreen class?

谢谢!

推荐答案

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

You can create a variable in your App Class:

some_variable = LandingScreen()

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

and then in your button call ChangePic() like this:

on_release: app.some_variable.ChangePic()

此外,这可以帮助您:StackOverflow, Kivy 的 Google 群组,属性简介

Also, this can help you: StackOverflow, Kivy's Google Group, Introduction to properties

这篇关于通过 Kivy 按钮调用不同类中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:通过 Kivy 按钮调用不同类中的函数

基础教程推荐