簡體   English   中英

Kivy 從另一個 class 調用 SELF 方法

[英]Kivy call SELF method from another class

In this very simple kivy python program I try to change text label from Window2 class using method in Window1 class. 當我在 Window2 中調用 Window1 方法時,方法已啟動,但 self.ids.... 行未完成。

知道必須更改什么才能使self.ids.label1.text = "DONE"工作嗎?

python 文件

from kivy.uix.boxlayout import BoxLayout


class ParentWindow(BoxLayout):
    pass


class Window1(BoxLayout):

    def update(self):
        print("This print works, but next line not ...")
        self.ids.label1.text = "DONE"


class Window2(BoxLayout):

    def try_change(self):
        Window1().update()


class MyProgramApp(App):
    def build(self):
        return ParentWindow()


MyProgramApp().run()

kivy 文件

<ParentWindow>:
    Window1:
    Window2:

<Window1>:
    orientation: "vertical"
    Label:
        id: label1
        text: "Try to change me"
    Button:
        text: "Works fine from self class"
        on_press: root.update()

<Window2>:
    Button:
        text: "Lets try"
        on_press: root.try_change()

每當您的代碼中有一個 class 名稱后跟()時,您就是在創建該 class 的新實例。 因此try_change()方法中的Window1().update()正在創建Window1的新實例(與 GUI 中的實例無關),並在該新實例上調用update() 這不會影響您在 GUI 中看到的內容。

您需要訪問實際在您的 GUI 中的Window1的實例。 為此,您可以將try_change()更改為:

def try_change(self):
    # Window1().update()
    window1 = App.get_running_app().root.ids.window1
    window1.update()

除了在您的kv中添加window1 id 之外:

<ParentWindow>:
    Window1:
        id: window1
    Window2:

我找到了解決方案:

.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout


class ParentWindow(BoxLayout):
    pass


class Window1(BoxLayout):

    def update(self):
        print("This print work, but next line not ...")
        self.ids.label1.text = "DONE"


class Window2(BoxLayout):

    def try_change(self):
        self.parent.ids.win1.update()


class MyProgramApp(App):
    def build(self):
        return ParentWindow()


MyProgramApp().run()

.kv

<ParentWindow>:
    Window1:
        id: win1
    Window2:


<Window1>:
    orientation: "vertical"
    Label:
        id: label1
        text: "Try to change me"
    Button:
        text: "Works fine from self class"
        on_press: root.update()

<Window2>:
    Button:
        text: "Lets try"
        on_press: root.try_change()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM