单击扫描ble的按钮后如何加载组合框?

时间:2019-04-12 08:40:21

标签: python tkinter combobox

我对tkinter框架很陌生,想知道是否有人可以帮助我解决我的问题。单击“扫描”按钮后,我正在尝试加载组合框。此扫描按钮基本上会扫描特定的蓝牙设备,然后返回所有蓝牙设备。扫描完成后,应将结果加载到组合框。然后,从组合框中选择一个选项后,我想将该值传递给另一个连接到蓝牙设备的按钮功能。

class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label = Label(master, text="This is our first GUI!")
        self.label.pack()

        self.button_scan = Button(master, text="Scan", command=self.scan1)
        self.button_scan.pack()

        self.box_value = StringVar()
        self.cb = ttk.Combobox(master, textvariable=self.box_value)
        self.cb.pack()
        self.cb['values'] = self.scan1()


        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()

    def scan1(self):
        scanner = Scanner()
        devices = scanner.scan(5)
        data = []
        for dev in devices:
            scanData = dev.getScanData()
            for (adtype, desc, value) in scanData:
                if desc == 'Complete Local Name':
                    if 'Thunder Sense #' in value:
                        deviceMac = dev.addr
                        #deviceMac1= str(deviceMac)
                        deviceId = int(value.split('#')[-1])
                        deviceId2 = str(deviceId)
                        print(deviceMac)
                        data.append(deviceMac)
                        #data.append(deviceMac)
        print(data)
        return data


root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

我能够打印deviceMac以及列表,但是我似乎无法加载组合框。谢谢

1 个答案:

答案 0 :(得分:1)

您的scan1不必返回数据。只需在扫描完成后立即修改combobox的值即可。

class MyFirstGUI:
    def __init__(self, master):
        ...

        self.box_value = StringVar()
        self.cb = ttk.Combobox(master, textvariable=self.box_value)
        self.cb.pack()

        ...

    def scan1(self):
        scanner = Scanner()
        devices = scanner.scan(5)
        data = []
        for dev in devices:
            scanData = dev.getScanData()
            for (adtype, desc, value) in scanData:
                if desc == 'Complete Local Name':
                    if 'Thunder Sense #' in value:
                        deviceMac = dev.addr
                        # deviceMac1= str(deviceMac)
                        deviceId = int(value.split('#')[-1])
                        deviceId2 = str(deviceId)
                        print(deviceMac)
                        data.append(deviceMac)
        self.cb["values"] = data