python行人分配id_在python端的Kivy中分配ID

im using kivy. the what im trying to do is have and 'idea',a slider and a label containing the slider's current value in a row in a grid layout

now getting the layout is fine but getting the label to have a text value the same as the slider's current value is tricky. I'm trying to use string concation to refer to the label with the same number suffix as the slider that it is paired with.

I think the problem im having is that im trying to assign ids on the python side when they normally have to be done on the kv side. It's either that or the fact the ids i'm assigning are strings when kv would normally expect plain text. any help would be appreciated

class ScatterTextWidget(FloatLayout):

def run_me(self):

r=1

main_list=self.ids.main_list

main_list.clear_widgets()

main_list.height=0

for idea in imported_ideas:

main_list.add_widget(Label(text=idea,color=(0,0,0,1),id='idea_label_'+str(r)))

main_list.add_widget(Slider(id='Slider_'+str(r),min=0,max=10,value=5, step=1,on_value_pos=self.slider_slid(self)))

main_list.add_widget(Label(color=(0,0,0,1),id='value_label_'+str(r)))

value_label=self.ids['value_label_'+str(r)] # get this working and then apply the method into slider slid

value_label.text='xxx'

main_list.height+=35

r +=1

button_1=self.ids.button_1

button_1.text='Begin'

button_1.bind(on_press=self.begin)

def slider_slid(self,sender):

s=str(sender.id)

value_label=self.ids['value_label_'+str(s[12:])]

value_label.text=str(sender.value)

value_label=self.ids['value_label_'+str(s[12:])]

KeyError: 'value_label_'

解决方案

self.ids only collects ids from children in the kv language rule of the widget. It doesn't know about widgets you added via python.

You don't need to use the id though. In this case you could keep e.g. a dictionary of id -> widget keys.

self.keys_dict = {}

for idea in imported_ideas:

new_widget = Label(color=(0,0,0,1),id='value_label_'+str(r)))

main_list.add_widget(new_widget)

self.keys_dict['value_label_' + str(r)] = new_widget

Then later you can access it with self.keys_dict['value_label_' + str(s[12:])] or whatever you like.

I suppose in practice you could also modify the actual ids dictionary in the same way, though I subjectively feel it is preferable to maintain your own dictionary with a name that represents its more specific contents.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值