Kivy 小部件比应有的大

Kivy widget is bigger than it should be

我试图通过自己的 coockie-clicker 制作,所以我创建了一个 kivy 小部件并将 coockie 的图像声明为其中的一部分。 每次单击 wiget 时,计数器都会上升,并且数字会显示在标签上。 一切顺利,在我得到关于堆栈溢出的帮助之后,但现在我面临的问题是宽度太大,所以即使我点击右上角,计数器上升,aldoug 我没有点击在饼干上。 这是源代码:

from kivy.app import App
from kivy.lang import Builder

from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.core.window import Window

from kivy.clock import Clock
from kivy.animation import Animation
from  kivy.core.text.markup import *

from kivy.uix.floatlayout import FloatLayout
from kivy.properties import NumericProperty
from kivy.properties import StringProperty

Builder.load_string('''
<Root>:

    Kecks:
        pos: 300, 300
        size: 100, 100
<Kecks>:

    Image:
        pos: root.pos
        id: my_image
        source: root.weg

    Label:
        id: my_Label
        font_size: 50
        text: root.txt
        center_x: 345
        center_y: 200       
''')

class Root(FloatLayout):
    def __init__(self, *args, **kwargs):
        super(Root, self).__init__(*args, **kwargs)

class Kecks(Widget):

    count = NumericProperty(0)
    amount = NumericProperty(1)
    txt = StringProperty()
    level = NumericProperty(1)
    weg = StringProperty('piernik.png')

    def __init__(self, *args, **kwargs):
        super(Kecks, self).__init__(*args, **kwargs)
        #self.txt = str(self.count)
        Clock.schedule_interval(self.Update, 1/60.)

    def Update(self, *args):
        self.txt = str(self.count)
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            self.count += self.amount


class app(App):
    def build(self):
        Window.clearcolor = (10, 0, 0, 1)
        return Root()

if __name__ == "__main__":
    app().run()

问题是您尚未定义 collide_points 您希望在哪个区域触发该事件。

考虑一下您是否希望 my_image 上的 collide_points 触发 on_touch_down事件,需要这样调整:

def on_touch_down(self, touch):
    # to check if touch.pos collides on my_image 
    if self.ids.my_image.collide_point(*touch.pos):
        self.count += self.amount

也许还可以考虑使用 pos_hint and size_hint,因为这将帮助您在不同设备(例如屏幕尺寸)中保持应用 运行 的一致性,而不是使用绝对尺寸 and/or位置。

希望对您有所帮助。