mardi 23 novembre 2021

How to change states of Tkinter checkboxes when creating checkboxes with dictionary?

I'm making a program which gives the user a selection of checkboxes to select from. The checkboxes are being automatically created with a loop. I am able to detect which checkboxes have been ticked, but I'm unable to change the state of specific checkboxes by myself later on. Specifically, I want to remove all the ticks from the ticked checkboxes after a button is clicked, but more generally, I would like to know how to change the state of individual checkboxes. Here's a sample code:

import tkinter
from tkinter import *
tagsValue = {'Beef': 0, 'Fish': 0, 'Chicken': 0, 'Pork': 0, 'Lamb': 0, 'Egg': 0, 'Ham': 0}

def execute():
    my_text.delete('1.0', END)
    for tag in tagsValue:
        if tagsValue[tag].get() == '1':
            my_text.insert(INSERT, ('\n' + tag))

root = Tk()
root.title('User Selection')
root.geometry("300x300")
my_button = Button(root, text ="Submit",command = execute)
my_text = Text(root)

for tag in list(tagsValue):
    tagsValue[tag] = Variable()
    l = Checkbutton(root,justify=LEFT,width=8, text=tag, variable=tagsValue[tag])
    l.deselect()
    l.pack()

my_button.pack()
my_text.pack()
root.mainloop()

I have tried using things like tagsValue['Ham'] = '0' and tagsValue['Ham'] = 0 before root.mainloop() but those do not work. I am aware of using ['state'] to change the state of checkboxes, but since my checkboxes are not named, I can't use it. (I can't name the checkboxes individually because I have many many many checkboxes). So how can I change the state of the checkboxes?




Aucun commentaire:

Enregistrer un commentaire