【问题标题】:Kivy Color Change with Button带按钮的 Kivy 颜色更改
【发布时间】:2015-05-27 21:26:09
【问题描述】:

我目前正在使用 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"

【问题讨论】:

    标签: python colors kivy


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      你应该尽量减少代码长度,在这种情况下你不需要使用任何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]
      

      【讨论】:

      • 谢谢。那行得通!现在,如果您再次按下按钮,我正在尝试将颜色改回来。我尝试了一个条件,如果 self.color 是一种颜色并且你按下按钮,它会切换到另一种颜色,如果 self.color 是另一种颜色并且你按下按钮,它会切换回第一种颜色,但是有条件不工作。我知道我的语法正确,并且没有收到任何错误消息。不知道怎么回事……
      • if self.ids.p.color == [1,0,0,1]: self.ids.p.color = [1,1,0,1] else: self.ids.p.color = [1,0,0,1] 如果按钮是 id
      猜你喜欢
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多