如何禁用Kivy中的小部件?

2024-04-25 20:02:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我读了Kivy的教程,但找不到如何禁用小部件(例如,按钮)。

def foo(self, instance, *args):
  #... main business logic, and then
  instance.disable = False
  # type(instance) = kivy.uix.Button

我将foofunctools.partial绑定。

正确的参数是什么?


Tags: andinstanceselffoomain部件defargs
3条回答

如果您使用的是kivy version>;=1.8,则可以只执行widget.disabled=True。如果在以前的版本中,您可以自己管理禁用,只要确保它不会对触摸做出反应,并在禁用时显示一个替代的外观。

  1. disabled,不是disable
  2. 设为真

示例:

from kivy.uix.button import Button
from kivy.app import App
from functools import partial

class ButtonTestApp(App):
    def foo(self, instance, *args):
        instance.disabled = True

    def build(self):
        btn = Button()
        btn.bind(on_press=partial(self.foo, btn));
        return btn

if __name__ == '__main__':
    ButtonTestApp().run()

在下面的示例中,MyButton遵循@qua non idea。它使用BooleanProperty来改变它的background_colorcolor。更重要的是,它在on_touch_down中添加了一个条件if self.enabled:。如果没有on_touch_down,那么就没有on_touch_moveon_touch_upon_presson_release。因此,我们可以考虑禁用Button

我使用名称enabled,而不是disabled,通过使用Kivy 1.8.0的相同属性来避免将来可能出现的问题。

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import BooleanProperty
from kivy.uix.button import Button
from kivy.lang import Builder

Builder.load_string("""
<Example>:
    cols: 3
    Button:
        text: "Disable right button"
        on_press: my_button.enabled = False
    Button:
        text: "enabled right button"
        on_press: my_button.enabled = True
    MyButton:
        id: my_button
        text: "My button"
        on_press: print "It is enabled"
""")

class MyButton(Button):
    enabled = BooleanProperty(True)

    def on_enabled(self, instance, value):
        if value:
            self.background_color = [1,1,1,1]
            self.color = [1,1,1,1]
        else:
            self.background_color = [1,1,1,.3]
            self.color = [1,1,1,.5]

    def on_touch_down( self, touch ):
        if self.enabled:
            return super(self.__class__, self).on_touch_down(touch)

class Example(GridLayout):    
    pass

class MyApp(App):
    def build(self):
        return Example()

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

相关问题 更多 >