Содержимое внизу экрана ... после добавления ToolBar с Kivy - PullRequest
0 голосов
/ 21 июня 2020

Я просто пытаюсь добавить простую панель инструментов, но после того, как панель инструментов продолжала выравниваться по нижнему краю, я обнаружил, что AnchorLayout: позвольте мне закрепить панель инструментов вверху. Но весь мой контент теперь отображается только в нижней половине экрана ... Я не уверен, почему ... Регулировка 'center_y': ничего не делает ... Кто-нибудь видит мою проблему, я очень ценю это.

основной

from kivymd.app import MDApp
from kivymd.uix.floatlayout import MDFloatLayout
from kivymd.uix.dialog import MDDialog
from kivymd.uix.button import MDFlatButton, MDIconButton
from kivy.uix.scrollview import ScrollView
from kivy.uix.screenmanager import Screen, ScreenManager

from PyDictionary import PyDictionary
import sys
import json
import requests


class Manager(ScreenManager):
    """Manages Screens"""

class Main(Screen):
    """main application goes here"""
    def close_dialog(self, obj):
        self.dialog.dismiss()

    def show_data(self):
        message = """
        This little program was
        designed to help re-think
        your sentences.
        """
        close = MDIconButton(icon="close-circle", on_release=self.close_dialog)
        #more = MDIconButton(icon="more")
        self.dialog = MDDialog(title="Probably Knot", text=message,
                         size_hint=(0.5, 1), buttons=[close])
        self.dialog.open()


class Analyzer(Screen):
    def analyze(self, main): # main is pointing to ---> Main().show_data()
        """Analyse data with PyDictionary"""
        sent = main.ids.sentence.text.lower()
        wrd = main.ids.word.text.lower()

        # Definition Section #
        dictionary = PyDictionary()
        define_wrd = dictionary.meaning(wrd)

        noun = ''
        verb = ''
        adjective = ''
        result = ''

        try:
            noun = " ".join(define_wrd['Noun'])
            result += f"Definition:\n1. {wrd}:\n{noun}\n"
        except TypeError or KeyError:
            noun = False
            print('Noun, is not found in API http://words.bighugelabs.com/api')
        try:
            verb = " ".join(define_wrd['Verb'])
            result += f"2.\n{verb}\n"
        except TypeError or KeyError:
            verb = False
            print('Verb, is not found in API http://words.bighugelabs.com/api')
        try:
            adjective = " ".join(define_wrd['Adjective'])
            result += f"3.\n{adjective}\n"
        except TypeError or KeyError:
            adjective = False
            print('Adjective, is not found in API http://words.bighugelabs.com/api')

        if not noun and not verb and not adjective:
            error = MDDialog(title="Error", text=f"Word: '{wrd}' is not in\n\n'dictionary'")
            error.open()

        if wrd != '' and sent != '':
            API_KEY = 'a701e74e453ee6695e450310340401f5'
            URL = f'http://words.bighugelabs.com/api/2/{API_KEY}/{wrd}/json'

            if wrd not in sent:
                error = MDDialog(title="Error", text=f"Word: '{wrd}' is not in\n\n'{sent}'")
                error.open()
            else:
                r = requests.get(URL) # get's url json file
                j = json.loads(r.text) # loads json into 'j' as a dict

                if type(j) == dict: # check is 'j' variable is coming in as a Dict 
                    # holds the new sentences
                    new = f"{result}\n"
                    try:
                        for num, w in enumerate(j['adjective']['syn'], 1):
                            new += f"{num}: {sent.replace(wrd, w)}\n"
                    except KeyError:
                        print(f'Adjective for "{wrd}" is not found.')
                    try:
                        for num, w in enumerate(j['noun']['syn'], 1):
                            new += f"{num}: {sent.replace(wrd, w)}\n"
                    except KeyError:
                        print(f'Noun for "{wrd}" is not found.') 
                    try:
                        for num, w in enumerate(j['verb']['syn'], 1):
                            new += f"{num}: {sent.replace(wrd, w)}\n"
                    except KeyError:
                        print(f'Verb for "{wrd}" is not found.')


class ProbablyKnotApp(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Yellow"
        self.theme_cls.primary_hue = "A700"

        return Manager()

ProbablyKnotApp().run()

кв файл

<Manager>:
    Main:
        name: 'main'
    Analyzer:
        name: 'analyzer'


<Main>:
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'top'
        MDToolbar:
            title: "Probably Knot"
            pos_hint_y: None
            pos_y: 1
            md_bg_color: app.theme_cls.accent_color
            right_action_items: [["dots-vertical", lambda x: app.callback()]]
    MDBoxLayout:
        orientation: 'vertical'
        MDRectangleFlatButton:
            text: "help"
            pos_hint: {'center_x': 0.75, 'center_y': 1}
            on_release: app.root.get_screen('main').show_data()

        MDTextField:
            id: sentence
            icon_right: "book-open-outline"
            icon_right_color: app.theme_cls.primary_color

            hint_text: "Enter Sentence"
            helper_text: "Write a problem statement to analyze"
            helper_text_mode: "on_focus"
            pos_hint: {'center_x': 0.5, 'center_y': 0.7}
            size_hint_x: None
            width: 400

        MDTextField:
            id: word
            icon_right: "lead-pencil"
            icon_right_color: app.theme_cls.primary_color

            hint_text: "Enter Word"
            helper_text: "Write ONE word from the above sentence"
            helper_text_mode: "on_focus"
            pos_hint: {'center_x': 0.5, 'center_y': 0.6}
            size_hint_x: None
            width: 400

        MDIconButton:
            icon: "card-plus"
            pos_hint: {'center_x': 0.75, 'center_y': 0.5}
            on_release: app.root.get_screen('analyzer').analyze(root)
<Analyzer>:
    MDToolbar:
        title: "Probably Knot"
        md_bg_color: app.theme_cls.accent_color
        right_action_items: [["dots-vertical", lambda x: app.callback()]]
    MDList:
        id: container

1 Ответ

1 голос
/ 21 июня 2020

Проблема в том, что вы не учитываете значения по умолчанию для size_hint (1,1) и pos (0,0). Таким образом, ваш AnchorLayout заполняет ваш Main Screen из-за значений по умолчанию, но настройка anchor_y помещает MDToolBar в верхнюю часть AnchorLayout.

Точно так же ваш MDBoxLayout также заполняет весь Main Screen, но поскольку MDRectangleFlatButton и MDTextField имеют заранее определенные размеры, они не заполняют MDBoxLayout. Таким образом, они заполняют только нижнюю половину MDBoxLayout.

Итак, вот версия вашего kv (для Main Screen), которая использует pos_hint для MDToolBar и minimum_height для MDBoxLayout и фактически устанавливая его значение y так, чтобы оно упиралось в панель инструментов:

<Main>:
    MDToolbar:
        id: toolbar
        title: "Probably Knot"
        pos_hint: {'top':1.0}
        md_bg_color: app.theme_cls.accent_color
        right_action_items: [["dots-vertical", lambda x: app.callback()]]
        
    MDBoxLayout:
        size_hint: 1, None
        height: self.minimum_height
        y: root.height - toolbar.height - self.height
        orientation: 'vertical'
        
        MDRectangleFlatButton:
            text: "help"
            pos_hint: {'center_x': 0.75, 'top': 1}
            on_release: app.root.get_screen('main').show_data()

        MDTextField:
            id: sentence
            icon_right: "book-open-outline"
            icon_right_color: app.theme_cls.primary_color

            hint_text: "Enter Sentence"
            helper_text: "Write a problem statement to analyze"
            helper_text_mode: "on_focus"
            pos_hint: {'center_x': 0.5, 'top': 0.7}
            size_hint_x: None
            width: 400

        MDTextField:
            id: word
            icon_right: "lead-pencil"
            icon_right_color: app.theme_cls.primary_color

            hint_text: "Enter Word"
            helper_text: "Write ONE word from the above sentence"
            helper_text_mode: "on_focus"
            pos_hint: {'center_x': 0.5, 'center_y': 0.6}
            size_hint_x: None
            width: 400

        MDIconButton:
            icon: "card-plus"
            pos_hint: {'center_x': 0.75, 'center_y': 0.5}
            on_release: app.root.get_screen('analyzer').analyze(root)
...