我希望我的应用程序在我使用 Kivymd 中的功能单击图块时切换屏幕,但是当我这样做时出现以下错误

I want my app to switch screen when I click on tile using a function in Kivymd but when I do so i get the following error

from kivymd.app import MDApp
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.window import Window
from kivy.factory import Factory
from kivy.uix.label import Label
import json
import requests
from functools import partial
happy_food = ['shahi paneer',
              'matar paneer',
              'dum aloo',
              'samosa',
              'tikki',
              'cheese burger',
              'bhindi do pyaza',
              'vegetble chow mein',
              'vegetable sizzler']
d_image = []
d_name = []
d_recipe = []
d_ingridents = []
d_healthlabels = []
for item in happy_food:
    try:
        v = requests.get(
            f"https://api.edamam.com/api/recipes/v2?type=public&q={item}&app_id=68068831&app_key=myapikey`


`&imageSize=LARGE").text
        food_data = json.loads(v)
    except Exception as e:
        pass
    try:
        dish_image = food_data['hits'][0]['recipe']['image']
        d_image.append(dish_image)
    except Exception as e:
        pass
    try:
        dish_name = food_data['hits'][0]['recipe']['label']
        d_name.append(dish_name)
    except Exception as e:
        pass
    try:
        dish_recipe = food_data['hits'][0]['recipe']['shareAs']
        d_recipe.append(dish_recipe)
    except Exception as e:
        pass
    try:
        dish_ingridents = food_data['hits'][0]['recipe']['ingredientLines']
        d_ingridents.append(dish_ingridents)
    except Exception as e:
        pass
    try:
        dish_healthlabels = food_data['hits'][0]['recipe']['healthLabels']
        d_healthlabels.append(dish_healthlabels)
    except Exception as e:
        pass

print(d_name)

Window.size = (320, 600)
style_string = """
<MagicButton@MagicBehavior+MDRaisedButton>
    size_hint: None, None
    size: "200dp", "200dp"
ScreenManager:
    id:screen_manager
    MainScreen:
    Screen1:
    Moodselection:
    Infoscreen:

<MainScreen>:
    name: 'main'
    Image:
        source: "Login1.png"
        allow_stretch:True
    MDLabel:
        text: "Welcome"
        halign: 'center'
        theme_text_color : 'Custom'
        text_color : (255/255.0, 255/255.0, 255/255.0, 1)
        font_size: '40sp'
        font_name: 'Atkinson-Hyperlegible-Regular-102.otf'
        pos_hint :{'center_C': 0.5 ,'center_y':0.9}
    MDLabel:
        text: "Let us suggest what to have!"
        halign: 'center'
        theme_text_color : 'Custom'
        text_color : (255/255.0, 255/255.0, 255/255.0, 1)
        font_size: '20sp'
        font_name: 'Atkinson-Hyperlegible-Regular-102.otf'
        pos_hint :{'center_C': 0.5 ,'center_y':0.85}
    MDTextField:
        id: username
        icon_right:'account'
        hint_text:"Foodie Name"
        size_hint_x : None
        width:225
        pos_hint : {'center_x':0.5,'center_y': 0.52}
        required:True
        helper_text_mode: "on_error"
        helper_text: "Enter text"
        max_text_length: 25
        elevation:8
    MDTextField:
        id: password
        icon_right:'lock'
        hint_text:"Password"
        size_hint_x : None
        width:225
        pos_hint : {'center_x':0.5,'center_y': 0.4}
        required:True
        helper_text_mode: "on_error"
        helper_text: "Enter text"
        max_text_length: 25
        password :True
    MagicButton:
        text: "LOGIN"
        on_press: root.show_data()
        on_release: self.grow()
        pos_hint: {"center_x": .5, "center_y": .3}
        size_hint: None, None
        size: "200dp", "280dp"
        
    MagicButton:
        text: "SignUp"
        pos_hint: {"center_x": .5, "center_y": .2}
        on_release: self.grow()
<MyTile@SmartTileWithLabel>
    size_hint: None,None
    size:100,100
    
    
<Screen1>:
    name :'S1'
    MDBoxLayout:
        padding: "2dp"
        size_hint:None,None
        size:320,580
        pos_hint: {"center_x": .5, "center_y": .51}
        
        ScrollView:
            MDList:
                id:box
                cols: 3
                padding: dp(4), dp(4)
                spacing: dp(4)
                elevation_normal:20
       
    MDBottomAppBar:
        MDToolbar:
            icon: "food"
            type: "bottom"
            left_action_items: [["magnify", lambda x: x],["account", lambda x: root.go_back()]]
            right_action_items:[["coffee", lambda x: x],["plus-circle-outline", lambda x: x]]
        
<Moodselection>:
    name:'moodselect'
    MDCard:
        size_hint: None, None
        size: "280dp", "180dp"
        pos_hint: {"center_x": .4, "center_y": .79}
        radius:[20,]
        
        MDLabel:
            text: "How are you feeling?"
            halign: 'center'
            font_size: '40sp'
            font_name: 'Atkinson-Hyperlegible-Regular-102.otf'
            theme_text_color : 'Custom'
            text_color : (26/255.0, 83/255.0, 255/255.0, 1)
            
    MDChip:
        text: 'Happy'
        color: (255/255.0, 255/255.0, 77/255.0, 1)
        icon: 'emoticon-happy'
        pos_hint: {"center_x": .5, "center_y": .45}
        check:True
        icon_color:(255/255.0, 77/255.0, 77/255.0, 1)
    MDChip:
        text: 'Sad'
        color: (255/255.0, 51/255.0, 119/255.0, 1)
        icon: 'emoticon-sad'
        pos_hint: {"center_x": .5, "center_y": .4}
        check:True
        icon_color:(102/255.0, 51/255.0, 255/255.0, 1)
    MDChip:
        text: 'Loved'
        color: (179/255.0, 0/255.0, 0/255.0, 1)
        icon: 'heart'
        pos_hint: {"center_x": .5, "center_y": .35}
        check:True
        icon_color:(255/255.0, 80/255.0, 80/255.0, 1)
    MDChip:
        text: 'Angry'
        color: (255/255.0, 64/255.0, 0/255.0, 1)
        icon: 'emoticon-angry'
        pos_hint: {"center_x": .5, "center_y": .3}
        check:True
        icon_color:(255/255.0, 102/255.0, 0/255.0, 1)
            
            
    MagicButton:
        text: "LetsGo!"
        align:'center'
        on_press: root.s1_content()
        on_release: self.grow()
        pos_hint: {"center_x": .5, "center_y": .2}
        
        
<Infoscreen>:
    name:'infoscreen'
    MagicButton:
        text: "LetsGo!"
        align:'center'
        on_release: self.grow()
        pos_hint: {"center_x": .5, "center_y": .2}
    
        
    

"""


class MainScreen(Screen):
    def show_data(self):
        username = self.ids.username.text
        password = self.ids.password.text
        if password == "1234":
            print("Login success!")
            self.manager.current = 'moodselect'


class Moodselection(Screen):
    c = 0
    def s1_content(self):
        self.manager.current = 'S1'
        for i in range(len(d_name)):
            tile = Factory.MyTile(source=d_image[i])
            tile.text = d_name[i]
            tile.id = "t" + str(i)
            tile.bind(on_release=Screen1.newdata)
            self.manager.get_screen('S1').ids.box.add_widget(tile)



class Screen1(Screen):
    def newdata(self):
        self.manager.current = 'infoscreen'


    def go_back(self):
        self.manager.current = 'moodselect'


class Infoscreen(Screen):
    pass

global sn
sn = ScreenManager()
sn.add_widget(MainScreen(name='main'))
sn.add_widget(Screen1(name='S1'))
sn.add_widget(Moodselection(name='moodselect'))
sn.add_widget(Infoscreen(name='infoscreen'))


class foodapp(MDApp):
    def build(self):
        screen = Screen()
        self.theme_cls.primary_palette = 'Teal'
        self.theme_cls.primary_hue = "100"
        style = Builder.load_string(style_string)
        screen.add_widget(style)
        return screen


foodapp().run()

我在点击磁贴时出现此错误,我试过 sn.current='infoscreen' 它不起作用。 单击图块时出现此错误,我已尝试 sn.current='infoscreen' 它不起作用。 单击图块时出现此错误,我已尝试 sn.current='infoscreen' 它不起作用。 单击图块时出现此错误,我已尝试 sn.current='infoscreen' 它不起作用。 单击图块时出现此错误,我已尝试 sn.current='infoscreen' 它不起作用。 单击图块时出现此错误,我已尝试 sn.current='infoscreen' 它不起作用。 单击图块时出现此错误,我已尝试 sn.current='infoscreen' 它不起作用。

[INFO   ] [Logger      ] Record log in C:\Users\nitis\.kivy\logs\kivy_21-06-19_31.txt
[INFO   ] [deps        ] Successfully imported "kivy_deps.gstreamer" 0.3.2
[INFO   ] [deps        ] Successfully imported "kivy_deps.angle" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.glew" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.3.1
[INFO   ] [Kivy        ] v2.0.0
[INFO   ] [Kivy        ] Installed at "C:\Python38\lib\site-packages\kivy\__init__.py"
[INFO   ] [Python      ] v3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)]
[INFO   ] [Python      ] Interpreter at "C:\Python38\python.exe"
[INFO   ] [KivyMD      ] 0.104.2.dev0, git-Unknown, 2021-06-03 (installed at "C:\Python38\lib\site-packages\kivymd\__init__.py")
[INFO   ] [Factory     ] 186 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_pil (img_ffpyplayer ignored)
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [Window      ] Provider: sdl2
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] GLEW initialization succeeded
[INFO   ] [GL          ] Backend used <glew>
[INFO   ] [GL          ] OpenGL version <b'4.6.0 - Build 27.20.100.9466'>
[INFO   ] [GL          ] OpenGL vendor <b'Intel'>
[INFO   ] [GL          ] OpenGL renderer <b'Intel(R) UHD Graphics 620'>
[INFO   ] [GL          ] OpenGL parsed version: 4, 6
[INFO   ] [GL          ] Shading version <b'4.60 - Build 27.20.100.9466'>
[INFO   ] [GL          ] Texture max size <16384>
[INFO   ] [GL          ] Texture max units <32>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
[INFO   ] [GL          ] NPOT texture support is available
['Shahi Paneer', 'Matar Paneer', 'Dum Aloo | Baby Potatoes in Yogurt Gravy', 'Samosa', 'Aloo Tikki Sandwich', 'Blue Cheese Burger', 'BHINDI DO PYAZA', 'Vegetable sizzler']
[INFO   ] [Base        ] Start application main loop
Login success!
[INFO   ] [Loader      ] using a thread pool of 2 workers
[INFO   ] [Base        ] Leaving application in progress...
 Traceback (most recent call last):
   File "C:/Users/nitis/Desktop/pythonProject/KivyAppsdev/Foodapp.py", line 276, in <module>
     foodapp().run()
   File "C:\Python38\lib\site-packages\kivy\app.py", line 950, in run
     runTouchApp()
   File "C:\Python38\lib\site-packages\kivy\base.py", line 582, in runTouchApp
     EventLoop.mainloop()
   File "C:\Python38\lib\site-packages\kivy\base.py", line 347, in mainloop
     self.idle()
   File "C:\Python38\lib\site-packages\kivy\base.py", line 391, in idle
     self.dispatch_input()
   File "C:\Python38\lib\site-packages\kivy\base.py", line 342, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Python38\lib\site-packages\kivy\base.py", line 308, in post_dispatch_input
     wid.dispatch('on_touch_up', me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Python38\lib\site-packages\kivymd\uix\behaviors\ripple_behavior.py", line 296, in on_touch_up
     return super().on_touch_up(touch)
   File "C:\Python38\lib\site-packages\kivy\uix\behaviors\button.py", line 179, in on_touch_up
     self.dispatch('on_release')
   File "kivy\_event.pyx", line 705, in kivy._event.EventDispatcher.dispatch
   File "kivy\_event.pyx", line 1248, in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx", line 1172, in kivy._event.EventObservers._dispatch
   File "C:/Users/nitis/Desktop/pythonProject/KivyAppsdev/Foodapp.py", line 248, in newdata
     self.manager.current = 'infoscreen'
 **AttributeError: 'MyTile' object has no attribute 'manager'**

尝试使用 sn.current 更改 Screens 是行不通的,因为 sn 实际上不是 App 的一部分。

代码行:

sn = ScreenManager()
sn.add_widget(MainScreen(name='main'))
sn.add_widget(Screen1(name='S1'))
sn.add_widget(Moodselection(name='moodselect'))
sn.add_widget(Infoscreen(name='infoscreen'))

正在构建小部件树,但该树(根于 sn)从未在您的 App 中使用过。这些行可以删除。

当您使用时:

tile.bind(on_release=Screen1.newdata)

您混淆了静态方法和实例方法。 Screen1newdata 方法是一个实例方法,需要接收一个 self 参数(在作为实例方法正确调用时自动提供)。通过将 MyTile 作为 Screen1.newdata 绑定到该方法,它提供了对 MyTile 实例的引用作为参数,并且 newdata 方法错误地将 MyTile 实例作为预期的 self 参数。这会产生所描述的错误。

我相信您可以通过在 Moodselection class 中创建一个 newdata 方法并绑定到该方法来解决这个问题:

class Moodselection(Screen):
    c = 0
    def s1_content(self):
        self.manager.current = 'S1'
        for i in range(len(d_name)):
            tile = Factory.MyTile(source=d_image[i])
            tile.text = d_name[i]
            tile.id = "t" + str(i)
            tile.bind(on_release=self.newdata)
            self.manager.get_screen('S1').ids.box.add_widget(tile)
    def newdata(self, *args):
        self.manager.current = 'infoscreen'

不是这个问题的一部分,但除非你是你所使用的构造的特定原因,否则你可以简化你的 build() 方法:

class foodapp(MDApp):
    def build(self):
        self.theme_cls.primary_palette = 'Teal'
        self.theme_cls.primary_hue = "100"
        style = Builder.load_string(style_string)
        return style