Home > Software design >  Using a list of Tkinter CheckButtons to get values
Using a list of Tkinter CheckButtons to get values

Time:05-30

Around line 36 in the CreateJson function, I'm trying to use the state of the checkboxes I've created to create a JSON file (I'm aware this is not the best way to create a JSON file ). Anyways I've tried many different ways to read the value of the Checkbox. I've read that using .get() on the Tkinter object works to grab the value, but I've tried that stand-along and on my list here and it does not seem to work. Printing the list shows the object and its locations like so. <tkinter.IntVar object at 0x000001CD7FB41150>

from itertools import count
from tkinter import *
from tkinter import filedialog
import os
import json
from traceback import print_tb

def openFile():

    filepath = filedialog.askdirectory()

    f = open("Modstext.json","w")
    f.write("\"mods\": [")

    jsonfiles = []
    for dirpath, subdirs, files in os.walk(filepath):
        for x in files:
            if x.endswith("ServerData.json"):
                jsonfiles.append(os.path.join(dirpath, x))

    counter = 0
    r = [len(jsonfiles)]
    for item in jsonfiles:
        with open(item,encoding='utf-8-sig') as file:
            data = json.load(file)
            var = IntVar()
            Checkbutton(window, text = data["name"],variable = var,onvalue=1,offvalue=0).pack()
            r.append(var)
            counter  = 1

    def CreateJson(): 
        counter = 0
        print(r)
        for x in jsonfiles:
            if r[counter] == 1:       
                with open(x,encoding='utf-8-sig') as file:
                    data = json.load(file)
                    f.write("\n     {")
                    f.write("\n          \"modsId\":"   "\"" data["id"] "\",")
                    f.write("\n          \"name\":"   "\"" data["name"] "\",")
                    f.write("\n          \"version\":"   "\"" data["revision"]["version"] "\"")
                f.write("\n     },")    
                counter  = counter 
            else:
                counter  = counter
                pass
        f = open("Modstext.json", "a")
        f.write("\n  ]")
        f.close
    
    button1 = Button(text="Create",command=CreateJson)
    button1.pack()  
    
    f.close()

window = Tk()
window.geometry("300x1200")
button = Button(text="Open",command=openFile)
button.pack()
window.mainloop() ```

CodePudding user response:

Not sure we totally understand your question. Is this what you are looking for?

value = Checkbutton.get() print(value)

The return value will be a yes or a no, or a 1 or 0.

  • Related