首页 > 解决方案 > 交替画布颜色 Kivy/kv

问题描述

尝试为我添加的每个其他小部件实现替代颜色....就像一个深色和浅色的方法来更好地分离每个小部件。

如果我添加一个新的小部件,我想要颜色 (1, 0, 0, 1),当我添加另一个小部件时,它应该是 (0, 1, 0, 1)

这段代码复制了我的应用程序的一个非常简单的版本。在理解如何实现这一点时,我希望得到一些帮助。

谢谢

主文件

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.config import Config
from kivy.utils import get_color_from_hex
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.popup import Popup
from kivy.animation import Animation
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.colorpicker import ColorPicker
from kivy.properties import ObjectProperty
from kivy.uix.textinput import TextInput
from kivy.clock import Clock
from kivy.uix.widget import Widget
from kivy.properties import ListProperty

import json
import os
from time import strftime
import smtplib
from gmail import GMail, Message


class ScreenGenerator(ScreenManager):
    pass

class Trackers(Screen):
    data = 'data.json'
    storage = []
    path = ''

    #def on_pre_enter(self):
        #self.path = App.get_running_app().user_data_dir + '/'
        #self.loadData(self.data)
        #for dictionary in self.storage:
            #for k, v in dictionary.items():
                #self.ids.track.add_widget(Tracker(text=k, number=v, data=self.storage))

    def on_pre_leave(self):
        self.ids.track.clear_widgets()
        self.saveData(self.data)

    def loadData(self, data, *args):
        try:
            with open(self.path + data, 'r') as d:
                self.storage = json.load(d)
                print(self.storage, 'data loaded')
        except FileNotFoundError:
            pass

    def addWidget(self):
        box = BoxLayout(orientation= 'vertical', padding=10, spacing=15)
        pop = Popup(title='Tracker:', content=box, size_hint=(None,None), height=(self.width / 2), width=(self.width))

        text_input = TextInput(hint_text='Add Trackers', multiline=False, size_hint=(1, None), size=(self.width - 125, 65))
        okay = Button(text='Save', size_hint=(1, None), size=(self.width - 125, self.width / 8), on_press=lambda *args :self.addit(text_input.text), on_release=pop.dismiss)
        input_Len = Label(bold=True, halign="center", text="", size_hint=(1, 0.5))
        limit = Label(opacity=.3, halign="left", bold=True, text="Character Limit 35".upper(), size_hint=(1, 0.5))

        text_input.bind(text=lambda instance, text: setattr(input_Len, "text", str(len(text))))

        box.add_widget(limit)
        box.add_widget(input_Len)
        box.add_widget(text_input)
        box.add_widget(okay)
        pop.open()

    def addit(self, text_input, *args):
        keys = []
        for dictionary in self.storage:
            for k, v in dictionary.items():
                keys.append(k)

        if text_input not in keys:
            num = '0'
            self.ids.track.add_widget(Tracker(text=text_input, number=num, data=self.storage))
            self.storage.append({text_input: '0'})
        else:
            box = BoxLayout(orientation= 'vertical', padding=80, spacing=5)
            pop = Popup(title=f'Opps: "{text_input}" is already listed below', content=box, size_hint=(None,None), height=(self.width - self.width / 2), width=(self.width / 2))
            try_again = Button(text='Try Again', on_release=pop.dismiss)
            box.add_widget(try_again)
            pop.open()


class Tracker(BoxLayout):
    def __init__(self, text='', number='', data={}, **kwargs):
        super().__init__(**kwargs)
        self.ids.label.text = text
        self.ids.count_add.text = number

    def cor( self):
        return (1, 0, 0, 1)

    def corr(self):
        return (0, 1, 0, 1)


class Pess(App):
    def build(self):
        Config.set('graphics', 'width', '600')
        Config.set('graphics', 'height', '800')
        from kivy.core.window import Window
        Window.clearcolor = get_color_from_hex('#262829')

        return ScreenGenerator()


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

pess.kv

#:import rgba kivy.utils.get_color_from_hex
# encoding: utf-8

<Label>:
    font_size: '17dp'

<RoundButton@ButtonBehavior+Label>:
    canvas.before:
        Color:
            rgba: 0.8, 0.3, 0.1, 1
        Ellipse:
            pos: self.width / 2.265, self.y + 130
            size: self.height - self.height / 1.5, self.height / 3

<FloatButton@ButtonBehavior+FloatLayout>:
    id: float_root
    size_hint: (None, None)
    text: '[b]+[/b]'
    font_size: '48dp'
    btn_size: (140,140)
    size: (140,140)
    bg_color: (0.8, 0.3, 0.1, 1)
    pos_hint: {'x': 5.4, 'y': .17}
    Button:
        text: float_root.text
        font_size: '14dp'
        markup: True
        size_hint: (None, None)
        size: float_root.btn_size
        pos_hint: float_root.pos_hint
        background_normal: ''
        background_color: (0,1,0,0)
        canvas.before:
            Color:
                rgba: float_root.bg_color
            Ellipse:
                pos: self.pos
                size: self.size

<TrackerButton@Button>:
    background_color: 0,0,0,0

<ScreenGenerator>:
    Trackers:
        name: 'track'

<Trackers>:
    BoxLayout:
        orientation: 'vertical'
        ActionBar:
            height: self.minimum_height + dp(50)
            size_hint_y: None
            background_image: ''
            background_color: rgba('#ffffff') #rgba('#0B3242')
            ActionView:
                ActionPrevious:
                    title: '[b]TRACKERS[/b]'
                    font_size: '17dp'
                    color: rgba('#AFB7BA')
                    markup: True
                    on_release: app.root.current = 'pess'
        ScrollView:
            BoxLayout:
                id: track
                orientation: 'vertical'
                padding: 15
                spacing: 45
                size_hint_y: None
                height: self.minimum_height
        FloatLayout:
            size_hint_y: None
            height: 0
            Button:
                text: '+'
                font_size: '75dp'
                pos: self.width * 7.4, self.height + self.height / 2
                size_hint_y: None
                size_hint_x: None
                background_image: ''
                background_color: (0,0,0,0)
                on_release: root.addWidget()


<Tracker>:
    count_add: count_add
    name: name
    size_hint_y: None
    height: dp(73)

    canvas.before:
        Color:
            rgba: root.cor() or root.corr()
        Rectangle:
            pos: self.pos[0] + self.height/2, self.pos[1]
            size: self.size[0], self.height
        Ellipse:
            pos: self.pos[0], self.pos[1]
            size: self.height, self.height

    TrackerButton:
        text: '[b]X[/b]'
        markup: True
        size_hint_x: None
        width: 120

    Label:
        id: name
        canvas.before:
            Color: 
                rgba: (1,1,1,.7)
            Rectangle:
                size: self.size
                pos: self.pos
        size_hint_x: None
        width: 1

    TrackerButton:
        id: label
        font_size: '16dp'
        halign: 'left'
        text_size: 600, None
        #on_release: app.root.get_screen('track').change_name(root)

    TrackerButton:
        id: count_add
        font_size: '16dp'
        text: '0'
        size_hint_x: None
        width: 120
        #on_release: app.root.get_screen('track').add_num(root)

    Label:
        canvas.before:
            Color: 
                rgba: (1,1,1,.7)
            Rectangle:
                size: self.size
                pos: self.pos
        size_hint_x: None
        width: 1

    TrackerButton:
        text: '[b]-[/b]'
        font_size: '24dp'
        markup: True
        size_hint_x: None
        width: 120
        #on_release: app.root.get_screen('track').subtract_num(root)

标签: androidpython-3.xkivy

解决方案


您可以通过将 a 添加BooleanPropertyTracker类以及类级实例计数器来完成此操作:

class Tracker(BoxLayout):
    instance_count = 0  # class variable
    isEven = BooleanProperty(True)   # instance level Property

    def __init__(self, text='', number='', data={}, **kwargs):
        super().__init__(**kwargs)
        self.ids.label.text = text
        self.ids.count_add.text = number

        # set the BooleanProperty and increment the instance count
        self.isEven = Tracker.instance_count % 2 == 0
        Tracker.instance_count += 1

然后,在kv文件中,您可以根据以下内容选择颜色BooleanProperty

<Tracker>:
    count_add: count_add
    name: name
    size_hint_y: None
    height: dp(73)

    canvas.before:
        Color:
            rgba: root.cor() if self.isEven else root.corr()
        Rectangle:
            pos: self.pos[0] + self.height/2, self.pos[1]
            size: self.size[0], self.height
        Ellipse:
            pos: self.pos[0], self.pos[1]
            size: self.height, self.height

推荐阅读