如何在 kivy 中存储我们点击另一个 class 的按钮 ID

How to store the button id on which we clicked for another class in kivy

我想用我在screen1上点击的按钮的id在screen2上打开一些与之相关的内容。假设我创建了 5 个不同名称的按钮。如果我单击按钮 1,它应该打开与按钮 1 相关的内容,反之亦然。

这是我的主要 .py 文件的代码:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen,ScreenManager


class MainWindow(Screen):
    def category(self):
        carsquiz=self.ids  #it should contain that button id which was clicked
        self.manager.current='quizgo'

class QuizWindow(MainWindow,Screen):
    def something(self):
        # i want to access that button id in this screen
        pass

class WindowManager(ScreenManager):
    pass

class StandAlone(App):
    def build(self):
        return Builder.load_file('StandAloneQuiz.kv')

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

这是我的 .kv 文件的代码:

#:kivy 2.1.0
WindowManager:
    MainWindow:
    QuizWindow:

<MainWindow>:
    name:"index"
    BoxLayout:
        orientation:'vertical'
        Label:
            text:'Choose your category...'
            font_size:25
        Button:
            text:'category 1'
            id:category1
            on_press:
                root.category()
                root.manager.transition.direction='left'

        Button:
            text:'category 2'
            id:category2
            on_release:
                root.category()
                root.manager.transition.direction='left'
        Button:
            text:'category 3'
            id:category3
            on_release:
                root.category()
                root.manager.transition.direction='left'
        Button:
            text:'category 4'
            id:category4
            on_release:
                root.category()
                root.manager.transition.direction='left'
        Button:
            text:'category 5'
            id:category5
            on_release:
                root.category()
                root.manager.transition.direction='left'

<QuizWindow>:
    name:"quizgo"
    Button:
        text:'go Back'
        on_release:
            root.something()
            app.root.current="index"
            root.manager.transition.direction='right'

如果将 self 添加到 kv 中的 self.category()

    Button:
        text:'category 5'
        id: category5
        on_release:
            root.category(self)  # pass the Button instance to the method
            root.manager.transition.direction='left'

当然,必须对所有 Buttons 进行此更改。

修改python代码以使用它:

class MainWindow(Screen):
    def category(self, butt_instance):
        the_id = None
        for butt_id, button in self.ids.items():
            if button == butt_instance:
                the_id = butt_id
                break
        quizgo = self.manager.get_screen('quizgo')
        quizgo.the_butt_id = the_id
        self.manager.current='quizgo'

class QuizWindow(Screen):
    the_butt_id: ''

    def something(self):
        print('in something the id is', self.the_butt_id)