Как получить данные из текстовых полей, назначенных спискам MDL в KivyMD Python

#python #kivy #textfield #kivymd

Вопрос:


Я хочу получить пользовательский ввод из текстовых полей, назначенных MDList, и назначить список (переменную). Можно ли это сделать тем методом, которому я следовал.

Иначе

  1. Могу ли я добавить текстовое поле в прокручиваемое окно? Если это так, то будет намного проще
  2. Есть ли другой способ?

Код.кв

 screen_helper = """
    
    ScreenManager:
        NoS:
        Neutral:
        
    <NoS>:
        name: 'nos'
        MDLabel:
            text: 'Get Songs to your Studio'
            font_style: 'H3'
            halign: 'center'
            pos_hint: {'center_x':0.5,'center_y':0.75}
        MDTextField:
            id:nos
            pos_hint: {'center_x':0.5,'center_y':0.45}
            size_hint: (0.7,0.1)
            hint_text : 'Number of Songs you want to Get'
            helper_text: 'Required'
            helper_text_mode: 'on_focus'
            icon_right: 'account-music'
            mode : 'rectangle'
            icon_right_color: app.theme_cls.primary_light
            required : True
        MDRaisedButton:
            text: 'Back'
            pos_hint: {'center_x':0.1,'center_y':0.08}
            font_style: 'Button'
            ripple_rad_default : 40
            ripple_duration_out : 1
            md_bg_color: app.theme_cls.accent_dark
            on_press: 
                root.manager.current = 'settingup'
                root.manager.transition.direction = 'right'
        MDRaisedButton:
            text:"Next"
            pos_hint: {'center_x':0.9,'center_y':0.08}
            font_style: 'Button'
            ripple_rad_default : 40
            ripple_duration_out : 1
            md_bg_color: app.theme_cls.primary_dark
            on_press:
                root.manager.current = 'neutral'
                root.manager.transition.direction = 'left'     
                app.song_info()   
        MDProgressBar:
            value:60
            pos_hint:{'center_y' : 0.007}
            
    <Neutral>:
        name : 'neutral'
        MDBoxLayout:
            orientation: "vertical"
            MDToolbar:
                md_bg_color: 0,0,0,.000001
                specific_text_color: app.theme_cls.primary_light
                title: "Get Songs to your Neutral Album"
                left_action_items: [["arrow-left", lambda x: app.back_to_nos()]]   
            ScrollView:
                MDList:
                    id: neutral
                    padding : '80dp'
        MDBoxLayout:
            orientation: "vertical"
            adaptive_height: True
            height: '69dp'
            md_bg_color: .07,.07,.07,1
        MDRaisedButton:
            text : 'Next'
            pos_hint : {'center_x':0.9,'center_y':0.08}
            font_style: 'Button'
            ripple_rad_default : 40
            ripple_duration_out : 1
            md_bg_color: app.theme_cls.primary_dark
            on_press:
                root.manager.current = 'home'
                root.manager.transition.direction = 'left'
        MDRaisedButton:
            text: 'Back'
            id : reset_nos
            pos_hint: {'center_x':0.1,'center_y':0.08}
            font_style: 'Button'
            ripple_rad_default : 40
            ripple_duration_out : 1
            md_bg_color: app.theme_cls.accent_dark
            on_press: 
                root.manager.current = 'nos'
                root.manager.transition.direction = 'right'     
                
    """
 

Текстовые поля были назначены MDList при ScrollView использовании self.screen.get_screen('neutral').ids.neutral.add_widget(MDTextField())

Code.py

 from kivy.lang.builder import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from kivymd.app import MDApp
from kivy.core.window import Window
from kivymd.uix.textfield import MDTextField

Window.size = (900, 600)


class NoS(Screen):
    pass


class Neutral(Screen):
    pass

sm = ScreenManager()
sm.add_widget(NoS(name='nos'))
sm.add_widget(Neutral(name='neutral'))

class Mode(MDApp):
    def build(self):
        screen = Screen()
        self.screen = Builder.load_string(screen_helper)
        screen.add_widget(self.screen)

        self.theme_cls.primary_palette = "Blue"
        self.theme_cls.accent_palette = 'Red'  # 'Red' ,'Yellow'
        self.theme_cls.primary_hue = "A700"
        self.theme_cls.theme_style = "Dark"

        return screen

    def song_info(self):
        nos = int(self.screen.get_screen('nos').ids.nos.text)   1

        for i in range(1, nos):
            if i == 1:
                self.screen.get_screen('neutral').ids.neutral.add_widget(
                    MDTextField(
                        hint_text=f"Enter the "   str(i)   "st Song you want to Enjoy when you are in Neutral",
                        pos_hint={'center_x': 0.5, 'center_y': 0.45},
                        size_hint=(0.7, 0.1), icon_right='account-music',
                        mode='rectangle', icon_right_color=self.theme_cls.primary_light
                    )
                )
            elif i == 2:
                self.screen.get_screen('neutral').ids.neutral.add_widget(
                    MDTextField(hint_text=f"Enter the "   str(i)   "nd Song you want to Enjoy when you are in Neutral",
                                pos_hint={'center_x': 0.5, 'center_y': 0.45},
                                size_hint=(0.7, 0.1), icon_right='account-music',
                                mode='rectangle', icon_right_color=self.theme_cls.primary_light
                                )
                )
            elif i == 3:
                self.screen.get_screen('neutral').ids.neutral.add_widget(
                    MDTextField(hint_text=f"Enter the "   str(i)   "rd Song you want to Enjoy when you are in Neutral",
                                pos_hint={'center_x': 0.5, 'center_y': 0.45},
                                size_hint=(0.7, 0.1), icon_right='account-music',
                                mode='rectangle', icon_right_color=self.theme_cls.primary_light)
                )
            else:
                self.screen.get_screen('neutral').ids.neutral.add_widget(
                    MDTextField(hint_text=f"Enter the "   str(i)   "th Song you want to Enjoy when you are in Neutral",
                                pos_hint={'center_x': 0.5, 'center_y': 0.45},
                                size_hint=(0.7, 0.1), icon_right='account-music',
                                mode='rectangle', icon_right_color=self.theme_cls.primary_light)
                )
                
                
Mode().run()
 

Ответ №1:

Вы можете добавить этот метод в свой Mode класс:

 def get_songs(self):
    neutral = self.screen.get_screen('neutral').ids.neutral
    song_list = []
    for w in neutral.walk():
        if isinstance(w, MDTextField):
            song_list.append(w.text)
    print('songs:', song_list)
    return song_list
 

Затем просто вызовите этот метод, чтобы получить список песен.

Комментарии:

1. Я не смог найти идеальный способ. Этот метод смог успешно это сделать. Большое вам спасибо @John Anderson