Kivy Labels在触摸其中一个标签时都会一起行动



我是一个初学者,试图用kivy制作数独游戏。我创建了自己的 Button 类,该类继承自 Kivy 的 Button 类,因此我可以定义所有标签共有的属性,但我遇到了一个问题,如果我按下其中一个标签,它们都会一起起作用。

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label

class SudokuLabel(Label):
# Define colors
bg_color = (250 / 255, 250 / 255, 250 / 255)
font_color = (200 / 255, 200 / 255, 200 / 255)
touch_bg_color = (58 / 255, 110 / 255, 223 / 255, 0.9)
touch_font_color = (250 / 255, 250 / 255, 250 / 255)
value = ""
def __init__(self, value, **kwargs):
super(SudokuLabel, self).__init__(**kwargs)
self.value = value
self.color = self.font_color
self.font_size = 32
self.size_hint = 1/10, 1/18  # Grid fills 90% of screen horizontally, and 50% vertically

def on_touch_down(self, touch):
self.color = self.touch_font_color
def on_touch_up(self, touch):
self.color = self.font_color
def __repr__(self):
return str(self.value)

我怀疑问题出在我从 Label 类继承的方式上,所以我制作了另一个类来继承"SudokuLabel",我在其中定义了"one_touch_down"方法,但这不起作用。任何帮助,不胜感激。

另外,我没有使用 .kv 文件,因为我正在 for 循环中创建数独表标签,我不知道我是否可以使用 kv 语言做到这一点。因此,如果您有 python 响应,请提供 python 响应。

您需要检查碰撞。

def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
self.color = self.touch_font_color
return True

最新更新