绝望的旋转器 on_text_changed 事件

Kivy spinner on_text_changed event

我想在 spinner 更改值时对事件做出反应并捕获该值。 这是最小的可重现示例:

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

class MyApp(App):
    def build(self):

        mainbox = BoxLayout(orientation="horizontal",
                            spacing=15,
                            padding=5)
        self.spinner_languages = Spinner(text ="", 
                values =("Python", "Java", "C++", "C", "C#", "PHP"), 
                size_hint = (0.3, 0.2)
                # on_text_changed = self.spinner_text_changed
                )
        mainbox.add_widget(self.spinner_languages)

        return mainbox

    #def spinner_text_changed(self, text):
    #    self.language = text
    #    print(self.language)

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

注释行是我要修复的内容。

你只需要在text 属性变化时使用bind触发spinner_text_changed()方法,像这样:

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

class MyApp(App):
    def build(self):

        mainbox = BoxLayout(orientation="horizontal",
                            spacing=15,
                            padding=5)
        self.spinner_languages = Spinner(text ="",
                values =("Python", "Java", "C++", "C", "C#", "PHP"),
                size_hint = (0.3, 0.2)
                )
        self.spinner_languages.bind(text=self.spinner_text_changed)
        mainbox.add_widget(self.spinner_languages)

        return mainbox

    def spinner_text_changed(self, spinner, text):
       self.language = text
       print(self.language)

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