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

时间:2015-02-08 13:29:06

标签: python tkinter

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

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

课程可能不是全部选择,也不能只选择一个。 我的代码仅用于检查课程,但无法获取。代码如下所示:

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

1 个答案:

答案 0 :(得分:1)

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

例如,您可以使用Button来允许学生单击“确定”。当用户单击“确定”时,您可以检查当前检查了多少个检查按钮,并最终显示错误或警告消息,如果学生未检查至少2个主题(例如)。

您可以使用IntVar变量来检查是否检查了Checkbuttons

如果您不想在主窗口中创建主题选择器,则可以从Toplevel窗口小部件派生您的课程。

我将尝试给出一个具体的例子,以便您可以更清楚地了解我在说什么。

# 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。我直接打包Choose your school subjects中的self标签,该标签来自Toplevel。如果您不理解传递给packgrid方法的选项,您可以忽略它们,这对您的程序逻辑并不那么重要。
如果你不明白的话,请随意询问。