我的问题可能主要是因为缺乏技能,但我找不到任何类似的帖子。所以我在主屏幕上有textinputs。我需要第二个屏幕上的按钮来清除这些文本输入。
我不知道该如何调用clear_inputs方法并将textinput作为参数传递。我认为使用clear_inputs方法可以清空那些文本字段,但是如何将其绑定到另一页中的按钮上呢?
Py。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.properties import StringProperty, BooleanProperty
class MainScreen(Screen):
pass
class SecondScreen(Screen):
def clear_inputs(self, text_inputs):
for text_input in text_inputs:
text_input.text = ''
class ScreenManagement(ScreenManager):
def changescreen(self, value):
try:
if value !='main':
self.current = value
except:
print('No Screen named'+ value)
class testiApp(App):
def build(self):
self.title = 'Hello'
testiApp().run()
KV。
ScreenManagement:
MainScreen:
name:'Main'
SecondScreen:
name:'Page2'
<MainScreen>:
name:'Main'
BoxLayout:
orientation:'vertical'
GridLayout:
cols:2
Label:
text:'testfield1'
TextInput:
id: textfield1
Label:
text:'testfield2'
TextInput:
id: textfield2
Button:
text:'Next Page'
on_release: app.root.current ='Page2'
<SecondScreen>:
name:'Page2'
Button:
text:'Clear textfields'
on_release:
答案 0 :(得分:1)
需要以下增强功能(kv文件和Python脚本)才能在另一屏幕上清除TextInput
的文本。
TextInput
小部件,请将id: container
添加到实例化对象GridLayout:
manager
,该属性为您提供所使用的ScreenManager
的实例。on_release
事件绑定到方法clear_inputs()
,不带任何参数<MainScreen>:
name:'Main'
BoxLayout:
orientation:'vertical'
GridLayout:
id: container
...
Button:
text:'Next Page'
on_release: root.manager.current ='Page2'
<SecondScreen>:
name:'Page2'
Button:
text:'Clear textfields'
on_release: root.clear_inputs()
from kivy.uix.textinput import TextInput
ScreenManager
的{{1}}函数获取实例化对象get_screen('Main')
MainScreen
循环通过for
遍历GridLayout:
的子代ids.container
函数检查isinstance()
小部件TextInput
答案 1 :(得分:0)
如果我不确定,那么您想使用X页面(Main
?)中的按钮来更改Y页面(Page2
?)中的文本。我不是Kivy的专家,所以也许有更好的方法,但是这里有一些想法:
1)我尝试为所有屏幕赋予类属性parent
,结果发现这是一个坏主意,因为Kivy已经使用了该名称。您可以简单地将其更改为parent_
或其他内容,然后自己尝试一下。您想要的是在创建时将“父级”作为参数传递给__init__
:
class ScreenManagement(ScreenManager):
def __init__(self, children_, **kwargs):
# you might need to save the children too
self.children_ = children_
def add_child(self, child):
# maybe as dict
self.children_[child.name] = child
class SecondScreen(Screen):
def __init__(self, parent_, **kwargs):
super().__init__(**kwargs)
# maybe the screen manager or the main app?
self.parent_ = parent_
self.name_ = "Second"
....
def clear_inputs(self, text_inputs):
....
class MainScreen(Screen):
def __init__(self, parent_, **kwargs):
super().__init__(**kwargs)
# maybe the screen manager or the main app?
self.parent_ = parent_
# you may want to
....
# Get the appropriate screen from the parent
self.parent_.children_["Second"].clear_inputs(...)
2)我还从youtube tutorial中看到了另一种方法。与其直接运行您的应用,不如将其分配给一个变量并引用该变量。对于高级用例,这可能仍需要篡改:
# Use the global variable within your classes/methods
class Whatever:
def whatever2(self, params):
app.something()
....
app = testiApp()
app.run()