如何为python kivy绘画应用添加一个清晰的按钮

时间:2017-05-22 07:17:32

标签: python button canvas kivy kivy-language

我正在使用python和kivy构建一个基本的绘画应用程序来学习应用程序开发。我试图弄清楚如何通过修改.kv文件上的代码在屏幕上绘图后清除画布。

在.kv文件中我想我需要修改#on_release:root.canvas.clear() 部分代码,目前它删除整个画布和按钮。我试图弄清楚如何制作它只是清除屏幕,允许再次在屏幕上重绘,并且不会删除按钮。

下面是上下文的图片 Painter App

按下清除按钮后会发生什么 Blank Screen

from random import random
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.widget import Widget
from kivy.graphics import Line, Color, Ellipse

class Painter(Widget):
    def on_touch_down(self, touch):
    color = (random(), 1.,1.) #reduce number of possible colors
    with self.canvas:
        Color(*color, mode='hsv') #sets the colors to be equally bright
        d = 30.
        Ellipse(pos=(touch.x - d / 2,touch.y - d / 2), size=(d,d))
        touch.ud["line"] = Line(points=(touch.x, touch.y))


def on_touch_move(self, touch):
    touch.ud["line"].points += [touch.x, touch.y]

class MainScreen(Screen):
    pass

class AnotherScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

presentation = Builder.load_file("main3.kv") #load the kivy file

class SimpleKivy7(App):
    def build(self):
        return presentation

if __name__== "__main__":
    SimpleKivy7().run()
以下是kivy文件
#: import FadeTransition kivy.uix.screenmanager.FadeTransition

ScreenManagement:
    transition: FadeTransition()
    MainScreen:
    AnotherScreen:

<MainScreen>:
    name: "main"
    Button:
        on_release: app.root.current = "other"
        text: "Next Screen"
        font_size: 50

<AnotherScreen>:
    name: "other"

FloatLayout:
    Painter
    Button:
        color:0,1,0,1
        font_size: 25
        size_hint: 0.3, 0.2
        text: "Back Home"
        on_release: app.root.current = "main"
        pos_hint: {"right":1, "top":1}

    Button:
        color:0,1,0,1
        font_size: 25
        size_hint: 0.3, 0.2
        text: "Clear"
        #on_release:root.canvas.clear() #root.canvas.clear() clears everything. 
        pos_hint: {"left":1, "top":1}

1 个答案:

答案 0 :(得分:4)

我认为您提供的代码只是代码库的一部分。我遇到了一些我想要澄清的错误:在Painter def on_touch_down之后第10行没有缩进,我在第10-17行缩进一次。在.kv文件中有两个小部件被视为根小部件(只能有一个小部件)。我在第3行的屏幕管理员<周围添加了>ScreenManagement。我很遗憾地说,在我的情况下,该应用仅绘制圆圈,而不是后面的线条。

问题出在.kv文件的第34行:on_release: root.canvas.clear()root引用FloatLayout。因此,您要清除FloatLayout上的所有内容,包括按钮。您需要清除的是Painter小部件的画布。在id添加Painter并改为清除其画布:

FloatLayout:
    Painter:
        id: painter # an id for referring to this widget
    Button:
        color:0,1,0,1
        font_size: 25
        size_hint: 0.3, 0.2
        text: "Back Home"
        on_release: app.root.current = "main"
        pos_hint: {"right":1, "top":1}

    Button:
        color:0,1,0,1
        font_size: 25
        size_hint: 0.3, 0.2
        text: "Clear"
        on_release:  painter.canvas.clear() # clear the Painter's canvas
        pos_hint: {"left":1, "top":1}