python tkinter复选框设置并行运行

时间:2015-09-29 13:39:52

标签: python tkinter

我定义了两组Checkbox,两者都输出到一个单独的List。代码运行,正确打开一个带有两个Checkbox的窗口。但是,当我签入一套时,它也会检查另一套。有什么想法吗?

from Tkinter import *
root = Tk()

n2_hit = range (4)
n1_hit = range (4)

self = Frame()

self.underframe = Frame()

self.underframe.n2e  = Frame(self.underframe, bd = 2, relief = RIDGE)
c_n2_0 = Checkbutton (self.underframe.n2e, variable = n2_hit[0])
c_n2_0.pack (side=LEFT)
c_n2_1 = Checkbutton (self.underframe.n2e, variable = n2_hit[1])
c_n2_1.pack (side=LEFT)
c_n2_2 = Checkbutton (self.underframe.n2e, variable = n2_hit[2])
c_n2_2.pack (side=LEFT)
c_n2_3 = Checkbutton (self.underframe.n2e, variable = n2_hit[3])
c_n2_3.pack (side=LEFT)
self.underframe.n2e.pack (side=LEFT)

self.underframe.n1e  = Frame(self.underframe, bd = 2, relief = RIDGE)
c_n1_0 = Checkbutton (self.underframe.n1e, variable = n1_hit[0])
c_n1_0.pack (side=LEFT)
c_n1_1 = Checkbutton (self.underframe.n1e, variable = n1_hit[1])
c_n1_1.pack (side=LEFT)
c_n1_2 = Checkbutton (self.underframe.n1e, variable = n1_hit[2])
c_n1_2.pack (side=LEFT)
c_n1_3 = Checkbutton (self.underframe.n1e, variable = n1_hit[3])
c_n1_3.pack (side=LEFT)
self.underframe.n1e.pack (side=LEFT)

self.underframe.pack (side=TOP)

self.pack ()

2 个答案:

答案 0 :(得分:0)

我认为你应该阅读更多关于tkiner的信息,我认为你应该使用另一种编程范例,例如:面向对象编程(OOP)。

在这里,我提供了一个具有您想要的功能的代码:

    from tkinter import *
    class Checkbar(Frame):
       def __init__(self, parent=None, picks=[], side=LEFT, anchor=W):
          Frame.__init__(self, parent)
          self.vars = []
          for pick in picks:
             var = IntVar()
             chk = Checkbutton(self, text=pick, variable=var)
             chk.pack(side=side, anchor=anchor, expand=YES)
             self.vars.append(var)
       def state(self):
          return map((lambda var: var.get()), self.vars)



  if __name__ == '__main__':
           root = Tk()
           lng = Checkbar(root, ['op1', 'op2','op3' ])
           tgl = Checkbar(root, ['op_1','op_2'])
           lng.pack(side=TOP,  fill=X)
           tgl.pack(side=LEFT)
           lng.config(relief=GROOVE, bd=2)

           def allstates(): 
              print(list(lng.state()), list(tgl.state()))
           Button(root, text='Quit', command=root.quit).pack(side=RIGHT)
           Button(root, text='What are select??', command=allstates).pack(side=RIGHT)
           root.mainloop()

答案 1 :(得分:0)

检查按钮的variable属性需要设置为特殊tkinter变量之一StringVarIntVarBooleanVarDoubleVar。您的代码将它们设置为整数。您需要为每个检查按钮创建其中一个变量。