简体   繁体   中英

Tkinter widget creation using Python3 of Rasberry Pi. Create an array of checkbuttons

I wish to create an array of checkboxes and reference them as an array of some sort. This makes writing the code a lot easier with shorter blocks. The ideal situation would be something like this

for IOBit in range(8)
    self.GPIO_Array[IOBit] = tk.BooleanVar()
    tk.Checkbutton(self.MyFrame , variable = self.GPIO_Array[IOBit] )

Afterwards I would have an array of 8 boolean variables called GPIO_Array[] . I would then want to use access these such as

self.GPIO_Array[Index].get()

Any thoughts of how to go about this is perhaps a different approach that allows loops rather than a large block of semi repeated code?

Since you didn't show actual code, only "something like" your actual code, it's hard to say for certain what you're doing wrong. Here's a working example where I've tried to mimic what you want:

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.MyFrame = tk.Frame(self)
        self.MyFrame.pack(side="top", fill="x")

        self.GPIO_Array = []
        for IOBit in range(8):
            self.GPIO_Array.append(tk.IntVar())
            w = tk.Checkbutton(self.MyFrame, variable=self.GPIO_Array[IOBit],
                               onvalue=1, offvalue=0, command=self.show)
            w.pack(side="left")

        self.label = tk.Label(self, text="", width=8)
        self.label.pack(side="top", fill="x")

        # show the current value when the GUI first starts
        self.show()

    def show(self):
        s = ""
        for IOBit in range(8):
            s += str(self.GPIO_Array[IOBit].get())
        self.label.configure(text=s)

if __name__ == "__main__":
    root = tk.Tk()
    app = Example(root)
    app.pack(fill="both", expand=True)
    root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM