如何在kivy python中动态更改画布颜色?

2024-06-16 11:50:57 发布

您现在位置:Python中文网/ 问答频道 /正文

目的是改变颜色的笔在kivy当用户按下按钮。那个颜色将更改为按钮的背景颜色。代码画布:

def on_touch_move(self,color,touch):
    with self.pc.canvas:
        global wtd,pencolor
        Color(pencolor)
        if wtd == 1:
            Ellipse(pos=(touch.x,touch.y),size=(penrad,penrad))

按“绑定到”按钮的代码:

^{pr2}$

按钮事件正常工作!在


Tags: 代码用户self目的颜色ondef画布
1条回答
网友
1楼 · 发布于 2024-06-16 11:50:57

解决方案

提供颜色的模式(rgb,rgba)。将颜色(铅笔色)替换为颜色(rgba=pencolor)

详情请参考下面的演示。笔的颜色从红色开始变为白色,即按钮的背景色。在

示例

在主.py在

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ListProperty, NumericProperty
from kivy.graphics import *


class MyWidget(Widget):
    wtd = NumericProperty(1)
    penrad = NumericProperty(10)
    pencolor = ListProperty([1, 0, 0, 1])  # Red

    def newclr(self, instance):
        print("Before Change@newclr: pencolor=", self.pencolor)
        self.pencolor = instance.background_color
        print("After Change@newclr: pencolor=", self.pencolor)

    def on_touch_move(self, touch):
        print("on_touch_move: touch=", touch)
        print("on_touch_move: pencolor=", self.pencolor)
        with self.canvas:
            Color(rgba=self.pencolor)
            if self.wtd == 1:
                Ellipse(pos=(touch.x, touch.y), size=(self.penrad, self.penrad))


class TestApp(App):
    title = "Kivy - Change Pen Colour"

    def build(self):
        return MyWidget()


if __name__ == "__main__":
    TestApp().run()

在试验电压在

^{pr2}$

输出

Img01 - App StartupImg02 - Red PenImg03 - White Pen After Clicked Button

相关问题 更多 >