user1876508
user1876508

Reputation: 13172

Dynamically add checkboxes with tkinter in python 2.7

I want to dynamically add ckeckboxes to my gui through a premade list. How would I populate the GUI with the names in my list? They all have the same type of functionality, so that should not be an issue.

Upvotes: 4

Views: 5908

Answers (2)

Kevin
Kevin

Reputation: 76194

If you want to populate your GUI with a premade list at startup:

from Tkinter import *

root = Tk()

premadeList = ["foo", "bar", "baz"]

for checkBoxName in premadeList:
    c = Checkbutton(root, text=checkBoxName)
    c.pack()

root.mainloop()

If you want to dynamically populate your GUI with checkboxes at runtime:

import random
import string
from Tkinter import *

root = Tk()

def addCheckBox():
    checkBoxName = "".join(random.choice(string.letters) for _ in range(10))
    c = Checkbutton(root, text=checkBoxName)
    c.pack()

b = Button(root, text="Add a checkbox", command=addCheckBox)
b.pack()

root.mainloop()

And of course, you can do both:

import random
import string
from Tkinter import *

root = Tk()

def addCheckBox():
    checkBoxName = "".join(random.choice(string.letters) for _ in range(10))
    c = Checkbutton(root, text=checkBoxName)
    c.pack()

b = Button(root, text="Add a checkbox", command=addCheckBox)
b.pack()

premadeList = ["foo", "bar", "baz"]

for checkBoxName in premadeList:
    c = Checkbutton(root, text=checkBoxName)
    c.pack()

root.mainloop()

Upvotes: 4

Brandon
Brandon

Reputation: 3764

Use a treeview with checkboxes.

Treeview with checkboxes

How to create a tree view with checkboxes in Python

Upvotes: 1

Related Questions