gpt4 book ai didi

python - 如何使 on_touch_down 小部件特定?

转载 作者:行者123 更新时间:2023-12-01 16:13:20 25 4
gpt4 key购买 nike

我正在尝试在 kivy 中创建一个简单的绘图应用程序,但我遇到了一些问题

on_touch_down

函数涉及整个类,而不仅仅是特定的小部件。因此,当我使用触碰和触碰移动功能在 Canvas 上绘图时,它会影响并有效禁用绑定(bind)到按钮的触碰功能。这是按钮不起作用的代码。

Python 代码:

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.graphics import Line
from kivy.graphics import *
from kivy.uix.widget import Widget
class MyScreenManager(ScreenManager):
pass

class MenuScreen(Screen):
pass

class DrawScreen(Screen):
def on_touch_down(self, touch):
with self.canvas.before:
Color(1, 0, 0)
touch.ud["line"] = Line(points=(touch.x, touch.y), width=5)

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



class DrawApp(App):
def build(self):
return MyScreenManager()

DrawApp().run()

基维代码:

<MenuButton@Button>:
font_size: 65
size_hint: 0.4, 0.25

<MyScreenManager>:
MenuScreen:
id: menu
name: "menu"

DrawScreen:
id: draw
name: "draw"

<MenuScreen>:
canvas.before:
Color:
rgba: 1,1,1,1
Rectangle:
size: self.size
pos: self.pos

MenuButton:
text: "Draw"
on_release: root.manager.current = "draw"
pos_hint:{"center_x":0.5, "center_y":0.6}
MenuButton:
text: "Quit"
on_release: app.stop()
pos_hint:{"center_x":0.5, "center_y":0.3}

<DrawScreen>:
canvas.before:
Color:
rgba: 1,1,1,1
Rectangle:
size: self.size
pos: self.pos


Button:
id: but
size_hint: 0.2,0.1
pos_hint_x: 0 + self.width
font_size: 30
text: "Back"
on_release: root.manager.current = "menu"

我设法使用 collide_point 找到了一个简单的解决方法,这是我的解决方法代码:

class DrawScreen(Screen):
def on_touch_down(self, touch):
but = self.ids.but
if but.collide_point(touch.x, touch.y):
self.manager.current = "menu"

else:
with self.canvas.before:
Color(1, 0, 0)
touch.ud["line"] = Line(points=(touch.x, touch.y), width=5)

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

但是,虽然这有效,但它带来了一系列新问题,例如我必须手动配置每个按钮以在按住时更改源,并且在释放按钮之前该功能不会运行。这也意味着我添加到类中的所有内容都必须添加到 if 语句中。

我非常肯定必须有一种更简单的方法。我的第一个想法是,也许可以添加 on touch down 以仅影响一个小部件?我的第二个想法是,也许不要在 Canvas 上画画或其他东西会更好吗?

感谢任何帮助或指点,谢谢!

最佳答案

当你覆盖一个方法时,你必须返回父类(super class)的相同方法

像这样:

...

class DrawScreen(Screen):
def on_touch_down(self, touch):
with self.canvas.before:
Color(1, 0, 0)
touch.ud["line"] = Line(points=(touch.x, touch.y), width=5)
return super(DrawScreen, self).on_touch_down(touch)

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

关于python - 如何使 on_touch_down 小部件特定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47662872/

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