ll2*_*2ll 1 python canvas button kivy kivy-language
我正在使用python和kivy构建一个基本的绘画应用程序,以学习应用程序开发。我试图弄清楚如何在屏幕上绘制后通过修改.kv文件上的代码来清除画布。
在.kv文件中,我认为我需要修改代码的#on_release:root.canvas.clear()部分,当前它删除了整个画布和按钮。我试图弄清楚如何制作它,使其仅清除屏幕,允许再次在屏幕上重画,而不擦除按钮。
这是上下文画家应用程序的图片
按下清除按钮空白屏幕后会发生什么
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()
Run Code Online (Sandbox Code Playgroud)
以下是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}
Run Code Online (Sandbox Code Playgroud)
小智 5
我假设您提供的代码只是代码库的一部分。我遇到了一些我想清除的错误:第10行之后没有缩进Painter def on_touch_down,我对10-17行缩进了一次。在该.kv文件中,有两个kivy小部件被视为根小部件(只能是一个)。我在第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}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
711 次 |
| 最近记录: |