繁体   English   中英

纽扣颜色变化

[英]Kivy Color Change with Button

我目前正在使用Kivy和Python编写一些代码。 我正在尝试这样做,因此当您单击按钮时,按钮的文本会更改颜色。

但是,当我单击该按钮时,颜色并不像我想要的那样。

任何想法如何解决? 我只是在学习Kivy,答案可能比我想的要容易。 .py文件在下面

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.uix.button import Button
from kivy.graphics import Color
class TextBubbleSample(Widget):
    bubble = ObjectProperty(None)

class TextBubble(Widget):
        pass

class Talk(Button):
    btn = Button
    def button_press(self):
        btn.bind(on_state = self.on_event)

def on_event(self):
        btn.color = 1,0,0,1

class TextBubbleApp(App):
    def build(self):
        return TextBubbleSample()

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




and here is the .kv file

#:kivy 1.0.9

<TextBubbleSample>:
    bubble: text_bubble
    btn: click_here

    TextBubble:
        id: text_bubble
        x: root.x
        center_y: root.center_y

    Talk:
        id: click_here
        x: 10
        center_y: 220
        text: "Talk to me."
        color: 0,0,1,1

<TextBubble>:
    canvas:
        Color:
            rgba: 1,0,0,1
        Rectangle:
            pos: 10, 10
            size: 780, 150

    Label:
        color: 0,0,1,1
        font_size: 35  
        center_x: 200
        top: root.top - 200
        text: "I am talking"

你不应该那样使用btn变量。 使用self.bind(on_state=self.on_event)然后self.color = (1, 0, 0, 1)

您应尝试减少代码长度,在这种情况下无需使用任何ID。

可能会有一个简单的替代方案来代替inclement的答案。 在您的.py文件(Talk类)中添加。

class Talk(Button):
....
def on_release(self):
    self.color = 1,0,0,1

并在您的.kv文件中添加

Talk:
    text: "talk to me"
    ....
    on_release: self.on_release

编辑:

你也可以这样

class Singularity(BoxLayout):
    def __init__(self,**kwargs):
        super(Singularity,self).__init__(**kwargs)
        self.b = Button(text = "hello",on_press = self.on_press)
        self.add_widget(self.b)
    def on_press(self,event):
        if event.color == [1,0,0,1]:
            event.color = [0,0,1,1]
        else:
            event.color=[1,0,0,1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM