生成一堆tkinter检查按钮,并立即读取所有这些单选按钮的状态

时间:2016-02-03 15:07:21

标签: python-2.7 tkinter

我有一个tkinter类,它将一些数据读入几个列表。从现在开始,我创建了一个用于创建支票按钮的字典。

我正在尝试在新窗口()中创建这些检查按钮,并使用按钮提交并阅读其中的stutus。我希望这些数据能够处理。

    def get_data(self):
        self.flags = ["one","two","three", "four"]
        self.tests = ["Jack","Queen","King","Ace"]
        self.value = [11,12,13,1]
        self.dict1 = {k:v for k,v in enumerate(self.flags,1)}
    def get_status(self):
        self.selectWindow = Toplevel(root)
        self.selectWindow.title("Select Test Cases")
        Submit_btn = Button(selectWindow, text="Submit", command=read_status )
        for testcase in self.dict1:
            self.dict1[testcase] = Variable()
            l = Checkbutton(self.selectWindow,text=self.dict1[testcase], variable=self.dict1[testcase])
            l.pack()
    def read_status(self):
        pass

从这里开始,我无法继续阅读检查按钮的状态并检查它们。我需要这些数据用于测试的进一步处理(这里给出的实际列表我还有更多)。怎么解决?请告诉我。

2 个答案:

答案 0 :(得分:1)

Checkbutton具有内置command功能,可以解决此问题。每次按下调用该功能的按钮,您都可以打印出按钮的值(0,1)

def get_data(self):
    self.flags = ["one","two","three", "four"]
    self.tests = ["Jack","Queen","King","Ace"]
    self.value = [11,12,13,1]
    self.dict1 = {k:v for k,v in enumerate(self.flags,1)}
def get_status(self):
    self.selectWindow = Toplevel(self)
    self.selectWindow.title("Select Test Cases")
    self.get_data()
    Submit_btn = Button(self.selectWindow, text="Submit", command=read_status ) # This button should be packed
    Submit_btn.pack()
    for testcase in self.dict1:
        self.dict1[testcase] = Variable()
        l = Checkbutton(self.selectWindow,text=self.dict1[testcase], variable=self.dict1[testcase], command=self.read_status) # Note the command
        l.pack()
    self.selectWindow.mainloop()

# Here comes the interesting part

def read_status(self):
    for i,j in self.dict1.iteritems():
        print j.get()

答案 1 :(得分:0)

您忘记使用selfpack方法:

Submit_btn = Button(self.selectWindow, text="Submit", command=self.read_status )
Submit_btn.pack()

Checkbutton的状态为(0, 1),因此请使用IntVar()来检查州:

...
self.dict1[testcase] = IntVar()
...

然后使用IntVar get方法:

def read_status(self):
    for v in self.dict1:
        print self.dict1[v].get()