如何获取由Checkbutton选中的标签的值

2024-04-26 11:35:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着为我的大学计算机科学课做一个项目,这个项目是在学生学习期间选择课程的过程。 我用CheckbuttonsLabels来选择课程。你知道吗

不过,问题是我需要访问学生(通过Checkbuttons)选择的课程(写在Labels),以便设置一些限制。比如说,一学期只选两门实验课。你知道吗

课程不一定都选,也不能只选一门。 我的代码只用于检查课程,但无法获取它们。代码如下所示:

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

Tags: 项目代码selflabelsdefroot学生pack
1条回答
网友
1楼 · 发布于 2024-04-26 11:35:23

在这种情况下,你甚至不需要标签。Check按钮有一个名为text的属性,它表示Check按钮旁边的文本。你知道吗

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

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

如果您不想让这个主题选择器成为主窗口,您可以从^{}小部件派生类。你知道吗

我将试着举一个具体的例子,以便你们能更清楚地了解我在说什么。你知道吗

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

我使用了两个帧,一个用于重新组合复选按钮,一个用于按钮Confirm。我直接将标签Choose your school subjects打包到self,它派生自Toplevel。如果您不了解传递给packgrid方法的选项,您可以忽略它们,这对程序的逻辑并不重要。
如果你不明白什么,尽管问。你知道吗

相关问题 更多 >