2016-04-19 65 views
1

我已经构建了一个简单的程序,用于扫描蓝牙设备并在按钮上显示其名称/地址。代码:在Python/Kivy的循环中创建不同的按钮?

def discover(self, *args): 
    devList = discover_devices() 
    for device in devList: 
     name = str(lookup_name(device)) 
     if str(lookup_name(device)) == "": 
      name = "Unknown device" 
     deviceinfo = "[color=1f358e][font=tahoma]Device name: [color=1f358e][font=tahoma]" + str(name) + "\n[color=1f358e][font=tahoma]MAC address: [color=1f358e][font=tahoma]" + str(device) 
     btnDevice = Button(text=deviceinfo, markup = True, font_size='17sp') 
     btnDevice.bind(on_release=self.optionmenu) 
     box.add_widget(btnDevice) 


    self.boxes.add_widget(box) 
    layout.clear_widgets() 

def optionmenu(self, *args): 
    print name 

所以,基本上,我想A.)发现蓝牙设备并将其添加到devList,B.)创建一个按钮显示的设备名称/地址在devList,C.每个设备)允许让用户点击一个按钮并打印该按钮分配给的设备的名称。我确信在这部分代码中必须有一些重要的结构变化才能工作,但我无法弄清楚究竟是什么。

+0

您可以替换'name = ...;顺便说一句,如果str(lookup ...:name = ...''with'name = lookup_name(device)or'Unknown device'',顺便说一下。 – TigerhawkT3

+0

你试过了吗?on_release = lambda x = name:self.optionmenu名字)''与'def optionmenu(self,name):print name'? – TigerhawkT3

+0

@ TigerhawkT3是的,点击任何按钮都会返回相同的名称,我猜测它找到的最后一个。 – Karrigan

回答

0

我相信这应该可以做到。

def discover(self, *args): 
    devList = discover_devices() 
    for device in devList: 
     name = str(lookup_name(device)) 
     if str(lookup_name(device)) == "": 
      name = "Unknown device" 
     deviceinfo = "[color=1f358e][font=tahoma]Device name: [color=1f358e][font=tahoma]" + str(name) + "\n[color=1f358e][font=tahoma]MAC address: [color=1f358e][font=tahoma]" + str(device) 
     btnDevice = Button(text=deviceinfo, markup = True, font_size='17sp') 
     btnDevice.bind(on_release=self.optionmenu) 
     box.add_widget(btnDevice) 


    self.boxes.add_widget(box) 
    layout.clear_widgets() 

def optionmenu(self, instance): 
    print instance.text 

“Instance”仅表示您按下的按钮对象。当然,你可以将其改为任何你喜欢的。