单击 Kivy Python 时返回按钮的 ID
问题描述
我遇到的简单问题:
当我在我的 Kivy/Python 应用程序中单击一个按钮时,我想要访问该按钮的 ID.
# Kivy code
Button:
id: position_1
on_press: app.access_button_id()
我进行了各种尝试和错误尝试,但我无法弄清楚.该按钮嵌套如下(作为更大应用程序的一部分),如果这是我的问题的一个因素:
I have had various trial and error attempts but I cannot figure it out. The button is nested as follows (as part of a bigger app), if this is a factor in my problem:
FloatLayout:
AnchorLayout:
ScreenManager:
Screen:
BoxLayout:
FloatLayout:
Button:
id: position_1
on_press: app.access_button_id()
这是我的 Python 代码,它返回所有的 id.这和我得到的一样接近:
Here is my Python code, which returns all of the id's. That's as close as I have got:
# Python code
def access_button_id(name):
print(self.root.ids)
我遇到的问题是我什至不知道我应该在文档中查看什么,因为我还没有完全理解术语,所以我找不到值得学习的正确信息.
The problem I've got is that I don't even know what I should be looking at in the documentation as I do not fully understand the terminology yet, so I can't find the right information to learn from.
传递给函数的(名称)用于某些其他功能,与此问题无关.
The (name) passed into the function is for some other functionality, not related to this problem.
解决方案
你已经知道 id - 你自己设置它.这些主要用作代码中的硬编码值:
You already know the id - you set it yourself. These are mostly used as a hard-coded values in your code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
Builder.load_string('''
<MyWidget>:
Button:
id: id_value_1
text: 'Print my id'
on_press: print({'id_value_1': self.proxy_ref})
Button:
id: id_value_2
text: 'Print all ids'
on_press: print(root.ids)
''')
class MyWidget(BoxLayout):
pass
class MyApp(App):
def build(self):
widget = MyWidget()
print({'id_value_1': widget.ids['id_value_1']})
return widget
if __name__ == '__main__':
MyApp().run()
如果您已经可以访问它,为什么还需要 Button 的 id?你想完成什么?
Why do you need id of a Button if you already have an access to it? What are you trying to accomplish?
编辑
评论中提到的问题的示例解决方案:
An example solution to problem mentioned in the comment:
import random
import functools
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.lang import Builder
Builder.load_string('''
<MyWidget>:
Button:
text: 'B1'
on_press: root.open_popup(self)
Button:
text: 'B2'
on_press: root.open_popup(self)
''')
class MyWidget(BoxLayout):
def open_popup(self, caller):
fun = functools.partial(self.rename, caller)
popup = Popup(
title='Test popup',
content=Button(
text='rename',
on_press=fun
),
size_hint=(None, None), size=(400, 400)
)
popup.open()
def rename(self, caller, *args):
caller.text = ''.join(chr(random.randint(48, 90)) for i in range(5))
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
相关文章