How to get the text of Checkbuttons?

2024/7/7 5:23:23

Checkbuttons gets generated dynamically and they are getting text from a python list. I need a logic for capturing selected checkbuttons text . As per my research everywhere they are returning the state of checkbox instead of text. Please help.

cb_list =['pencil','pen','book','bag','watch','glasses','passport','clothes','shoes','cap'] 
try:r = 0cl = 1for op in cb_list:cb = Checkbutton(checkbutton_frame, text=op, relief=RIDGE)cb.grid(row=r, column=cl, sticky="W")r = r + 1
except Exception as e:logging.basicConfig(filename=LOG_FILENAME, level=logging.ERROR)logging.error(e)# print (e)selected_item = Text(self, width=30, height=20, wrap=WORD)selected_item.grid(row=1, column=6, padx=20, pady=20, columnspan=2, sticky=E)display_button = Button(self, text='DISPLAY', command=display()convert_button.grid(row=1, column=8, padx=20, pady=20)
Answer

The idea is to associate one BooleanVar to each checkbutton and store them in a list cb_var. Then, to display the selected items, we just have to clear the display box (I have used a Listbox) and then loop simultaneously through cb_list and cb_var to determine which items are selected:

import tkinter as tkroot = tk.Tk()
checkbutton_frame = tk.Frame(root)
checkbutton_frame.grid(row=1, column=0)def display():# clear listboxselected_item.delete(0, 'end')# add selected items in listboxfor text, var in zip(cb_list, cb_var):if var.get():# the checkbutton is selectedselected_item.insert('end', text)cb_list = ['pencil','pen','book','bag','watch','glasses','passport','clothes','shoes','cap'] 
cb_var = []  # to store the variables associated to the checkbuttons
cl = 1
for r, op in enumerate(cb_list):var = tk.BooleanVar(root, False)cb = tk.Checkbutton(checkbutton_frame, variable=var, text=op, relief='ridge')cb.grid(row=r, column=cl, sticky="w")cb_var.append(var)selected_item = tk.Listbox(root, width=30, height=20)
selected_item.grid(row=1, column=6, padx=20, pady=20, columnspan=2, sticky='e')display_button = tk.Button(root, text='DISPLAY', command=display)
display_button.grid(row=1, column=8, padx=20, pady=20)root.mainloop()

enter image description here

EDIT: If you want to be able to change the list of items easily, you can use a function init_checkbuttons to create the checkbuttons from your list of items. This function does the following things:

  1. Destroy all previous checkbuttons
  2. Clear the listbox
  3. Create the new checkbuttons
  4. Change the command of the display button

You can notice that the display function now takes cb_list and cb_var in argument, so that you can change them.

import tkinter as tkroot = tk.Tk()
checkbutton_frame = tk.Frame(root)
checkbutton_frame.grid(row=1, column=0)def display(cb_list, cb_var):# clear listboxselected_item.delete(0, 'end')# add selected items in listboxfor text, var in zip(cb_list, cb_var):if var.get():# the checkbutton is selectedselected_item.insert('end', text)def init_checkbuttons(cb_list, cl=1):# destroy previous checkbuttons (assuming that checkbutton_frame only contains the checkbuttons)cbs = list(checkbutton_frame.children.values())for cb in cbs:cb.destroy()# clear listboxselected_item.delete(0, 'end')# create new checkbuttonscb_var = []  # to store the variables associated to the checkbuttonsfor r, op in enumerate(cb_list):var = tk.BooleanVar(root, False)cb = tk.Checkbutton(checkbutton_frame, variable=var, text=op, relief='ridge')cb.grid(row=r, column=cl, sticky="w")cb_var.append(var)# change display commanddisplay_button.configure(command=lambda: display(cb_list, cb_var))cb_list = ['pencil', 'pen', 'book', 'bag', 'watch', 'glasses', 'passport', 'clothes', 'shoes', 'cap']
cb_list2 = ['ball', 'table', 'bat']selected_item = tk.Listbox(root, width=30, height=20)
selected_item.grid(row=1, column=6, padx=20, pady=20, columnspan=2, sticky='e')display_button = tk.Button(root, text='DISPLAY')
display_button.grid(row=1, column=8, padx=20, pady=20)tk.Button(root, text='Change list', command=lambda: init_checkbuttons(cb_list2)).grid(row=2, column=8)init_checkbuttons(cb_list)
root.mainloop()
https://en.xdnf.cn/q/120435.html

Related Q&A

Working out an equation

Im trying to solve a differential equation numerically, and am writing an equation that will give me an array of the solution to each time point.import numpy as np import matplotlib.pylab as pltpi=np.p…

combine rows and add up value in dataframe

I got a dataframe(named table) with 6 columns labeled as [price1,price2,price3,time,type,volume]for type, I got Q and T, arranged like:QTQTTQNow I want to combine the rows with consecutive T and add up…

How to access a part of an element from a list?

import cv2 import os import glob import pandas as pd from pylibdmtx import pylibdmtx import xlsxwriter# co de for scanningimg_dir = "C:\\images" # Enter Directory of all images data_path = os…

How to get invisible data from website with BeautifulSoup

I need fiverr service delivery times but I could get just first packages(Basic) delivery time. How can I get second and third packages delivery time? Is there any chance I can get it without using Sel…

How to get rid of \n and in my json file

thanks for reading I am creating a json file as a result of an API that I am using. My issue is that the outcome gets has \h and in it and a .json file does not process the \n but keeps them, so the f…

Python code to calculate the maximal amount of baggage is allowed using recursive function

I am new to python and I have an assignment, I need to write a recursive function that takes two arguments (Weights, W), weights is the list of weights of baggage and W is the maximal weight a student …

How to flatten a nested dictionary? [duplicate]

This question already has answers here:Flatten nested dictionaries, compressing keys(32 answers)Closed 10 years ago.Is there a native function to flatten a nested dictionary to an output dictionary whe…

Find an element in a list of tuples in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…

print dictionary values which are inside a list in python

I am trying to print out just the dict values inside a list in python.car_object = {}cursor = self._db.execute(SELECT IDENT, MAKE, MODEL, DISPLACEMENT, POWER, LUXURY FROM CARS)for row in cursor:objectn…

Triangle of numbers on Python

Im asked to write a loop system that prints the following:0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0However, my script prints this:0 1…