【问题标题】:Kivy unable to add text to button using ButtonBehaviorKivy 无法使用 ButtonBehavior 向按钮添加文本
【发布时间】:2018-08-21 12:05:41
【问题描述】:

我想在圆形图像的右侧添加文字。我被告知要使用标签来执行此操作,但我无法弄清楚如何实际执行此操作。它必须是动态的,所以如果您必须在 KV 语言中执行此操作,您能否告诉我如何保持按钮动态,即使在 KV 文件中制作按钮也是如此。如果可能的话,我想把它保存在 Python 文件中,但如果 KV 方式更好,那就这样吧。

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.clock import mainthread
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.properties import BooleanProperty, StringProperty
from kivy.uix.image import AsyncImage
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.image import Image

Builder.load_file('main.kv')

login_plz = Popup(title='Please login',
                  content=Label(text='You need to login first'),
                  size_hint=(None, None), size=(400, 400),
                  auto_dismiss=True)


class Menu(BoxLayout):

    access_denied = BooleanProperty(True)


class ScreenLogIn(Screen):


    @mainthread
    def verify_credentials(self):
        popup = Popup(title='Try again',
                      content=Label(text='Wrong Email/Password'),
                      size_hint=(None, None), size=(400, 400),
                      auto_dismiss=True)

        try:

            if len(self.ids.login.text) > 20 or len(self.ids.passw.text) > 32:
                popup.open()



            elif self.ids.login.text == "a" and self.ids.passw.text == "a":
                App.get_running_app().root.access_denied = False
                self.manager.current = "match"


            else:
                App.get_running_app().root.access_denied = True

                popup.open()
        except Exception as e:
            pass


class ScreenNearUsers(Screen):

    @mainthread
    def on_enter(self):
        if App.get_running_app().root.access_denied is True:
            self.manager.current = 'login'
            login_plz.open()
        else:
            for i in xrange(31):
                button = Button(text="B_" + str(i))
                self.ids.grid.add_widget(button)


class ScreenMatch(Screen):



    def on_enter(self, *args):
        if App.get_running_app().root.access_denied is True:
            self.manager.current = 'login'
            login_plz.open()
        else:
            for i in range(10):
                src = "http://placehold.it/480x270.png&text=slide-%d&.png" % i
                image = AsyncImage(source=src, allow_stretch=True, keep_ratio=False, opacity=1, size_hint=(1, 1.3),
                                   pos_hint={'center_x': 0.5, 'center_y': 0.75}, border=True)
                self.ids.carousel.add_widget(image)

class ImageButton(ButtonBehavior, Image):
    def __init__(self, **kwargs):
        super(ImageButton, self).__init__(**kwargs)



class ScreenChats(Screen):


    def on_enter(self, *args):
        if App.get_running_app().root.access_denied is True:
            self.manager.current = 'login'
            login_plz.open()
        else:
            # This is the button with the image below
            for i in range(4):
                button = ImageButton(source=('Trifecta.png'), size=(200,200), size_hint=(None,None), text='some text')
                self.ids.chat_layout.add_widget(button)



class ScreenUserProfile(Screen):
    def on_enter(self, *args):
        if App.get_running_app().root.access_denied is True:
            self.manager.current = 'login'
            login_plz.open()
        else:
            pass


class Manager(ScreenManager):
    screen_log_in = ObjectProperty(None)
    screen_near_user = ObjectProperty(None)
    screen_match = ObjectProperty(None)
    screen_chats = ObjectProperty(None)
    screen_user_profile = ObjectProperty(None)


class MenuApp(App):






    def build(self):
        return Menu()

    def on_start(self):
        self.current_screen = 'login'





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

主Kv:

<Menu>:
    manager: screen_manager
    orientation: "vertical"
    id: action

    ActionBar:
        size_hint_y: 0.1
        background_color: 0, 0, 1000, 10
        background_normal: ""
        ActionView:
            ActionPrevious:
                app_icon:""
                with_previous: False
                markup:True
                font_size:"16dp"
            ActionButton:
                id: near_users
                size_hint: 1, 1
                height: self.texture_size[ 1 ]
                width: self.texture_size[ 0 ] + 40
                minimum_width: self.texture_size[ 0 ] + 60

                halign: "center"
                icon: 'icons/internet.png'
                disabled: True if root.access_denied else False
                on_press: root.manager.current = 'near_users'
            ActionButton:
                id: matching_bar
                size_hint: 1, 1

                height: self.texture_size[ 1 ]
                width: self.texture_size[ 0 ] + 40
                minimum_width: -self.texture_size[ 0 ] + 60
                halign: "center"
                text: "Matching"
                disabled: True if root.access_denied else False
                on_press: root.manager.current= 'match'
            ActionButton:
                id: chat
                size_hint: 1, 1

                height: self.texture_size[ 1 ]
                width: self.texture_size[ 0 ] + 40
                minimum_width: self.texture_size[ 0 ] + 60

                halign: "center"
                text: "chat"
                disabled: True if root.access_denied else False
                on_press: root.manager.current = 'chats'
            ActionButton:
                id: profile
                size_hint: 1, 1

                height: self.texture_size[ 1 ]
                width: self.texture_size[ 0 ] + 40
                minimum_width: self.texture_size[ 0 ] + 60

                halign: "center"
                text: "Profile"
                disabled: True if root.access_denied else False
                on_press: root.manager.current = 'profile'
    Manager:
        id: screen_manager

<ScreenLogIn>:
    id: login_screen
    BoxLayout:
        orientation: "vertical"
        padding: 20, 20
        spacing: 50
        TextInput:
            id: login
            size_hint_y: None

            multiline: False
        TextInput:
            id: passw
            size_hint_y: None
            multiline: False
            password: True # hide password
        Button:
            text: "Log In"
            on_release: root.verify_credentials()

<ScreenNearUsers>:
    ScrollView:
        GridLayout:
            id: grid
            size_hint_y: None
            height: self.minimum_height
            cols: 2
            row_default_height: '20dp'
            row_force_default: True
            spacing: 0, 0
            padding: 0, 0



<ScreenMatch>:
    name: 'Carousel'
    fullscreen: True



    BoxLayout:
        size_hint_y: None
        height: '48dp'

        Button:

            text: 'last user'
            id: last_user

        Button:

            text: 'like'

        Button:
            text: 'super like'
            on_release: carousel.load_previous()

        Button:
            text: 'Dislike'
            on_release: carousel.load_next()


    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'center'




    Carousel:

        id: carousel
        loop: last_user.state == 'down'



<ScreenChats>:


    ScrollView:

        GridLayout:
            id: chat_layout
            size_hint_y: None
            height: self.minimum_height
            cols: 1
            row_default_height: '125dp'
            row_force_default: True
            spacing: 0, 0
            padding: 0, 0



<ScreenUserProfile>:

    Button:
        text: "stuff4"

<Manager>:
    id: screen_manager
    screen_log_in: screen_log_in
    screen_near_users: screen_near_users
    screen_match: screen_match
    screen_chats: screen_chats
    screen_user_profile: screen_user_profile

    ScreenLogIn:
        id: screen_log_in
        name: 'login'
        manager: screen_manager
    ScreenNearUsers:
        id: screen_near_users
        name: 'near_users'
        manager: screen_manager
    ScreenMatch:
        id: screen_match
        name: 'match'
        manager: screen_manager
    ScreenChats:
        id: screen_chats
        name: 'chats'
        manager: screen_manager
    ScreenUserProfile:
        id: screen_user_profile
        name: 'profile'
        manger: screen_manager

【问题讨论】:

    标签: python python-2.7 kivy kivy-language


    【解决方案1】:

    ButtonBehaviour 不支持文本。试试这个:

    button = Button()
    button.size_hint=(None,None)
    button.size=(200,200)
    button.text = "some text"
    button.background_normal = 'Trifecta.png';
    

    【讨论】:

    • 如果我使用按钮,那么图像将拉伸以适合按钮。为什么你认为我不只是使用 Button 开头?
    【解决方案2】:

    我自己找到了答案,在使用 ButtonBehavior 时,您只能在 KV 语言的按钮内放置标签。然后你可以使用 Factory 从 python 文件中访问按钮。 ImageButton 类中的“text = StringProperty()”是必需的,因为存在某种错误,导致生成的第一个按钮没有文本。

    from kivy.app import App
    from kivy.uix.screenmanager import ScreenManager, Screen
    from kivy.properties import ObjectProperty
    from kivy.uix.boxlayout import BoxLayout
    from kivy.lang import Builder
    from kivy.clock import mainthread
    from kivy.uix.button import Button
    from kivy.uix.popup import Popup
    from kivy.uix.label import Label
    from kivy.uix.button import Button
    from kivy.properties import BooleanProperty, StringProperty
    from kivy.uix.image import AsyncImage
    from kivy.uix.behaviors import ButtonBehavior
    from kivy.uix.image import Image
    from kivy.factory import Factory
    
    Builder.load_file('main.kv')
    
    login_plz = Popup(title='Please login',
                      content=Label(text='You need to login first'),
                      size_hint=(None, None), size=(400, 400),
                      auto_dismiss=True)
    
    
    class Menu(BoxLayout):
    
        access_denied = BooleanProperty(True)
    
    
    class ScreenLogIn(Screen):
    
    
        def verify_credentials(self):
            popup = Popup(title='Try again',
                          content=Label(text='Wrong Email/Password'),
                          size_hint=(None, None), size=(400, 400),
                          auto_dismiss=True)
    
            try:
    
                if len(self.ids.login.text) > 20 or len(self.ids.passw.text) > 32:
                    popup.open()
    
    
    
                elif self.ids.login.text == "a" and self.ids.passw.text == "a":
                    App.get_running_app().root.access_denied = False
                    self.manager.current = "match"
    
    
                else:
                    App.get_running_app().root.access_denied = True
    
                    popup.open()
            except Exception as e:
                pass
    
    
    class ScreenNearUsers(Screen):
    
        @mainthread
        def on_enter(self):
            if App.get_running_app().root.access_denied is True:
                self.manager.current = 'login'
                login_plz.open()
            else:
                for i in xrange(31):
                    button = Button(text="B_" + str(i))
                    self.ids.grid.add_widget(button)
    
    
    class ScreenMatch(Screen):
    
    
    
        def on_enter(self, *args):
            if App.get_running_app().root.access_denied is True:
                self.manager.current = 'login'
                login_plz.open()
            else:
                for i in range(10):
                    src = "http://placehold.it/480x270.png&text=slide-%d&.png" % i
                    image = AsyncImage(source=src, allow_stretch=True, keep_ratio=False, opacity=1, size_hint=(1, 1.3),
                                       pos_hint={'center_x': 0.5, 'center_y': 0.75}, border=True)
                    self.ids.carousel.add_widget(image)
    
    class ImageButton(ButtonBehavior, Image):
        text = StringProperty()
    
    
    
    
    class ScreenChats(Screen):
    
        def get_user_chat(self):
            self.manager.current = 'match'
    
    
        def on_enter(self, *args):
            if App.get_running_app().root.access_denied is True:
                self.manager.current = 'login'
                login_plz.open()
            else:
                for i in range(4):
                    btn = Factory.ImageButton(text='sometxt', source='Trifecta.png')
                    self.ids.chat_layout.add_widget(btn)
    
    
    class ScreenUserProfile(Screen):
        def on_enter(self, *args):
            if App.get_running_app().root.access_denied is True:
                self.manager.current = 'login'
                login_plz.open()
            else:
                pass
    
    
    class Manager(ScreenManager):
        screen_log_in = ObjectProperty(None)
        screen_near_user = ObjectProperty(None)
        screen_match = ObjectProperty(None)
        screen_chats = ObjectProperty(None)
        screen_user_profile = ObjectProperty(None)
    
    
    class MenuApp(App):
    
        def build(self):
            return Menu()
    
        def on_start(self):
            self.current_screen = 'login'
    
    
    if __name__ == '__main__':
        MenuApp().run()
    

    Kv:

    <Menu>:
        manager: screen_manager
        orientation: "vertical"
        id: action
    
        ActionBar:
            size_hint_y: 0.1
            background_color: 0, 0, 1000, 10
            background_normal: ""
            ActionView:
                ActionPrevious:
                    app_icon:""
                    with_previous: False
    
                    text:"    [b]Dhobiwala.com[/b]"
    
                    markup:True
                    font_size:"16dp"
                ActionButton:
                    id: near_users
                    size_hint: 1, 1
                    height: self.texture_size[ 1 ]
                    width: self.texture_size[ 0 ] + 40
                    minimum_width: self.texture_size[ 0 ] + 60
    
                    halign: "center"
                    icon: 'icons/internet.png'
                    disabled: True if root.access_denied else False
                    on_press: root.manager.current = 'near_users'
                ActionButton:
                    id: matching_bar
                    size_hint: 1, 1
    
                    height: self.texture_size[ 1 ]
                    width: self.texture_size[ 0 ] + 40
                    minimum_width: -self.texture_size[ 0 ] + 60
                    halign: "center"
                    text: "Matching"
                    disabled: True if root.access_denied else False
                    on_press: root.manager.current= 'match'
                ActionButton:
                    id: chat
                    size_hint: 1, 1
    
                    height: self.texture_size[ 1 ]
                    width: self.texture_size[ 0 ] + 40
                    minimum_width: self.texture_size[ 0 ] + 60
    
                    halign: "center"
                    text: "chat"
                    disabled: True if root.access_denied else False
                    on_press: root.manager.current = 'chats'
                ActionButton:
                    id: profile
                    size_hint: 1, 1
    
                    height: self.texture_size[ 1 ]
                    width: self.texture_size[ 0 ] + 40
                    minimum_width: self.texture_size[ 0 ] + 60
    
                    halign: "center"
                    text: "Profile"
                    disabled: True if root.access_denied else False
                    on_press: root.manager.current = 'profile'
        Manager:
            id: screen_manager
    
    <ScreenLogIn>:
        id: login_screen
        BoxLayout:
            orientation: "vertical"
            padding: 20, 20
            spacing: 50
            TextInput:
                id: login
                size_hint_y: None
    
                multiline: False
            TextInput:
                id: passw
                size_hint_y: None
                multiline: False
                password: True # hide password
            Button:
                text: "Log In"
                on_release: root.verify_credentials()
    
    <ScreenNearUsers>:
        ScrollView:
            GridLayout:
                id: grid
                size_hint_y: None
                height: self.minimum_height
                cols: 2
                row_default_height: '20dp'
                row_force_default: True
                spacing: 0, 0
                padding: 0, 0
    
    
    
    <ScreenMatch>:
        name: 'Carousel'
        fullscreen: True
    
    
    
        BoxLayout:
            size_hint_y: None
            height: '48dp'
    
            Button:
    
                text: 'last user'
                id: last_user
    
            Button:
    
                text: 'like'
    
            Button:
                text: 'super like'
                on_release: carousel.load_previous()
    
            Button:
                text: 'Dislike'
                on_release: carousel.load_next()
    
    
        AnchorLayout:
            anchor_x: 'center'
            anchor_y: 'center'
    
    
    
    
        Carousel:
    
            id: carousel
            loop: last_user.state == 'down'
    
    <ImageButton>:
        size_hint: None, None
        size: 200, 200
        text: ''
        Label:
        Label:
            text: root.text
            pos: root.x - -75, root.y - 0
            size: root.size
    
    <ScreenChats>:
    
    
        ScrollView:
    
            GridLayout:
                id: chat_layout
                size_hint_y: None
                height: self.minimum_height
                cols: 1
                row_default_height: '125dp'
                row_force_default: True
                spacing: 0, 0
                padding: 0, 0
    
    
    
    
    <ScreenUserProfile>:
    
        Button:
            text: "stuff4"
    
    <Manager>:
        id: screen_manager
        screen_log_in: screen_log_in
        screen_near_users: screen_near_users
        screen_match: screen_match
        screen_chats: screen_chats
        screen_user_profile: screen_user_profile
    
        ScreenLogIn:
            id: screen_log_in
            name: 'login'
            manager: screen_manager
        ScreenNearUsers:
            id: screen_near_users
            name: 'near_users'
            manager: screen_manager
        ScreenMatch:
            id: screen_match
            name: 'match'
            manager: screen_manager
        ScreenChats:
            id: screen_chats
            name: 'chats'
            manager: screen_manager
        ScreenUserProfile:
            id: screen_user_profile
            name: 'profile'
            manger: screen_manager
    

    【讨论】:

      猜你喜欢
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 2016-05-24
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多