Kivy画布小部件绘制在按钮上方

2 投票
1 回答
2476 浏览
提问于 2025-05-10 15:05

这是来自马克·瓦西尔科夫的书《Kivy蓝图》的一个例子。这个例子可以运行,但在绘图的时候,线条会覆盖到按钮上。请帮忙解决这个问题。

...   
class CanvasWidget(Widget):  

def on_touch_down(self, touch):
    if Widget.on_touch_down(self, touch):
        return True
    print(touch.x, touch.y)
    with self.canvas:
        Color(*get_color_from_hex('#0080FF80'))
        Line(circle=(touch.x, touch.y, 2), width=2)
        touch.ud['current_line'] = Line(points=(touch.x, touch.y), width=2)     

def on_touch_move(self, touch):                               
    if 'current_line' in touch.ud:
        touch.ud['current_line'].points += (touch.x, touch.y)

def set_color(self, new_color):
    self.canvas.add(Color(*new_color))    

def clear_canvas(self):        
    self.canvas.clear()
    saved = self.children[:]
    self.clear_widgets()        
    for widget in saved:
        self.add_widget(widget)

class PaintApp(App):

def build(self):
    self.canvas_widget = CanvasWidget()
    self.canvas_widget.set_color(get_color_from_hex('#2980B9'))
    return self.canvas_widget

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

Kv文件中的“清除”按钮和“颜色按钮”。

<CanvasWidget>:
Button:  
on_release: root.clear_canvas()
text: 'Clear'
...
<ColorButton@RadioButton>:
on_release: app.canvas_widget.set_color(self.background_color)
...

相关文章:

  • 暂无相关问题
暂无标签

1 个回答

2

canvas.before 替代 canvas

...
def on_touch_down(self, touch):
    if Widget.on_touch_down(self, touch):
        return True
    print(touch.x, touch.y)
    with self.canvas.before:
        Color(*get_color_from_hex('#0080FF80'))
        Line(circle=(touch.x, touch.y, 2), width=2)
        touch.ud['current_line'] = Line(points=(touch.x, touch.y), width=2)
...

撰写回答