首页 > 解决方案 > KivyMD 应用程序中某些小部件的位置问题

问题描述

我正在尝试构建一个关于冠状病毒的信息应用程序,我正在使用 newsapi 实时实现新闻。但是,我在制作它时遇到了几个问题,这主要是因为我对 KivyMD 框架有点陌生。无论如何,我现在遇到的主要问题是将一些小部件居中并在小部件上获得正确的位置listitem

编码:


from kivy.lang.builder import Builder
from kivy.uix.screenmanager import ScreenManager, Screen#<--Screen Manager
from kivy.properties import ObjectProperty #<--- Object Propert
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout#<--FloatLayout
from kivy.uix.gridlayout import GridLayout#<--GridLayout
from kivy.uix.scrollview import ScrollView#<--ScrollView
from kivy.uix.button import Button#<--Button
from kivymd.app import MDApp#<--MDApp
from kivy.clock import Clock#<--Clock
import requests#<--Requests
from kivymd.uix.tab import MDTabsBase
from kivymd.uix.list import IRightBodyTouch, OneLineAvatarIconListItem
import json#<--json
import gc#<--gc
import time
from kivymd.uix.list import OneLineListItem
from kivymd.uix.selectioncontrol import MDCheckbox




url = ('http://newsapi.org/v2/everything?'
       'q=Coronavírus&'
       'language=pt&'
       'apiKey=f5e80820673d4590ac59b11d3be9013a')
       
#Try connecting to NewsApi
try:
   response = requests.get(url)
   toph = response.json()
   eachnews = toph.get('articles')
   separatenews1 = eachnews[-1]
   separatenews2 = eachnews[-2]
   separatenews3 = eachnews[-3]
   titlen1 = "[b]1# [/b]" + str(separatenews1.get('title'))
   titlen2 = "[b]2# [/b]" + str(separatenews2.get('title'))
   titlen3 = "[b]3# [/b]" + str(separatenews3.get('title'))
   img1 = str(separatenews1.get('urlToImage'))
   img2 = str(separatenews2.get('urlToImage'))
   img3 = str(separatenews3.get('urlToImage'))
except (requests.exceptions.ConnectionError, HTTPError):
   r.status_code = "Connection refused"

#disable gc
gc.disable()

#kivy language file

Kv_string = '''

#:import ScrollEffect  kivy.effects.scroll.ScrollEffect
#:import images_path kivymd.images_path

<ContentNavigationDrawer>:
    orientation: "vertical"
    padding: "8dp"
    spacing: "8dp"
    AnchorLayout:
        anchor_x: "left"
        anchor_y: "top"
        size_hint_y: None
        height: image_init.height
        Image:
            id: image_init
            size_hint: None, None
            size: "100dp", "100dp"
            source: "Lokgo.jpg"
    ScrollView:
        MDList:
            OneLineAvatarIconListItem:
                text:"Notícias"
                pos_hint:{'y':0.8}
                on_press: root.nav_drawer.set_state("close")
                on_press:root.screen_man.current = "subscreen1"
                IconLeftWidget:
                    icon:"newspaper"
            OneLineAvatarIconListItem:
                text:"Curados"
                on_press:root.nav_drawer.set_state("close")
                on_press:root.screen_man.current = "subscreen2"
                IconLeftWidget:
                    icon:"medical-bag"
            OneLineAvatarIconListItem:
                text:"Pesquisa"
                on_press:root.nav_drawer.set_state("close")
                on_press:root.screen_man.current = "subscreen3"
                IconLeftWidget:
                    icon:"align-horizontal-left"

   
                    


ScreenMain:
    screen_man:screen_man
    
    NavigationLayout:
        ScreenManager:
            id:screen_man
            Screen:
                name:"screen1"
                FloatLayout:
                    orientation:'vertical'
                    AsyncImage:
                        size_hint_x: 1
                        size_hint_y: 
                        allow_stretch: True
                        source:"https://i.ibb.co/ftV87fN/corons.gif"
                        pos_hint:{'center_x':0.5,'y':0.35}
                        border_radius:[20, 20, 20, 20]
                    MDLabel:
                        text:"Bem-vindo(a)"
                        halign:'center'
                    MDRoundFlatButton:
                        text:"Entrar"
                        pos_hint: {'center_x':0.5,'y':0.3}
                        
                        on_press: root.screen_man.current="screen2"
            Screen:
                name:"screen2"
                
                BoxLayout:
                    orientation:"vertical"
                    MDToolbar:
                        title:"C-19"
                        left_action_items: [["menu", lambda x: nav_drawer.set_state("open")]]
                        elevation: 10
                        pos_hint: {"top": 1}
                    ScreenManager:
                        id:screen_men
                        Screen:
                            name:"subscreen1"
                            scrole:scrole.__self__
                            cabeca_linhas1: cabeca_linhas1.__self__
                            head_lines2: head_lines2.__self__
                            head_lines3: head_lines3.__self__
                            foto_1: foto_1.__self__
                            image_2:image_2.__self__
                            image_3:image_3.__self__
                            
                            
                            ScrollView:
                                id:scrole
                                effect_cls: ScrollEffect
                                bar_width: 4
                                GridLayout:
                                    id:box_sb1
                                    cols:1
                                    spacing: 80, 80
                                    size_hint_y: None
                                    height: self.minimum_height
                                    
                                    MDLabel:
                                        text:"\\n"
                                    MDCard:
                                        orientation: "vertical"
                                        padding: "8dp"
                                        size_hint: None, None
                                        size: "280dp", "300dp"
                                        pos_hint: {"center_x": .5, "center_y": .4}
                                        AsyncImage:
                                            id: foto_1
                                            allow_stretch: True
                                            size:"270dp", "50dp"
                                            source:""
                                        MDLabel:
                                            id:cabeca_linhas1
                                            markup: True
                                            text:""
                                            
                                    MDCard:
                                        orientation: "vertical"
                                        padding: "8dp"
                                        size_hint: None, None
                                        size: "280dp", "300dp"
                                        pos_hint: {"center_x": .5, "center_y": .3}
                                        AsyncImage:
                                            id: image_2
                                            allow_stretch: True
                                            size:"270dp", "50dp"
                                        
                                            source:""
                                        MDLabel:
                                            id: head_lines2
                                            markup: True
                                            text:""
                                    
                                    MDCard:
                                        orientation: "vertical"
                                        padding: "8dp"
                                        size_hint: None, None
                                        size: "280dp", "300dp"
                                        pos_hint: {"center_x": .5, "center_y": .1}
                                        
                                        AsyncImage:
                                            id:image_3
                                            allow_stretch: True
                                            size:"270dp", "50dp"
                                            source:""
                                        MDLabel:
                                            id:head_lines3
                                            markup:True
                                            text:""
                                            
                                    MDLabel:
                                        text:"\\n"
                        Screen:
                            name:"subscreen2"
                            MDTabs:
                                on_tab_switch: app.on_tab_switch(*args)
                                Tab:
                                    text:"O Vírus"
                                Tab:
                                    text:"Profilaxia"

                        Screen:
                            name:"subscreen3"
                            idade_user_:idade_user_
                            resposta_idade_:resposta_idade_
                            ScrollView:
                                GridLayout:
                                    id:box_sb2
                                    cols:1
                                    spacing: 80, 80
                                    size_hint_y: None
                                    height: self.minimum_height
                                    MDTextField:
                                        id:idade_user_
                                        hint_text:"Digite sua idade-"
                                        helper_text_mode: "on_focus"
                                        pos_hint:{'center_x':0.5, 'center_y':0.1}
                                        input_filter: 'int'
                                        max_text_length: 3
                                    MDLabel:
                                        text:"Verifique se tem alguma dessas doenças:"
                                    MyListOfProbls:
                                        OneLineListItem:
                                            text:"1"
                                        RightCheckbox:
                                        
                                                
    
                                    MDRoundFlatButton:
                                        text:"Resposta"
                                        halign:"center"
                                        pos_hint:{'center_x':0.5, 'center_y':0.1}
                                        on_press:root.resposta()
                                    MDSeparator:
                                        height:'3dp'
                                        pos_hint:{'center_x':0.5, 'center_y':0.4}
                                    MDLabel:
                                        id:resposta_idade_
                                        text:""
                                        pos_hint:{'x':0.3, 'center_y':0.2}
                                        halign:"center"
                                    MDLabel:
                                        text:""
                MDNavigationDrawer:
                    id: nav_drawer
                    ContentNavigationDrawer:
                        screen_men:screen_man
                        screen_man:screen_men
                        nav_drawer:nav_drawer
                        
<Tab>:
    ScrollView:
        GridLayout:
            MDLabel:
                id:my_test
                halign:"center"
                pos_hint:{'center_x':0.5, 'center_y':0.7}
                text:""
'''

class Tab(FloatLayout, MDTabsBase):
    pass

class MyListOfProbls(OneLineListItem):
    '''Custom list item.'''
    
class RightCheckbox(IRightBodyTouch, MDCheckbox):
    '''Custom right container.'''
    
class ContentNavigationDrawer(BoxLayout):
    screen_man = ObjectProperty()
    screen_men = ObjectProperty()
    nav_drawer = ObjectProperty()
    idade_user_ = ObjectProperty(None)
    resposta_idade_ = ObjectProperty(None)
    
class ScreenMain(Screen):
    cabeca_linhas1 = ObjectProperty(None)
    head_lines2 = ObjectProperty(None)
    head_lines3 = ObjectProperty(None)
    foto_1 = ObjectProperty(None)
    image_2 = ObjectProperty(None)
    image_3 = ObjectProperty(None)
    
    def __init__(self, **kwargs):
        
        super(ScreenMain, self).__init__(**kwargs)
        Clock.schedule_once(self.on_enter)
        
    def on_enter(self, *argm):
        
        
        #First News
        self.ids.cabeca_linhas1.text = titlen1
        self.ids.foto_1.source = img1
        #Second News
        self.ids.head_lines2.text = titlen2
        self.ids.image_2.source = img2
        #Third News
        self.ids.head_lines3.text = titlen3
        self.ids.image_3.source = img3
        
    def resposta(self, *args):
        
        list_improprio=[""]
        
        if len(str(self.ids.idade_user_.text)) > 3:
            pass
            
            
        elif str(self.ids.idade_user_.text) in list_improprio:
            pass
            
            
        elif int(float(self.ids.idade_user_.text)) > 50:
            self.ids.resposta_idade_.text="GRUPO DE RISCO!"
            
            
        elif int(float(self.ids.idade_user_.text)) < 0:
            pass
            
            
        else:
            self.ids.resposta_idade_.text = "Fora do grupo de risco."   

#MDApp Class
class TestNavigationDrawer(MDApp):
    def build(self):
        self.theme_cls.primary_palette = "Blue"
        return Builder.load_string(Kv_string)
    def on_tab_switch(self, instance_tabs, instance_tab, instance_tab_label, tab_text):
        if tab_text == "O Vírus":
            instance_tab.ids.my_test.text = "1" #MUDAR O TEXT
        elif tab_text == "Profilaxia":
            instance_tab.ids.my_test.text = "Lave suas mãos com frequência. Use sabão e água ou álcool em gel. Mantenha uma distância segura de pessoas que estiverem tossindo ou espirrando. Use máscara quando não for possível manter o distanciamento físico. Não toque nos olhos, no nariz ou na boca. Cubra seu nariz e boca com o braço dobrado ou um lenço ao tossir ou expirar. Fique em casa se você se sentir indisposto. Procure atendimento médico se tiver febre, tosse e dificuldade para respirar. São medidas adotadas para a prevenção e propagação da covid-19, que apesar de não lhe tornar imune ao vírus, diminui chances de propagação, e vem dando certo em diversos países, que a quarentena foi seguida corretamente, como na Itália, que sofria com muitos casos, mas com essas medidas o número de casos diminuíram dramaticamente" #MUDAR O TEXT

TestNavigationDrawer().run()

在这部分代码中,有一种供人们进行的调查,以便他们了解自己是否属于风险组。

                                GridLayout:
                                    id:box_sb2
                                    cols:1
                                    spacing: 80, 80
                                    size_hint_y: None
                                    height: self.minimum_height
                                    MDTextField:
                                        id:idade_user_
                                        hint_text:"Digite sua idade-"
                                        helper_text_mode: "on_focus"
                                        pos_hint:{'center_x':0.5, 'center_y':0.1}
                                        input_filter: 'int'
                                        max_text_length: 3
                                    MDLabel:
                                        text:"Verifique se tem alguma dessas doenças:"
                                    MyListOfProbls:
                                        OneLineListItem:
                                            text:"1"
                                        RightCheckbox:
                                        
                                                
    
                                    MDRoundFlatButton:
                                        text:"Resposta"
                                        halign:"center"
                                        pos_hint:{'center_x':0.5, 'center_y':0.1}
                                        on_press:root.resposta()
                                    MDSeparator:
                                        height:'3dp'
                                        pos_hint:{'center_x':0.5, 'center_y':0.4}
                                    MDLabel:
                                        id:resposta_idade_
                                        text:""
                                        pos_hint:{'x':0.3, 'center_y':0.2}
                                        halign:"center"
                                    MDLabel:
                                        text:""

当我运行它时,输出是这样的: 在此处输入图像描述

你能看到有些元素没有居中吗?就像按钮“Resposta”一样。MDList 也有一点漏洞。那么,我该如何解决呢?

标签: pythonpython-3.xkivykivymd

解决方案


推荐阅读