python - 我如何通过 id 获得 2 个 TextInput 值
问题描述
所以我有一个必须创建任务的类,它看起来像这样
class CreateTask(Screen):
def CreateTask(self,*args):
bl = BoxLayout(orientation="vertical",spacing=10)
name=self.root.ids.TaskName.text
desc=self.root.ids.TaskDesc.text
bl.add_widget(name)
bl.add_widget(desc)
self.root.MainLayout.add_widget(bl)
但我得到错误'CreateTask'对象没有属性'root',那么我如何通过id从2个TextInputs获取文本?
这是我那个类的kv代码
<CreateTask>
name:"third"
AnchorLayout:
size:root.size
anchor_x:"center"
anchor_y:"top"
BoxLayout:
orientation:"vertical"
size_hint:[0.6,0.6]
Label:
text:"Input Task Name"
TextInput:
size_hint:[0.2,0.2]
id:"TaskName"
TextInput:
size_hint:[0.6,0.6]
id:"TaskDesc"
multiline:False
Button:
size_hint:[0.4,0.4]
text:"come_back"
on_release:
app.root.current ="second"
root.manager.transition.direction = "left"
Button:
size_hint:[0.4,0.4]
text:"Create"
on_release:root.CreateTask(*args)
这是主布局
BoxLayout:
size_hint:[0.4,0.2]
id:MainLayout
orientation:"vertical"
Button:
size_hint:[0.3,0.3]
text:"Add Task"
on_release:
app.root.current="third"
root.manager.transition.direction = "right"
也好像制表有错误,没有,就是这样粘贴的
解决方案
“CreateTask”对象没有属性“root”,因为“self”已经是根。并且不要使用字符串作为 id。
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.screenmanager import ScreenManager, Screen
class CreateTask(Screen):
def CreateTask(self, *args):
bl = BoxLayout(orientation="vertical",spacing=10)
name=self.ids.TaskName.text
desc=self.ids.TaskDesc.text
lbl_name = Label(text=name)
lbl_desc = Label(text=desc)
bl.add_widget(lbl_name)
bl.add_widget(lbl_desc)
self.ids.MainLayout.add_widget(bl)
sm = ScreenManager()
Builder.load_file("mainscreen.kv")
sm.add_widget(CreateTask())
class MainScreenApp(App):
def build(self):
return sm
if __name__ == "__main__":
MainScreenApp().run()
<CreateTask>
name:"third"
AnchorLayout:
size:root.size
anchor_x:"center"
anchor_y:"top"
BoxLayout:
orientation:"vertical"
size_hint:[0.6,0.6]
Label:
text:"Input Task Name"
TextInput:
size_hint:[0.2,0.2]
id: TaskName
TextInput:
size_hint:[0.6,0.6]
id: TaskDesc
multiline:False
Button:
size_hint:[0.4,0.4]
text:"come_back"
on_release:
app.root.current: "second"
root.manager.transition.direction: "left"
Button:
size_hint:[0.4,0.4]
text:"Create"
on_release: root.CreateTask(*args)
BoxLayout:
size_hint:[0.4,0.2]
id:MainLayout
orientation:"vertical"
Button:
size_hint:[0.3,0.3]
text:"Add Task"
on_release:
app.root.current="third"
root.manager.transition.direction = "right"
推荐阅读
- elasticsearch - 弹性:尝试初始化同义词标记过滤器时出错
- android - PANIC:启动模拟器时损坏的 AVD 系统路径
- php - php - mysqli_fetch_assoc to to json 编码数组适用于大多数查询,但不适用于其他查询(尽管查询返回有效结果)
- python - 生成公共/私人比特币密钥
- html - Moving variable text to the right side
- c - Why won't my File.dat be read and run and how can I assign the data to a struct? - C
- python - 如何在包含每小时平均值和每小时每个平均值的相应计数的数据帧末尾添加新列。
- ionic-framework - 像离子的按钮
- c - C语言破解密码
- javascript - 如何使用 Greasemonkey 启用禁用的按钮?