gpt4 book ai didi

python - 如何为 python kivy 绘画应用程序添加一个清除按钮

转载 作者:太空宇宙 更新时间:2023-11-04 08:42:01 25 4
gpt4 key购买 nike

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

在 .kv 文件中,我想我需要修改 #on_release:root.canvas.clear()部分代码,目前它删除了整个 Canvas 和按钮。我正在想办法让它只清除屏幕,允许再次在屏幕上重绘,并且不会删除按钮。

这是上下文图片 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}

最佳答案

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

问题出在 .kv 中的第 34 行文件:on_release: root.canvas.clear() . root指的是FloatLayout .因此,您正在清除 FloatLayout 上的所有内容包括按钮。您需要清除的是 Painter小部件的 Canvas 。添加 id给你的Painter并清除它的 Canvas :

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}

关于python - 如何为 python kivy 绘画应用程序添加一个清除按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44106801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com