Kivy - Create style buttons for reStructuredText

人盡茶涼 提交于 2019-12-08 09:39:54

问题


I would like to create buttons for the reStructuredText widget in Kivy. The buttons would do basic things like bold, underline, or make a heading so the user doesn't have to manually type in the markup. For example, the user could select some text then click the 'bold' button and the text would then be surrounded by [b]...[/b].

I would love to show code of what I've tried but I honestly don't even know where to begin. (Or please let me know if there is a better way to implement basic text editing in Kivy.) I'm currently using the Kivy language to display the rst widget by simply adding

RstDocument:
    show_errors: True

to the kv file (along with the save, etc... buttons).


回答1:


In your question, I heard about the RstDocument widget for the first time. You got me interested and I came up with a minimal sample app which could be a good starting point for you to add more. This is my python file

from kivy.app import App
from kivy.base import Builder
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout



Builder.load_string("""
<root_wgt>:
    orientation: 'vertical'
    BoxLayout:
        size_hint_y:0.2
        Button:
            text: 'Emphasize'
            on_press: root.emphasize()
        Button:
            text: 'Section Header'
            on_press: root.add_section_header()
        Button:
            text: 'Subection Header'
            on_press: root.add_sub_section_header()

    BoxLayout:
        orientation: 'vertical'
        TextInput:
            id: textinput

        RstDocument:
            id: rstdocument
            text: textinput.text
""")


class root_wgt(BoxLayout):
    def emphasize(self):
        text = self.ids.textinput.text
        selection = self.ids.textinput.selection_text
        begin = self.ids.textinput.selection_from
        end = self.ids.textinput.selection_to
        new_text = text[:begin] + ' **' + selection + '** ' + text[end:]
        self.ids.textinput.text = new_text
        self.ids.rstdocument.render()

    def add_section_header(self):
        self.ids.textinput.insert_text("""\n==============""")

    def add_sub_section_header(self):
        self.ids.textinput.insert_text("""\n-----------------""")

class MyApp(App):
    def build(self):
        return root_wgt()

if __name__ == '__main__':
    MyApp().run()

Alternatively, you could just go with a label which also has some styling options https://kivy.org/docs/api-kivy.uix.label.html#markup-text The implementation would look quite similar.



来源:https://stackoverflow.com/questions/45134304/kivy-create-style-buttons-for-restructuredtext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!