将on_release动作添加到循环中的按钮

问题描述 投票:0回答:1
class WidgetFiscal(Screen):
    box = ObjectProperty(None)

    def on_box(self, *args):
        fiscal = ['Elzab Mera TE FV', 'Posnet Thermal XL', 'Posnet HD', 'Elzab Sigma', 'Novitus Delio Prime E', 'Elzab D10', 'Posnet Trio', 'Epson TM-T801FV']
        for i in fiscal:
            self.box.add_widget(Button(text=str(i), background_color=[1,2,1,1]))

我们.k圆角:

<FiscalPrinter>:
    name: 'fiscal_printer'

    BoxLayout:
        size: root.size
        spacing: 20
        padding: 10,10,10,10
        orientation: 'vertical'

        Label:
            text: 'Choose fiscal printer which you want to rent'
            size: root.width, root.height / 10
            size_hint: None, None

        WidgetFiscal:

        Button:
            text: 'GO BACK'
            size: root.width, root.height / 10
            size_hint: None, None
            on_release: app.root.current = "rent_device"

<WidgetFiscal>:
    box: box

    GridLayout:
        background_color: 1,2,1,1
        cols: 3
        id: box
python python-3.x kivy kivy-language
1个回答
1
投票

on_release事件添加到Button小部件。

self.box.add_widget(Button(..., on_release=self.mycallback))

Notes

Kivy » Touch event basics

默认情况下,会将触摸事件分派给所有当前显示的窗口小部件。这意味着小部件接收触摸事件,无论它是否发生在其物理区域内。

...

为了提供最大的灵活性,Kivy将事件分派给所有小部件,并让他们决定如何对它们做出反应。如果您只想响应窗口小部件中的触摸事件,只需检查:

def on_touch_down(self, touch):
    if self.collide_point(*touch.pos):
        # The touch has occurred inside the widgets area. Do stuff!
        pass

Solution

因此,您希望使用class PrinterButton小部件的继承来定义Button并实现on_touch_down方法,以仅响应触及的Button的触摸事件。

片段

class PrinterButton(Button):
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            print(f"\nPrinterButton.on_touch_down: text={self.text}")
            self.dispatch('on_release')
            return True    # consumed on_touch_down & stop propagation / bubbling
        return super(PrinterButton, self).on_touch_down(touch)

class WidgetFiscal(Screen): 
    box = ObjectProperty(None)

    def on_box(self, *args):
        fiscal = ['Elzab Mera TE FV', 'Posnet Thermal XL', 'Posnet HD', 'Elzab Sigma', 'Novitus Delio Prime E', 'Elzab D10', 'Posnet Trio', 'Epson TM-T801FV']
        for i in fiscal:
            self.box.add_widget(PrinterButton(text=str(i), background_color=[1,2,1,1], on_release=self.mycallback))

    def mycallback(self, instance):
        print(f"mycallback: Button.text={instance.text}")

Output

Result

© www.soinside.com 2019 - 2024. All rights reserved.