在Python / Kivy的循环中创建不同的按钮?

时间:2016-04-19 23:45:05

标签: python button bluetooth 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中每个设备的设备名称/地址。)允许用户点击按钮并打印分配按钮的设备的名称。我确信在这部分代码中必须有一些重要的结构变化才能实现,但我无法弄明白究竟是什么。

1 个答案:

答案 0 :(得分: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 

“实例”仅表示您按下的按钮对象。您可以将其更改为您喜欢的任何内容。