Home > Blockchain >  deselect the checkbox using the listbox item in tkinter python and print the current item of listbox
deselect the checkbox using the listbox item in tkinter python and print the current item of listbox

Time:09-17

I have two checkbox Pass and FAIL I am parsing the csv for column1 and adding the two checkbox .

        X = 100
        Y = 71
        for item in column1[key]:
            if item != '':
                listbox.insert('end', item)
                chk_state1 = tk.IntVar()
                tk.Checkbutton(self.root, text="PASS",variable=chk_state1,font=("Arial Bold", 8),).place(x=X,y=Y)
                chk_state2 = tk.IntVar()
                tk.Checkbutton(self.root, text="FAIL",variable=chk_state2,font=("Arial Bold", 8),).place(x=X 80,y=Y)
                Y = Y  20
  1. How to know which row of column1 Checkbox is selected
  2. At a time only one checkbox should be selected

Any inputs will be helpful thanks in advance

CodePudding user response:

For item 1, use a dictionary (item names as the keys) to hold the created tkinter IntVars. Then you can get the checked state for each item by going through the dictionary later.

For item 2, you can use Radiobutton instead of Checkbutton.

        X = 100
        Y = 71

        myfont = ('Arial Bold', 8)
        self.cblist = {}
        for item in column1[key]:
            if item != '':
                listbox.insert('end', item)
                chk_state = tk.IntVar(value=0)
                tk.Radiobutton(self.root, text='PASS', variable=chk_state, value=1, font=myfont).place(x=X, y=Y)
                tk.Radiobutton(self.root, text='FAIL', variable=chk_state, value=0, font=myfont).place(x=X 80, y=Y)
                self.cblist[item] = chk_state
                Y  = 22

        tk.Button(self.root, text='Check', command=self.check).place(x=X, y=Y 10)

    ...

    def check(self):
        result = ('Fail', 'Pass')
        print(', '.join(f'{item}:{result[var.get()]}' for item, var in self.cblist.items()))

Note that I have added a button to print out the selected state for each item.

  • Related