[英]Enable/Disable Fullscreen and Wakelock with a Button in Python Kivy?
[英]Python, Kivy. How to disable/enable a button?
当#1 (TextInput)
或#2 (TextInput)
或两者(TextInput)
为空时是否可以禁用“结果”按钮并在两个TextInput都填充时启用按钮? 我在.kv
文件中找到并尝试了“ disabled: True
”,但后来我被卡住了,我不知道如何让它工作。
我创建了一个简单的代码来向您展示我想要实现的目标:
我的文件.py
:
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.properties import ObjectProperty
class test(BoxLayout):
first = ObjectProperty()
second = ObjectProperty()
result = ObjectProperty()
def result_final(self):
x = int(self.first.text)
y = int(self.second.text)
z = x * y
self.result.text = str(z)
class firstApp(App):
def build(self):
return test()
if __name__ == "__main__":
firstApp().run()
我的文件.kv
:
<test>:
first: first_number
second: second_number
result: result_number
orientation: "vertical"
padding: 20
spacing: 20
BoxLayout:
Label:
text: "#1"
TextInput:
id: first_number
input_filter: "int"
BoxLayout:
Label:
text: "#2"
TextInput:
id: second_number
input_filter: "int"
BoxLayout:
Button:
text: 'RESULT'
on_press: root.result_final()
BoxLayout:
TextInput:
id: result_number**
是的,这很容易在您的kv
中使用一些逻辑。 将此用于您的Result
Button
:
Button:
text: 'RESULT'
disabled: True if first_number.text == '' or second_number.text == '' else False
on_press: root.result_final()
import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
class Test(BoxLayout):
first = ObjectProperty()
second = ObjectProperty()
result = ObjectProperty()
result_btn = ObjectProperty()
empty = True
def check(self):
if self.first.text.strip() != '' and self.second.text.strip() != '':
self.result_btn.disabled = False
else:
self.result_btn.disabled = True
def result_final(self):
x = int(self.first.text)
y = int(self.second.text)
z = x * y
self.result.text = str(z)
class FirstApp(App):
def build(self):
return Test()
if __name__ == "__main__":
FirstApp().run()
和.kv
<test>:
first: first_number
second: second_number
result: result_number
result_btn: result_btn
orientation: "vertical"
padding: 20
spacing: 20
BoxLayout:
Label:
text: "#1"
TextInput:
id: first_number
input_filter: "int"
on_text:
root.check()
BoxLayout:
Label:
text: "#2"
TextInput:
id: second_number
input_filter: "int"
on_text:
root.check()
BoxLayout:
Button:
id: result_btn
text: 'RESULT'
on_press: root.result_final()
disabled: True if root.empty else False
BoxLayout:
TextInput:
id: result_number
基本上,每次输入任何数字时,都会调用一个 check() 方法,该方法会检查两个输入是否为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.