[英]How to update the on_touch_move and on_touch_down methods of a Widget in kivy
[英]How do I make on_touch_down widget specific?
我正在嘗試在kivy中創建一個簡單的繪圖應用程序,但我遇到了一些問題
on_touch_down
因為它關注整個類,而不僅僅是一個特定的小部件。 因此,當我使用觸摸向下和觸摸移動功能在畫布上繪制時,它會影響並有效地禁用綁定到按鈕的觸摸功能。 這是按鈕不起作用的代碼。
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()
kivy代碼:
<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語句中。
我非常肯定必須有一個更簡單的方法。 我的第一個想法是,也許有人可以添加觸摸下來只影響一個小部件? 我的第二個想法是,如果不畫畫布或其他東西會更好嗎?
任何幫助或指示表示贊賞,謝謝!
覆蓋方法時,必須返回超類的相同方法
這樣的事情:
...
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.