2013-03-02 52 views
0

在編碼tkinter複選框時需要一些幫助。 我有一個檢查按鈕,如果我選擇,它將啓用許多其他複選框。下面是選擇第一個複選框tkinter複選框

def enable_(): 
    # Global variables 
    global var 
    # If Single test 
    if (var.get()==1): 
     Label (text='Select The Test To Be Executed').grid(row=7,column=1) 
     L11 = Label().grid(row=9,column=1) 
     row_me =9 
     col_me =0 
     test_name_backup = test_name 
     for checkBoxName in test_name: 
      row_me = row_me+1 
      chk_bx = Checkbutton(root, text=checkBoxName, variable =checkBoxName, \ 
          onvalue = 1, offvalue = 0, height=1, command=box_select(checkBoxName), \ 
          width = 20) 
      chk_bx.grid(row = row_me, column = col_me) 
      if (row_me == 20): 
       row_me = 9 
       col_me = col_me+1 

後的功能我有兩個問題在這裏。

  1. 如何刪除動態創建的複選框(chk_bx)我的意思是,如果我選擇初始複選框它將使許多其他箱,如果我取消第一個複選框它應該刪除最初創建的盒子?

  2. 我將如何從動態創建的框中選擇「選定/不是」的值?

+1

幾個意見:'L11'是'None'因爲這是'.grid'返回的內容。您創建Checkbutton時執行Checkbutton命令...您可能希望'lambda name = checkBoxName:box_select(name)' – mgilson 2013-03-02 15:34:19

+0

您不應該使用'var'作爲變量名稱...也不應該使用全局變量。您可以將該變量傳遞給該函數。 – 2013-03-02 17:02:52

回答

1

1.如何刪除動態創建的複選框?

只是所有checkbuttons添加到列表中,這樣在需要的時候你可以叫他們destroy()

def remove_checkbuttons(): 
    # Remove the checkbuttons you want 
    for chk_bx in checkbuttons: 
     chk_bx.destroy() 

def create_checkbutton(name): 
    return Checkbutton(root, text=name, command=lambda: box_select(name), 
         onvalue=1, offvalue=0, height=1, width=20) 

#... 
checkbuttons = [create_checkbutton(name) for name in test_name] 

2.我將如何得到動態creaed框中的值「選擇/不」 ?

你必須創建一個Tkinter的IntVar,用於存儲取決於checkbutton是否選擇不onvalueoffvalue。您還需要保持該對象的軌道,但沒有必要建立一個新的列表,因爲你可以將它們連接到相應的checkbutton:

def printcheckbuttons(): 
    for chk_bx in checkbuttons: 
     print chk_bx.var.get() 

def create_checkbutton(name): 
    var = IntVar() 
    cb = Checkbutton(root, variable=var, ...) 
    cb.var = var 
    return cb 
+0

在def printcheckbuttons()中: 我該如何打印哪個盒子被選中? 爲chk_bx在checkbuttons: \t \t如果(chk_bx.var.get()== 1): 我想BR打印checkbutton文本名稱 – 2013-03-03 12:15:51

+0

使用['cget'](http://effbot.org/tkinterbook /widget.htm#Tkinter.Widget.cget-method):'print chk_bx.cget('text')' – 2013-03-03 14:50:05

+0

that helps .. thanks – 2013-03-04 07:46:24

相關問題