问题描述
主要:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.widget import Widget
class testclass:
def someth(txt):
print (txt)
#how get access to textinput from begin Screen here?
class BeginScreen(Screen):
def __init__(self,**kwargs):
super().__init__()
self.layout =BoxLayout(orientation='vertical',padding=20,spacing=5,)
self.btn=Label(text=str('Hello'))
self.layout.add_widget(self.btn)
self.btn=TextInput(id='test',text='')
self.layout.add_widget(self.btn)
self.btn=Button(text='Button!', on_press=testclass.someth('?'))
# what write in ? to send textinput text to testclass.someth?
self.layout.add_widget(self.btn)
self.add_widget(self.layout)
print(self.layout.ids) #why i have no ids? textinput have id
class TestApp(App):
from kivy.config import Config
Config.set('graphics', 'width', '800')
Config.set('graphics', 'height', '400')
def build(self):
sm = ScreenManager()
sm.add_widget(BeginScreen(name='test'))
return sm
TestApp().run()
那么我该如何访问textinput?我有id ='test',但是当我打印布局时,id是说我没人.为什么?有人可以向我解释我做错了什么,我该怎么做呢?
So how can i access the textinput? I have id='test' but when i printing layouts id is saying i have noone. Why? Someone can explain me what im doing wrong and how can i make it good?
推荐答案
从functools导入部分
要访问外部方法中的textinput,可以使用部分函数或lambda函数.
from functools import partial
To access the textinput in your external method, you could use partial functions or lambda function.
由于没有kv文件,您将获得None或空字典.
You are getting None or empty dictionary because you don't have a kv file.
当解析您的kv文件时,kivy会收集所有标记有id的小部件,并将它们放在此self.ids字典类型属性中.
When your kv file is parsed, kivy collects all the widgets tagged with id’s and places them in this self.ids dictionary type property.
请参阅下面的示例以了解详细信息.
Please refer to my example below for deatils.
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from functools import partial
class testclass:
def someth(*args, txt):
print(txt)
class BeginScreen(Screen):
def __init__(self, **kwargs):
super(BeginScreen, self).__init__(**kwargs)
layout = BoxLayout(orientation='vertical', padding=20, spacing=5)
layout.add_widget(Label(text=str('Hello')))
layout.add_widget(TextInput(id='test', text=''))
layout.add_widget(Button(text='Button!', on_press=partial(testclass.someth, txt='?')))
self.add_widget(layout)
print("self.ids={}".format(self.ids))
class TestApp(App):
from kivy.config import Config
Config.set('graphics', 'width', '800')
Config.set('graphics', 'height', '400')
def build(self):
sm = ScreenManager()
sm.add_widget(BeginScreen(name='test'))
return sm
TestApp().run()
输出
这篇关于python代码中的Kivy ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!