Home > Software design >  multiple checkboxes again in python
multiple checkboxes again in python

Time:11-18

I am a noob, I am trying to create many checkboxes at once. ultimately, my program would create folders in the same directory, depending on which ones have been checked. I simply do not get the IntVar() use. I would love for some of the boxes to be ticked by default...according to the entries in my dictionary I even tried to put the "variable" = 1 in my loop and the boxes are not ticked!!!

import os
from tkinter import *


def create_folders():
    for item in list_of_folders:
        print(item)
            # os.mkdir(list_of_folders[item])


list_of_folders = {"Audio":0,"AVI":0, "Footage":1, "GFX":1, "MP4":1, "MOV":1, "MPG":0,  "Photography":1, "Press":1}
num_row=0
window = Tk()
var=[]
window.title("Folder Creation v1.0")
window.minsize(300, 200)
window.config(padx=100, pady=100)

for item in list_of_folders:
    num_row  =1
    Checkbutton(window, text=item, variable=list_of_folders[item]).grid(row=num_row, sticky=W)



Label(window, text="").grid(column=0, row=10, sticky=W)

Button(window, text="Create Folders", command=create_folders).grid(column=0, row=15, sticky=W)

Button(window, text="Exit", command=window.destroy).grid(column=1, row=15, sticky=W)

window.mainloop()

CodePudding user response:

You was so damn close to the victory there is nothing fancy that I added, I just optimized your code a bit and used the IntVar(value=1) to check the button and stored the variable of that IntVar() into a list to later iterate on final button click to actually create the directories.

Calling the get method on the IntVar() returns the current state of the checkbox as you can see in the screenshot.

import os
from tkinter import *


def create_folders():
    for button in boxes:
        if button["state"].get(): #check if its checked or not
            print("Creating folder", button["text"])
            os.mkdir(button["text"])


boxes = []

list_of_folders = {
    "Audio": 0,
    "AVI": 0, 
    "Footage": 1, 
    "GFX": 1, 
    "MP4": 0, 
    "MOV": 1,
    "MPG": 0,  
    "Photography": 1,
    "Press": 1
}

num_row=0
window = Tk()
window.title("Folder Creation v1.0")
window.minsize(300, 200)
window.config(padx=100, pady=100)

for item in list_of_folders.keys():
    lookup = IntVar(value=list_of_folders[item])
    Checkbutton(window, text = item, variable=lookup).grid(row=len(boxes)   1, sticky=W)
    boxes.append({ 
        "text": item, #store name to create the directory
        "state": lookup #store reference to check whether we need to create directory
    })



Label(window, text="").grid(column=0, row=10, sticky=W)

Button(window, text="Create Folders", command=create_folders).grid(column=0, row=15, sticky=W)

Button(window, text="Exit", command=window.destroy).grid(column=1, row=15, sticky=W)
window.mainloop()

Screenshot

enter image description here

  • Related