为什么我的kivy程序没有从另一个类调用该函数?

时间:2020-04-10 05:03:28

标签: python-3.x function class button kivy

我认为这更多是一个python问题,然后是一个kivy问题。

class Keyboard正在共享来自类GUI的方法。我创建了一个名为“ self.a”的GUI实例,以连接Keyboard类中的2个类。另外,我还创建了一个键盘类实例“ MainApp类中的self.key。

当我使用此方法时,“打印(按下“返回按钮”))“返回”按钮能够执行打印语句。我知道它为什么有效。当我在方法中使用“ self.a.up()”时,返回按钮不会从类GUI调用up()方法。这可能是一个小细节或我所缺少的概念。程序的其余部分没有错误。请帮助并提前致谢。

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.lang.builder import Builder
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.modules import keybinding
from kivy.core.window import Window


class GUI(BoxLayout):
    main_display = ObjectProperty()
    text_input = ObjectProperty()


    def plus_1(self):
        self.value = int(self.main_display.text)
        self.main_display.text = str(self.value + 1)
        print (self.main_display.text)

    def minus_1(self):
        self.value = int(self.main_display.text)
        self.main_display.text = str(self.value - 1)


    def up(self):
        self.main_display.text = self.text_input.text
        self.text_input.text = ''

class Keyboard(Widget):

    def __init__(self,):
        super().__init__()
        self.a = GUI()

        self.keyboard = Window.request_keyboard(None, self)
        self.keyboard.bind(on_key_down=self.on_keyboard_down)

    def on_keyboard_down(self, keyboard, keycode, text, modifiers):
        if keycode[1] == 'enter':
            self.a.up()
#           print ("Return button is pressed")
        return True

class MainApp(App):
    def build(self):
        key = Keyboard()
        return GUI()



if __name__=="__main__":
    app = MainApp()
    app.run()

1 个答案:

答案 0 :(得分:1)

我认为它可以正常工作,但是在另一个看不见的对象中。问题是您在屏幕上显示GUI类的一个对象。对于Keyboard类,您创建了另一个看不见的对象。因此,解决方案是使用GUI类的一个对象,并在MainAppKeyboard类中对其进行操作。像这样:

class MainApp(App):
    def build(self):
        # here we create an object...
        self.gui = GUI()
        # ...send it to Keyboard class
        key = Keyboard(self.gui)
        # and return it
        return self.gui

class Keyboard(Widget):

    def __init__(self, gui):
        super().__init__()
        # and here we receive that object instead of creating new one
        self.a = gui
相关问题