如何获取由 Checkbutton 检查的 Label 的值

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

我正在尝试运行我大学计算机科学的一个项目class,这是在学生学习期间选择课程的过程. 我用 CheckbuttonsLabels 来 select 课程。

不过,问题是我需要访问学生(通过 Checkbuttons)选择的课程(写在 Labels 中)以设置一些限制。比方说一个学期只选择 2 节实验课。

课程不能全部选,也不能只选一门。 我的代码 运行s 只能查看课程,但无法获取。代码如下所示:

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()

在这种情况下,您甚至不需要标签。复选按钮有一个名为 text 的 属性,代表复选按钮旁边的文本。

例如,您可以有一个 Button 允许学生单击“确定”。当用户单击确定时,您可以检查当前检查了多少个检查按钮,如果学生没有检查至少 2 个科目(例如),最终会显示错误或警告消息。

您可以使用 IntVar 变量来检查 Checkbuttons 是否被选中。

如果您不想让这个 主题选择器 成为主要 window,您可以从 Toplevel 派生您的 class小部件。

我会尽量举一个具体的例子,让大家更清楚地了解我在说什么。

# 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()

我正在使用 2 个框架,一个用于重新组合复选按钮,另一个用于按钮 Confirm。我是直接打包self中的标签Choose your school subjects,它来源于Toplevel。如果您不理解传递给 packgrid 方法的选项,您可以简单地忽略它们,这对您的程序逻辑来说并不那么重要。
有不懂的地方尽管问。