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

Time:11-24

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?

CodePudding user response:

After the for loop, all values of tagsValue will be instances of Variable. So you can use, for example, tagsValue['Ham'].set('0') to change the state of checkbutton for Ham.

If you want to clear all ticks using a button, do as below:

def clear():
    for var in tagsValue.values():
        var.set('0')
...

clear_button = Button(root, text='Clear', command=clear)
clear_button.pack()
...

As @Bryan said in the comment, use specific StringVar or IntVar instead of generic Variable in general.

  • Related