python 中的多个复选框

multiple checkboxes again in python

我是菜鸟,我想一次创建多个复选框。最终,我的程序会在同一目录中创建文件夹,具体取决于已检查的文件夹。 我根本没有使用 IntVar() 。 我希望默认勾选某些框...根据我字典中的条目 我什至尝试将“变量”= 1 放入我的循环中,但没有勾选方框!!!

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()

你离胜利太近了,我没有添加任何花哨的东西,我只是稍微优化了你的代码并使用 IntVar(value=1) 检查按钮并存储了 [=12= 的变量] 到列表中,稍后在最终按钮上迭代,单击以实际创建目录。

IntVar() returns 复选框的当前状态上调用 get 方法,如您在屏幕截图中所见。

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()

截图