Davi Silveira
Davi Silveira

Reputation: 97

Content at bottom of screen... after adding ToolBar with Kivy

I'm just trying to add a simple 'ToolBar' but after the tool bar kept aligning to the bottom I found that AnchorLayout: let's me anchor the toolbar to the top. But all my content is now only showing in the bottom half of the screen... I'm not sure why.. Adjusting the 'center_y': does nothing... Does anyone see my issue, I really appreciate it.

main

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()

kv file

<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

Upvotes: 0

Views: 1708

Answers (1)

John Anderson
John Anderson

Reputation: 39012

The problem is that you are not taking into account the default values for size_hint (1,1) and pos (0,0). So your AnchorLayout fills your Main Screen, because of the default values, but the anchor_y setting puts the MDToolBar at the top of the AnchorLayout.

Similarly, your MDBoxLayout also fills the entire Main Screen, but because the MDRectangleFlatButton and the MDTextField have pre-defined sizes, they don't fill the MDBoxLayout. So they only fill the bottom half of the MDBoxLayout.

So here is a version of your kv (for the Main Screen) that uses pos_hint for the MDToolBar and minimum_height for the MDBoxLayout and actually setting its y value to bump up against the tool bar:

<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)

Upvotes: 2

Related Questions