Проблема с kivy.uix.widget.WidgetException - PullRequest
       123

Проблема с kivy.uix.widget.WidgetException

0 голосов
/ 07 августа 2020

Я новичок в python и kivymd, и я пытаюсь разработать программу для ввода данных. Однако когда я создаю раскрывающееся меню для выбора, произошла ошибка, и я не могу обновить значение текстового поля после выбора элемента. Вот код python:

from kivymd.app import MDApp
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.properties import ObjectProperty
from kivymd.uix.menu import MDDropdownMenu
class AMRMenu(Screen):
    def GIbutton(self):
        sm.current = 'GI'
class GIWindow(Screen):
    weather = ObjectProperty(None)
    menu_weather_items = [{"text":"Sunny"},{"text":"Cloudy"},{"text":"Raining"}]
    menu_FeedResponse_items=[{"text":"High"},{"text":"Medium"},{"text":"Low"}]
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.menu = MDDropdownMenu(
                    items=self.menu_weather_items, 
                    width_mult=4,
                    caller = self.weather,
                    callback=self.set_item)
    def set_item(self, instance):
        def set_item(interval):
            self.weather.text = instance.text
            self.menu.dismiss()
        Clock.schedule_once(set_item, 0.5) 
class WindowManager(ScreenManager):
    pass
sm = WindowManager()    

class MainApp(MDApp):   
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        kv = Builder.load_file("FR.kv")
    def build(self):        
        screens = [AMRMenu(name = "menu"), GIWindow(name = "GI")]
        for screen in screens:
            sm.add_widget(screen)
        sm.current = "menu"
        return sm
if __name__ == "__main__":
    MainApp().run()

А вот и кв. file:

<AMRMenu>:
    name:"menu"
    BoxLayout:
        orientation: "vertical"
        MDToolbar:
            title: "Main Menu"
        MDList:
            OneLineListItem:
                text: "General Information"
                on_press: root.GIbutton()
            OneLineListItem:
                text: "Water Temperature"
            OneLineListItem
                text: "Feeding Amount"
            OneLineListItem: 
                text: "Residue and Feeding response"
            OneLineListItem: 
                text: "Dead fish"
            OneLineListItem:
                text: "Sell/Use"

<GIWindow>
    name: "GI"

    weather: weather
    ScrollView:
        id: screen
        MDBoxLayout:
            orientation: 'vertical'
            adaptive_height: True

            MDTextField:
                id: weather
                pos_hint: {'center_x': .5, 'center_y': .5}
                hint_text: "Weather"
                icon_right: "arrow-down-drop-circle-outline"
                input_filter: lambda text, from_undo: text[:5 - len(self.text)]
                on_focus: root.menu.open()

Вот сообщение об ошибке:

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/kivy/core/window/__init__.py", line 1297, in add_widget
 (widget, widget.parent)
 kivy.uix.widget.WidgetException: Cannot add <kivymd.uix.menu.MDDropdownMenu object at 0x7fd2fa31a6e0> to window, it already has a parent <kivy.core.window.window_sdl2.WindowSDL object at 0x7fd2f65826e0>

Я не знаю, почему я это сделал. Очень помогает, если кто-то в этом разбирается. Спасибо, что прочитали этот вопрос

1 Ответ

0 голосов
/ 07 августа 2020

Проблема в том, что ваша kv строка:

on_focus: root.menu.open()

открывает меню каждый раз, когда focus изменяется. Таким образом, он пытается открыть меню, даже если focus становится ложным. Простое решение - просто открыть меню, когда focus is True`:

on_focus: if self.focus: root.menu.open()
...