2014-12-07 83 views
1

我正在爲涉及python和tkinter的計算機科學類開發一個項目。我正在努力打造一款功能齊全的大富翁遊戲,並且它的進展順利。我終於碰到了一個我似乎無法克服的障礙。我試圖做一個接口來抵押用戶的屬性,我想用tkinter checkbuttons來獲得用戶輸入,然後抵押所有被檢查的屬性。這裏是類的我所做的片段:使用未知量的複選框創建窗口 - Python/tkinter

from tkinter import * 

class Mortgager(Tk): 
    def __init__(self,coorder): # 'coorder' is a class that coordinates all of the 
     self.coorder = coorder  # other classes together 

     Tk.__init__(self,className='Mortgager') 
     self.title('Mortgaging') 

     self.cbuttons = [] 
     self.intvars = [] 
     for prop in coorder.active_player.properties: # iterate through player's currently owned properties 
      if not prop.mortgaged: 
       self.intvars.append(IntVar(self,0)) 
       self.cbuttons.append(Checkbutton(self, 
               variable=self.intvars[-1],text=prop.get_name(), 
               # Most recent intvar, method returns name of property 

               command=self.update_cash_onscreen) 
               #### Not sure what to do here... 
       self.cbuttons[-1].var = self.intvars[-1] 
       self.cbuttons[-1].text = prop.get_name() 
     i = 0 
     for cbutton in self.cbuttons: # Every three properties, new column 
      cbutton.grid(column=i//3,row=i%3,sticky=W, 
         padx=5,pady=5) 
      i += 1 
     # Haven't finished the rest of the class... 

我的問題是:如何創建checkbuttons任意數量的,然後告訴它checkbuttons已被點擊「在路上」更新某種Label顯示當前的抵押金額,StringVar或類似的東西,然後做一些與總金額?

在此先感謝!

回答

1

我挺不理解你的代碼,但如果你想在一個列表標籤創建n個checkbuttons「ctrls監視」試試這個

# if ctrls is a list of all lables to your checkboxes 
# i is the count and j is the text of label 
for i,j in enumerate(ctrls): #what ever loop you want 
    var = IntVar() 
    c = Checkbutton(self.master,text=j,variable=var) 
    boxes.append([j.strip(),var,c]) 

後,如果您要檢查哪些按鈕被檢查

for i in boxes: 
    if i[1].get()==0: 
     #do what ever you want 
     i[2].destroy()