Dafni V.
Dafni V.

Reputation: 35

How can I get the value of a Label that is checked by a Checkbutton

I'm trying to run a project for my university Computer Science class that is the process of choosing lessons in the terms during a student's studies. I have used Checkbuttons and Labels to select the lessons.

Though, the problem is that I need to access the lessons(written in the Labels) that have been chosen by the student(via the Checkbuttons) so as to put some restrictions. Let's say for instance to choose only 2 lab lessons in a term.

The lessons may not be all chosen and also cannot choose only one. My code runs for only checking the lessons, but cannot get them. The code looks like this:

from Tkinter import *


class CreatingWindowForEachLesson:
    selected = []  # lessons chosen

    def __init__(self, root, d):
        self.v = StringVar()
        self.frame1 = Frame(root)  # TITLE OF THE LESSON
        self.frame1.pack(side=LEFT, anchor="nw")
        self.frame3 = Frame(root)  # for the CHECKBUTTONS
        self.frame3.pack(side=LEFT, anchor="nw")
        self.d = d

        for i in self.d:
            self.w1 = Label(self.frame1, text=str(i))
            self.w1.grid()
            self.w1.config()
            self.w3 = Checkbutton(self.frame3, text="Choose")
            self.w3.pack()
            self.w3.config()

    def SelectedLessons(self):
        if CreatingWindowForEachLesson.check == 0:
            print "NONE CHOSEN!"
        else:
            pass


root = Tk()
tpA7 = [........]
myLesson = CreatingWindowForEachLesson(root, tpA7)
root.mainloop()

Upvotes: 0

Views: 71

Answers (1)

nbro
nbro

Reputation: 15837

In this case you don't even need labels. Check buttons have a property called text, which represents the text next to the check button.

You can for example have a Button which allows the student to click ok. When the user clicks ok, you can check how many check buttons are currently checked, and eventually show an error or warning message, if the student has not checked at least 2 subjects (for example).

You can use IntVar variables to check if the Checkbuttons are or not checked.

If you don't want to make this subject chooser the main window, you can derive your class from a Toplevel widget.

I will try to give a concrete example, so that you can have a clearer idea of what I am talking about.

# subjects chooser

import Tkinter as tk


class SubjectsChooser(tk.Toplevel):

    def __init__(self, parent):
        tk.Toplevel.__init__(self, parent)
        self.parent = parent
        self.prompt = tk.Label(self.parent, text='Choose your school subjects',
                               border=1, relief='groove', padx=10, pady=10)
        self.prompt.pack(fill='both', padx=5, pady=5)

        self.top = tk.Frame(self.parent)

        # Using IntVar objects to save the state of the Checkbuttons
        # I will associate the property variable of each checkbutton
        # with the corrensponding IntVar object
        self.english_value = tk.IntVar(self.top)
        self.maths_value = tk.IntVar(self.top)
        self.sports_value = tk.IntVar(self.top)

        # I am saving the IntVar references in a list
        # in order to iterate through them easily, 
        # when we need to check their values later!
        self.vars = [self.english_value, self.maths_value, self.sports_value]

        # Note I am associating the property 'variable' with self.english_value
        # which is a IntVar object
        # I am using this variables to check then the state of the checkbuttons
        # state: (checked=1, unchecked=0)
        self.english = tk.Checkbutton(self.top, text='English', 
                                     variable=self.english_value)
        self.english.grid(row=0, column=0, sticky='nsw')
        self.maths = tk.Checkbutton(self.top, text='Maths',
                                   variable=self.maths_value)
        self.maths.grid(row=1, column=0, sticky='nsw')
        self.sports = tk.Checkbutton(self.top, text='Sports',
                                    variable=self.sports_value)
        self.sports.grid(row=2, column=0, sticky='nsw')          
        self.top.pack(expand=1, fill='both')
        self.subjects = [self.english, self.maths, self.sports]

        self.bottom = tk.Frame(self.parent, border=1, relief='groove')
        # not I am associating self.choose as the command of self.ok
        self.ok = tk.Button(self.bottom, text='Confirm',
                           command=self.choose)
        self.ok.pack(side='right', padx=10, pady=5)
        self.bottom.pack(fill='both', padx=5, pady=5)

    def choose(self):
        # Needed to check how many checkbuttons are checked
        # Remember, the state of the check buttons is stored in
        # their corresponding IntVar variable
        # Actually, I could simply check the length of 'indices'.
        total_checked = 0
        indices = []  # will hold the indices of the checked subjects
        for index, intvar in enumerate(self.vars):
            if intvar.get() == 1: 
                total_checked += 1
                indices.append(index)
        if total_checked <= 1:
            print 'You have to choose at least 2 subjects!'
        else:
            for i in indices:
                # using the method 'cget' to get the 'text' property
                # of the checked check buttons
                print 'You have choosen', self.subjects[i].cget('text') 


if __name__ == '__main__': # in case this is launched as main app
    root = tk.Tk()
    schooser = SubjectsChooser(root)
    root.mainloop()

I am using 2 frames, one to regroup the check buttons and 1 for the button Confirm. I am packing directly the label Choose your school subjects in self, which derives from Toplevel. If you don't understand the options passed to pack and grid methods, you can simply ignore them, that's not so important to the logic of your program.
Feel free to ask, if you don't understand something.

Upvotes: 1

Related Questions