Метка: ввод длинного текста на экран - PullRequest
1 голос
/ 22 марта 2019

Я пытаюсь получить действительно длинный текст с пронумерованными точками и абзацами на экране моего приложения, используя библиотеку kivy для python.Тем не менее, я не добился успеха в этом, потому что я использую свойство Label, которое допускает только одну строку кода.Если бы я мог получить некоторые подсказки о том, что я должен реализовать в своем коде, это было бы здорово!Я думал о том, чтобы поместить длинный текст в текстовый файл и прочитать его оттуда, но я не слишком уверен, как это сделать.Я хочу ввести длинный текст в приложении: "What can I do" -> "How to prevent a heart attack".

from kivy.lang import Builder
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.popup import Popup

Builder.load_string("""
<Bump@Button>:
    font_size: 40
    color: 1,1,1,1
    size_hint: 0.8,0.4 
    background_color: 1,0,0,1

<Back@Button>: 
    text: 'back'
    pos_hint: {'x':0,'y':0.9}
    size_hint: 0.2,0.1

<menu>:

    Bump:
        text: "What can I do?"
        pos_hint: {'center_x': 0.5, 'center_y':0.7}
        on_press: root.manager.current = 'info'
        on_press: root.manager.transition.direction = 'left'
    Label:
        text: "Remity Biotechnologies"
        pos_hint: {'center_x': 0.5, 'center_y':0.95}

<info>:
    Bump:
        text: "How to prevent a heart attack?"
        size_hint:0.8,0.15
        pos_hint:{'center_x':0.5,'center_y':0.15}
        on_press: root.manager.current = 'info2'
        on_press: root.manager.transition.direction = 'left'
    Back:
        on_press: root.manager.current = 'menu'
        on_press: root.manager.transition.direction = 'right'
        on_press: root.manager.transition.direction = 'left'
<info2>
    ScrollView:
        do_scroll_x: False
        do_scroll_y: True
        bar_width: 4
        Label:                            #PROBLEM LOCATED HERE
            text: "THIS IS WHERE I WANT TO PUT A LONG TEXT"
            font_size: 90
            size_hint_x: 1.0               
            size_hint_y: None
            text_size: self.width, None
            height: self.texture_size[1]


    Back:
        on_press: root.manager.current = 'info'
        on_press: root.manager.transition.direction = 'right'       


""")     
class confirm(Popup):
    pass

class menu(Screen):
    def update(self,dt):
        pass

class info(Screen):
    def update(self,dt):
        pass

class info2(Screen):
    def update(self,dt):
        pass

class ScreenManager(ScreenManager):  
    def update(self,dt):
        self.current_screen.update(dt)

sm = ScreenManager()
sm.add_widget(menu(name='menu'))
sm.add_widget(info(name='info'))
sm.add_widget(info2(name='info2'))


class SimpleKivy4(App):

    def build(self):
        return sm

if __name__ == "__main__":
    SimpleKivy4().run()

Я хотел бы ввести текст ...

long_text =\

"""1)   Be more physically active
Consult with your doctor on the type of exercise you can do and attempt to be consistent with your work outs, with 150 minutes of physical activity every week. Some simple exercises we can recommend are brisk walking, cycling, squats, tow and chair stands, and etc. 
2)  Quit smoking
Smoking is the leading cause of preventable death. It damages the artery walls which increases the chances of atrial fibrillation, strokes and even cancer. Put it out before it puts you out. 
3)  Don’t drink a lot of alcohol
Drinking alcohol raises your blood pressure and severely damages the cardiovascular system. Men should bring no more than 2 drinks a day and women only one. One drink represents 
-One 12-ounce can or bottle of regular beer, ale, or wine cooler
-One 8- or 9-ounce can or bottle of malt liquor
-One 5-ounce glass of red or white wine
-One 1.5-ounce shot glass of distilled spirits like gin, rum, tequila, vodka, or whiskey

4)  Healthy diet
Start eating foods that are low in trans and saturated fats, added sugars and salt. Eat more fruits, vegetables, whole grains, and highly fibrous foods. You should aim for a healthy weight by having smaller portion sizes. 
5)  Manage stress
Stress itself can increase blood pressure and blood clots which increases the chances of heart related problems. Learn to manage your stress levels by doing meditation or physical activities. 
"""

Ответы [ 2 ]

0 голосов
/ 23 марта 2019

Ваши существующие коды для Label могут обрабатывать длинный текст.Вы можете поместить длинный текст в класс, если он не меняется очень часто.

Python Script

Объявите long_text в классе info2:

py - Snippets

from kivy.properties import StringProperty
...
class info2(Screen):
    long_text = StringProperty('')

    def __init__(self, **kwargs):
        super(info2, self).__init__(**kwargs)
        self.long_text = """
        1)   Be more physically active
        Consult with your doctor on the type of exercise you can do and attempt to be consistent with your work outs, with 150 minutes of physical activity every week. Some simple exercises we can recommend are brisk walking, cycling, squats, tow and chair stands, and etc. 
        2)  Quit smoking
        Smoking is the leading cause of preventable death. It damages the artery walls which increases the chances of atrial fibrillation, strokes and even cancer. Put it out before it puts you out. 
        3)  Don’t drink a lot of alcohol
        Drinking alcohol raises your blood pressure and severely damages the cardiovascular system. Men should bring no more than 2 drinks a day and women only one. One drink represents 
        -One 12-ounce can or bottle of regular beer, ale, or wine cooler
        -One 8- or 9-ounce can or bottle of malt liquor
        -One 5-ounce glass of red or white wine
        -One 1.5-ounce shot glass of distilled spirits like gin, rum, tequila, vodka, or whiskey

        4)  Healthy diet
        Start eating foods that are low in trans and saturated fats, added sugars and salt. Eat more fruits, vegetables, whole grains, and highly fibrous foods. You should aim for a healthy weight by having smaller portion sizes. 
        5)  Manage stress
        Stress itself can increase blood pressure and blood clots which increases the chances of heart related problems. Learn to manage your stress levels by doing meditation or physical activities. 
        """

kv файл

  • Перед изменением экрана всегда изменяйте направление перехода ScreenManager.
  • Замените text: "THIS IS WHERE I WANT TO PUT A LONG TEXT" на text: root.long_text

kv - Snippets

    on_press: 
        root.manager.transition.direction = 'left'
        root.manager.current = 'info'
    ...

Label:
    text: root.long_text

Пример

main.py

from kivy.lang import Builder
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.popup import Popup
from kivy.properties import StringProperty

Builder.load_string("""
<Bump@Button>:
    font_size: 40
    color: 1,1,1,1
    size_hint: 0.8,0.4 
    background_color: 1,0,0,1

<Back@Button>: 
    text: 'back'
    pos_hint: {'x':0,'y':0.9}
    size_hint: 0.2,0.1

<menu>:

    Bump:
        text: "What can I do?"
        pos_hint: {'center_x': 0.5, 'center_y':0.7}
        on_press: 
            root.manager.transition.direction = 'left'
            root.manager.current = 'info'
    Label:
        text: "Remity Biotechnologies"
        pos_hint: {'center_x': 0.5, 'center_y':0.95}

<info>:
    Bump:
        text: "How to prevent a heart attack?"
        size_hint:0.8,0.15
        pos_hint:{'center_x':0.5,'center_y':0.15}
        on_press: 
            root.manager.transition.direction = 'left'
            root.manager.current = 'info2'
    Back:
        on_press: 
            root.manager.transition.direction = 'right'
            root.manager.current = 'menu'
<info2>:
    ScrollView:
        do_scroll_x: False
        do_scroll_y: True
        bar_width: 4

        Label:
            text: root.long_text
            font_size: 90
            size_hint_x: 1.0               
            size_hint_y: None
            text_size: self.width, None
            height: self.texture_size[1]

    Back:
        on_press: 
            root.manager.transition.direction = 'right'       
            root.manager.current = 'info'


""")


class confirm(Popup):
    pass


class menu(Screen):
    def update(self, dt):
        pass


class info(Screen):
    def update(self, dt):
        pass


class info2(Screen):
    long_text = StringProperty('')

    def __init__(self, **kwargs):
        super(info2, self).__init__(**kwargs)
        self.long_text = """
        1)   Be more physically active
        Consult with your doctor on the type of exercise you can do and attempt to be consistent with your work outs, with 150 minutes of physical activity every week. Some simple exercises we can recommend are brisk walking, cycling, squats, tow and chair stands, and etc. 
        2)  Quit smoking
        Smoking is the leading cause of preventable death. It damages the artery walls which increases the chances of atrial fibrillation, strokes and even cancer. Put it out before it puts you out. 
        3)  Don’t drink a lot of alcohol
        Drinking alcohol raises your blood pressure and severely damages the cardiovascular system. Men should bring no more than 2 drinks a day and women only one. One drink represents 
        -One 12-ounce can or bottle of regular beer, ale, or wine cooler
        -One 8- or 9-ounce can or bottle of malt liquor
        -One 5-ounce glass of red or white wine
        -One 1.5-ounce shot glass of distilled spirits like gin, rum, tequila, vodka, or whiskey

        4)  Healthy diet
        Start eating foods that are low in trans and saturated fats, added sugars and salt. Eat more fruits, vegetables, whole grains, and highly fibrous foods. You should aim for a healthy weight by having smaller portion sizes. 
        5)  Manage stress
        Stress itself can increase blood pressure and blood clots which increases the chances of heart related problems. Learn to manage your stress levels by doing meditation or physical activities. 
        """

    def update(self, dt):
        pass


class ScreenManager(ScreenManager):

    def update(self, dt):
        self.current_screen.update(dt)


sm = ScreenManager()
sm.add_widget(menu(name='menu'))
sm.add_widget(info(name='info'))
sm.add_widget(info2(name='info2'))


class SimpleKivy4(App):

    def build(self):
        return sm


if __name__ == "__main__":
    SimpleKivy4().run()

Выход

App StartupScrolled to point 2 Scrolled to bottom of long text

0 голосов
/ 23 марта 2019

Попробуйте это:

Label:
    size_hint_y: None
    text_size: self.width, None
    height: self.texture_size[1]

Источник / сообщение в блоге об этом: https://blog.kivy.org/2014/07/wrapping-text-in-kivys-label/

...