Kivy无法使用ButtonBehavior向按钮添加文本

时间:2018-08-21 12:05:42

标签: python python-2.7 kivy kivy-language

我想在圆形图像的右侧添加文本。有人告诉我使用标签来执行此操作,但是我不知道如何实际执行此操作。它必须是动态的,所以如果您必须使用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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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