I created a custom button in the kv file, i want to set disabled = True if app.root.ids.my_label == "disabled" else disabled=False. However i keep getting AttributeError: 'NoneType' object has no attribute 'ids. I no this can be done, i'm not just doing it right, i will be grateful for any help. Thanks!
test.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty
Builder.load_string('''
<CustomBtn@Button>
disabled: True if app.root.ids.word.my_label == "disable" else False
<main>:
my_label:my_label
BoxLayout:
orientation:"vertical"
Label:
id: my_label
text: "Disabled"
CustomBtn:
text: "Btn1"
CustomBtn:
text: "Btn2"
CustomBtn:
text: "Btn3"
Button:
text: "Disable/Enable"
on_press: root.disablebtn()
''')
class main(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
my_label = ObjectProperty()
def disablebtn(self):
print(self.my_label)
if self.my_label.text == "Disabled":
self.my_label.text = "Enabled"
else:
self.my_label.text = "Disabled"
class CallApp(App):
def build(self):
return main()
CallApp().run()
You can do it by putting the expression under each CustomBtn
, like this:
CustomBtn:
text: "Btn1"
disabled: True if root.my_label.text == "Disabled" else False
rather than in the <CustomBtn>:
rule.
Your original approach won't work because app.root
is not set when your <CustomBtn@Button>
rule is applied. Here is a modified version of your code, that does what you want without that problem:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.button import Button
class CustomBtn(Button):
pass
Builder.load_string('''
<main>:
my_label:my_label
BoxLayout:
orientation:"vertical"
Label:
id: my_label
text: "Disabled"
CustomBtn:
text: "Btn1"
CustomBtn:
text: "Btn2"
CustomBtn:
text: "Btn3"
Button:
text: "Disable/Enable"
on_press: root.disablebtn()
''')
class main(BoxLayout):
my_label = ObjectProperty()
def disablebtn(self):
if self.my_label.text == "Disabled":
self.my_label.text = "Enabled"
self.disable_customBtns(False)
else:
self.my_label.text = "Disabled"
self.disable_customBtns(True)
def disable_customBtns(self, is_disabled):
# Look for CustomBtn instances, and set their `disabled` value
for child in self.walk():
if isinstance(child, CustomBtn):
child.disabled = is_disabled
def on_my_label(self, *args):
# this just sets the initial value of disabled to True
self.disable_customBtns(True)
class CallApp(App):
def build(self):
return main()
CallApp().run()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.