Киви: Могу ли я свободно изменить положение текста внутри кнопки? и добавить еще один текст в кнопку? - PullRequest
0 голосов
/ 25 августа 2018

t3.py

#-*- coding: utf-8 -*-
__version__ = "1.0"

import kivy
import os
kivy.require('1.10.0')
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.core.window import Window 
Window.size = (540, 960)

class StationTest(Screen):

    def __init__(self, **kwargs):
        super(StationTest, self).__init__(**kwargs)


class ScreenManagement(ScreenManager):
    pass

presentation = Builder.load_file("t3.kv")

class Test2App(App):
    def build(self):
        return presentation


Test2App().run()

t3.kv

# -*- coding: utf-8 -*-
#:kivy 1.10.0
#:import NoTransition kivy.uix.screenmanager.NoTransition
#:import SlideTransition kivy.uix.screenmanager.SlideTransition
#:import Button kivy.uix.button.Button

ScreenManagement:
    transition: SlideTransition(direction='left')
    StationTest:

<StationTest>: 
    name: 'StationTest'
    canvas:
        Rectangle:
            pos: self.pos
            size: self.size 
            source: 'image/background.png' #backgroundimage
    header: _header
    ScrollView:
        FloatLayout:
            size_hint_y: None
            height: 500
            BoxLayout:
                id: _header
                orientation: 'vertical'
                size_hint: 1, 0.10
                pos_hint: {'top': 1.0}
                anchor: _anchor
                canvas:
                    Color:              
                        rgba: 0.8, 0.6, 0.4, 1.0
                    Rectangle:
                        pos: self.pos
                        size: self.size
                Label:
                    text: "STATION > STATION"
                    font_size: 40
                BoxLayout
                    id: _anchor
                    size_hint_y: 0.3
                    canvas.before:
                        Color:              
                            rgba: 0.3, 0.5, 0.8, 1.0
                        Rectangle:
                            pos: self.pos
                            size: self.size
                    Label:
                        text: "TEST1234"

            BoxLayout:
                orientation: 'vertical'
                #size_hint: 1, 0.35
                size: 1,0.35
                spacing: 10
                pos_hint:{"center_x":0.5,"y":-0.6}
                padding: 0, -200, 0, 0
    GridLayout:
        cols: 1
        rows: 10
        spacing: 0
        padding: [0,100]
        on_parent:
            for i in range(10): txt = 'abcdef'; self.add_widget(Button(text = txt, text_size=(cm(2), cm(2)), background_color=(255,255,255,1),
            pos=self.pos, id=txt, color=(0,0,0,1))) # 0~1.0

Я хочу добавить текст «123456» отдельно от «abcdef» в одну кнопку.я могу кодировать txt = 'abcdef' + '123456' но это не то, что я хотелЯ хотел бы добавить тексты в кнопку и применить нужные параметры к каждому тексту, но это нелегко.

on_parent:
    for i in range(10): txt = 'abcdef'; self.add_widget(Button(text = txt, text_size=(cm(2), cm(2)), background_color=(255,255,255,1),
    pos=self.pos, id=txt, color=(0,0,0,1))) # 0~1.0

Поэтому у меня есть два вопроса.

1.Могу ли япоместить два текста, которые могут перемещаться независимо, в одну кнопку?

2. Можно ли свободно установить положение текста внутри кнопки?

1 Ответ

0 голосов
/ 11 сентября 2018
  1. Могу ли я поместить две надписи, которые могут двигаться независимо, в одну кнопку? Нет, вы не можете
  2. Можно ли свободно установить положение текста внутри кнопки? Нет, вы не можете

Решение

Создание пользовательской кнопки с наследованием ButtonBehavior и BoxLayout . Внутри BoxLayout есть три Label виджета.

Отрывок

<CustomLabel@Label>:
    text_size: root.width, None
    size: self.texture_size
    valign: 'center'
    halign: 'right'

<CustomButton>:
    color: 0, 0, 0, 1    # black color text

    orientation: 'vertical'
    canvas.before:
        Rectangle:
            size: self.size
            pos: self.pos

    size_hint: 1, None
    height: 60
    padding: 5, 5, 5, 5

    background_color: [0.50196, 0.50196, 0.50196, 1] if self.state == 'normal' else [0, 1, 1, 1]

    AnchorLayout:
        canvas.before:
            Color:
                rgba: [1, 1, 1, 1] if root.background_color is None else root.background_color
            Rectangle:
                size: self.size
                pos: self.pos

        AnchorLayout:
            anchor_x: 'left'
            anchor_y: 'top'
            CustomLabel:
                text: root.route
                color: root.color
                halign: 'left'

        AnchorLayout:
            anchor_x: 'right'
            anchor_y: 'top'
            CustomLabel:
                text: root.stations
                color: root.color

    AnchorLayout:
        canvas.before:
            Color:
                rgba: [1, 1, 1, 1] if root.background_color is None else root.background_color
            Rectangle:
                size: self.size
                pos: self.pos
        anchor_x: 'right'
        anchor_y: 'bottom'

        CustomLabel:
            text: root.commute
            color: root.color
* +1025 * Пример

main.py

#-*- coding: utf-8 -*-
__version__ = "1.0"

import os
import kivy
kivy.require('1.11.0')

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window
Window.size = (540, 960)

from kivy.uix.button import ButtonBehavior
from kivy.properties import StringProperty


def oopath(ndid, uor):
    path = os.path.join(os.path.dirname(__file__), ndid + '.txt')
    return path

##############################################################################################################


class StationTest(Screen):

    def __init__(self, **kwargs):
        super(StationTest, self).__init__(**kwargs)

        oo = oopath('TESTTEST', 0)
        self.rpandgv(oo)

    def rpandgv(self, path):
        with open(path) as businfo:
            Businfo = []
            for line in businfo:
                Businfo.append(line.rstrip())

        self.businfolist = Businfo
        self.lenbil = int(len(Businfo))
        self.numberoflist = int(len(Businfo)/3)

    def populate_businfo(self, instance):
        for x in range(0, self.lenbil, 3):
            instance.add_widget(CustomButton(route=self.businfolist[x], stations=self.businfolist[x+1], commute=self.businfolist[x+2]))


class ScreenManagement(ScreenManager):
    pass


class CustomButton(ButtonBehavior, BoxLayout):
    route = StringProperty('')
    stations = StringProperty('')
    commute = StringProperty('')

    def on_release(self):
        print("\troute={0}, stations={1}, commute={2}".format(self.route, self.stations, self.commute))


presentation = Builder.load_file("test.kv")


class Test2App(App):
    def build(self):
        return presentation


Test2App().run()

test.kv

# -*- coding: utf-8 -*-
#:kivy 1.11.0
#:import NoTransition kivy.uix.screenmanager.NoTransition
#:import SlideTransition kivy.uix.screenmanager.SlideTransition
#:import Button kivy.uix.button.Button

ScreenManagement:
    transition: SlideTransition(direction='left')
    StationTest:

<StationTest>:
    name: 'StationTest'
    canvas:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'image/background.png' #backgroundimage

    header: _header

    ScrollView:
        FloatLayout:
            size_hint_y: None
            height: 500
            BoxLayout:
                id: _header
                orientation: 'vertical'
                size_hint: 1, 0.10
                pos_hint: {'top': 1.0}
                anchor: _anchor
                canvas:
                    Color:
                        rgba: 0.8, 0.6, 0.4, 1.0
                    Rectangle:
                        pos: self.pos
                        size: self.size
                Label:
                    text: "STATION > STATION"
                    font_size: 40
                BoxLayout
                    id: _anchor
                    size_hint_y: 0.3
                    canvas.before:
                        Color:
                            rgba: 0.3, 0.5, 0.8, 1.0
                        Rectangle:
                            pos: self.pos
                            size: self.size
                    Label:
                        text: "TEST1234"

            BoxLayout:
                orientation: 'vertical'
                #size_hint: 1, 0.35
                size: 1,0.35
                spacing: 10
                pos_hint:{"center_x":0.5,"y":-0.6}
                padding: 0, -200, 0, 0

    GridLayout:
        cols: 1
        rows: 10
        spacing: 0
        padding: [0,100]
        on_parent:
            root.populate_businfo(self)


<CustomLabel@Label>:
    text_size: root.width, None
    size: self.texture_size
    valign: 'center'
    halign: 'right'

<CustomButton>:
    color: 0, 0, 0, 1    # black color text

    orientation: 'vertical'
    canvas.before:
        Rectangle:
            size: self.size
            pos: self.pos

    size_hint: 1, None
    height: 60
    padding: 5, 5, 5, 5

    background_color: [0.50196, 0.50196, 0.50196, 1] if self.state == 'normal' else [0, 1, 1, 1]

    AnchorLayout:
        canvas.before:
            Color:
                rgba: [1, 1, 1, 1] if root.background_color is None else root.background_color
            Rectangle:
                size: self.size
                pos: self.pos

        AnchorLayout:
            anchor_x: 'left'
            anchor_y: 'top'
            CustomLabel:
                text: root.route
                color: root.color
                halign: 'left'

        AnchorLayout:
            anchor_x: 'right'
            anchor_y: 'top'
            CustomLabel:
                text: root.stations
                color: root.color

    AnchorLayout:
        canvas.before:
            Color:
                rgba: [1, 1, 1, 1] if root.background_color is None else root.background_color
            Rectangle:
                size: self.size
                pos: self.pos
        anchor_x: 'right'
        anchor_y: 'bottom'

        CustomLabel:
            text: root.commute
            color: root.color

выход

Img01 Img02

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...