Instead of overwriting the same variable, cb
, try using an iterable type such as dict
ionary. You should also need to be attaching the value of Checkbutton
to a tkinter variable class, such as BooleanVar
, in order to easily track its status & value.
The code below produces a GUI that re-writes Text
each time a Checkbutton
is selected. It first populates a dictionary, cbs
, with items from a list, cb_list
, as keys and tk.Checkbutton
objects as the values.
Checkbutton
objects are so that each is attached to a special object, Tkinter Variable class, BooleanVar
, which has a get
method that returns the Checkbutton
it is attached to’s current value when called. In this case, each Checkbutton
holds True
if checked, and False
if unchecked as its value.
Each Checkbutton
is also attached to a method, update_text
, which is called when any of the Checkbutton
is pressed. In that method for every Checkbutton
in cbs
, it first checks if the Checkbutton
has True
value, if so it appends its text
to a _string
. After this has been done for all Checkbuttons
, the method then proceeds as first delete
ing the entire text in the Text
widget, then it puts _string
to the Text
.
The code:
import tkinter as tk
def update_text():
global cbs
_string = ''
for name, checkbutton in cbs.items():
if checkbutton.var.get():
_string += checkbutton['text'] + '\n'
text.delete('1.0', 'end')
text.insert('1.0', _string)
if __name__ == '__main__':
root = tk.Tk()
text = tk.Text(root)
cb_list =['pencil','pen','book','bag','watch','glasses','passport',
'clothes','shoes','cap']
cbs = dict()
for i, value in enumerate(cb_list):
cbs[value] = tk.Checkbutton(root, text=value, onvalue=True,
offvalue=False, command=update_text)
cbs[value].var = tk.BooleanVar(root, value=False)
cbs[value]['variable'] = cbs[value].var
cbs[value].grid(row=i, column=0)
text.grid()
root.mainloop()
text
is an option to Checkbutton
widget, which means you can get its value using cget
(widget.cget('option')
) or simply widget['option']
.
1
solved How to get the text of Checkbuttons?