Python Forum

Full Version: Create a set of checkbutton widgets and refer to every one of them individually?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am a teacher. Using Tkinter and Openpyxl I need to code a graphical user interface so I could click on a student's name “linked” with a checkbutton square and display his/her marks (saved on a “.xlsx” file) whenever his/her checkbutton is active. How can I create a set of widgets/checkbuttons that I can refer individually later on? My code fails.



# -*- coding: utf-8 -*-
    from tkinter import *
    import openpyxl

    wb = openpyxl.load_workbook('marks.xlsx', data_only=True)
    sheet =

    names_and_rows = {}

    for i in range(2, sheet.max_row + 1):
            name = sheet.cell(row=i, column=1).value
            names_and_rows[name] = i

    root = Tk()
    root.title("Student's marks")

    students_names = Frame(root, bd=1, relief="solid")

    student_marks = Frame(root, bd=1, relief="solid")

    message = Label(student_marks, text="You still haven't checked on a 
        ny student's name")

    def get_marks(v):
        marks = ""
        for i in range(2, sheet.max_column + 1):
            information = str(sheet.cell(row=1, column=i).value) + ": " 
                + str(sheet.cell(row=v, column=i).value) + "\n"
            marks = marks + information
        if (v.get() == 1):
            message.config(text="You still haven't checked on any 
                student's name")

    list_of_widgets = []

    for k, v in names_and_rows.items():
        square = Checkbutton(students_names, variable=v, onvalue=1, 
            offvalue=0, text=k, command=lambda: get_marks(v))

Quote:so I could click on a student's name “linked” with a checkbutton square and display his/her marks
This example that I found on the web long ago, shows how to associate a button with a name in a second list. You could also use a dictionary.
import tkinter as tk     # Python3

def cb_checked():
    # remove text from label
    label['text'] = ''
    for ctr, int_var in enumerate(cb_intvar):
        if int_var.get():     ## IntVar not zero==checked
            label['text'] += '%s is checked' % cb_list[ctr] + '\n'

root = tk.Tk()

cb_list = [

# list of IntVar for each button
cb_intvar = []
for this_row, text in enumerate(cb_list):
    tk.Checkbutton(root, text=text,
                     command=cb_checked).grid(row=this_row, column=0, sticky='w')

label = tk.Label(root, width=20)
label.grid(row=20, column=0, sticky='w')

# you can preset check buttons (1=checked, 0=unchecked)
# show what is initially checked