我正在动态创建按钮并为每个按钮动态创建下拉列表。选择按钮时,主按钮上的文本值会更新。 我想将主要按钮更新的文本值导入Run_DrawsTest()。 我一直在尝试运行按钮ID来获取文本值。通常是btn_txt = self.ids.button_id_name.text。 由于按钮是动态创建的,我无法预见将创建的数量,我不知道如何获得文本
for i in range(row_count):
drpName.append(DropDown())
btnName = Button(text="Select", size_hint_y= self.size_hint_y)
self.cnt_btns += 1
for e in self.sel:
self.ssbtn = ('tbtn' + str(sbtn))
sbtn += 1
btn = Button(text=e, size_hint_y=None, height=25, id=self.ssbtn)
btn.bind(on_release=lambda btn=btn, dropdown=drpName[i]: dropdown.select(btn.text))
drpName[i].add_widget(btn)
btnName.bind(on_release=drpName[i].open)
drpName[i].bind(on_select=lambda instance, x, btn=btnName: setattr(btn, 'text', x))
self.ids.select_btn.add_widget(btnName)
self.my_btn_names.append(self.ssbtn)
def Run_Draws_Test (self):
counter = 0
vals = [ ]
while counter != self.cnt_btns:
btn_ids = (self.my_btn_names[counter])
txt = ('txt' + str(counter))
s = btn_ids
btn_texts = str(txt + ' = ' + "self.ids." + s + ".text")
vals.append(btn_texts)
executable_code = (vals[counter])
print(executable_code)
time.sleep(3)
exec(str(executable_code))
print(txt)
counter += 1
答案 0 :(得分:0)
使用 on_select 事件将所选文本传递给方法。有关详细信息,请参阅代码段和示例。
<CustomDropDown>:
on_select:
app.root.ids.Notes.ids.mainbutton.text = '{}'.format(args[1])
app.root.Run_Draws_Test(args[1])
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.core.window import Window
Window.size = (800, 480)
class CustomDropDown(DropDown):
def __init__(self, **kwargs):
super(CustomDropDown, self).__init__(**kwargs)
self.add_buttons()
def add_buttons(self):
for index in range(10):
# When adding widgets, we need to specify the height manually
# (disabling the size_hint_y) so the dropdown can calculate
# the area it needs.
btn = Button(text='Value %d' % index, size_hint_y=None, height=44)
# for each button, attach a callback that will call the select() method
# on the dropdown. We'll pass the text of the button as the data of the
# selection.
btn.bind(on_release=lambda btn: self.select(btn.text))
# then add the button inside the dropdown
self.add_widget(btn)
class Notes(Screen):
pass
class MyScreenManager(ScreenManager):
def Run_Draws_Test(self, value):
print(value)
class TestApp(App):
title = "Kivy Drop-Down List Demo"
def build(self):
return MyScreenManager()
if __name__ == '__main__':
TestApp().run()
#:kivy 1.10.0
#:import Factory kivy.factory.Factory
<CustomDropDown>:
on_select:
app.root.ids.Notes.ids.mainbutton.text = '{}'.format(args[1])
app.root.Run_Draws_Test(args[1])
<Notes>:
orientation: "vertical"
FloatLayout:
size_hint: None, None
canvas.before:
Color:
rgba: 1, 1, 0, 1
Button:
id: mainbutton
text: "Menu name"
font_size: 20
size_hint: None, None
size: 150, 50
pos: 20,400
on_release: Factory.CustomDropDown().open(self)
<MyScreenManager>:
canvas.before:
Color:
rgba: 0.5, 0.5, 0.5, 0.5
Rectangle:
pos: 0,0
size: 800, 480
Notes:
id:Notes
name: 'Notes'