【问题标题】:Adding on_release action to buttons in loop将 on_release 操作添加到循环中的按钮
【发布时间】:2019-05-01 00:23:15
【问题描述】:
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]))

我的 .kv 文件:

<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】:

    on_release 事件添加到Button 小部件。

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

    注意事项

    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
    

    解决方案

    因此,您想定义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}")
    

    输出

    【讨论】:

      猜你喜欢
      • 2012-09-23
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 2015-06-29
      • 2017-12-04
      相关资源
      最近更新 更多