2016-03-01 39 views
0

我有一個問題,我可以壓縮此代碼(我已告訴我可以)但沒有得到任何幫助,這樣做,並沒有一個線索如何做到這一點。壓縮我的類爲我的tkinter窗口按鈕

試過把它放到for循環中,但我想要一個3x3的按鈕網格,中間的按鈕是一個列表框,而不是按鈕的死點。

我環顧四周,一小時後,我沒有回答。

在這裏,我嘗試追加每個按鈕到一個列表中,並將它們包裝在一個for循環中,但它有可能在for循環中完成它們並且在完成後單獨打包Listbox?

class MatchGame(Toplevel): 
    def __init__(self,master): 
     self.fr=Toplevel(master) 
     self.GameFrame=Frame(self.fr) 
     self.AllButtons=[] 
     self.AllButtons.append(Button(self.GameFrame,bg="red",height=5,width=15,text="")) 
     self.AllButtons.append(Button(self.GameFrame,bg="green",height=5,width=15,text="")) 
     self.AllButtons.append(Button(self.GameFrame,bg="dark blue",height=5,width=15,text="")) 
     self.AllButtons.append(Button(self.GameFrame,bg="turquoise",height=5,width=15,text="")) 
     self.AllButtons.append(Listbox(self.GameFrame,bg="grey",height=5,width=15)) 
     self.AllButtons.append(Button(self.GameFrame,bg="yellow",height=5,width=15,text="")) 
     self.AllButtons.append(Button(self.GameFrame,bg="pink",height=5,width=15,text="")) 
     self.AllButtons.append(Button(self.GameFrame,bg="orange",height=5,width=15,text="")) 
     self.AllButtons.append(Button(self.GameFrame,bg="purple",height=5,width=15,text="")) 
     for x in range(0,len(self.AllButtons)): 
      AllButtons[x].grid(row=int(round(((x+1)/3)+0.5)),column=x%3) 
     self.GameFrame.grid(row=0,column=0) 
     Quit=Button(self.fr, text="Destroy This Game", bg="orange",command=self.fr.destroy) 
     Quit.grid(row=1,column=0) 

它需要有單獨的顏色,相同的大小和所有,但我不知道該怎麼做。我對課程相當陌生,而且我無法解決我的生活如何使用緊湊的代碼製作此窗口(每個對象不是9行,然後將它們全部打包)。

回答

1

如果您想要動態地創建一個3x3的按鈕網格。那麼嵌套的for循環似乎是你最好的選擇。

例子:

import tkinter as tk 

root = tk.Tk() 
# List of your colours 
COLOURS = [['red', 'green', 'dark blue'], 
      ['turquoise', 'grey', 'yellow'], 
      ['pink', 'orange', 'purple']] 

# Nested for-loop for a 3x3 grid 
for x in range(3): 
    for y in range(3):   
     if x == 1 and y == 1: # If statement for the Listbox 
      tk.Listbox(root, bg = COLOURS[x][y], height=5, width=15).grid(row = x, column = y) 
     else: 
      tk.Button(root, bg = COLOURS[x][y], height=5, width=15).grid(row = x, column = y) 

root.mainloop() 
+0

謝謝,我可以聯繫你,如果我遇到問題與建立的命令? –

+1

歡迎您。雖然我不能答應立即回答。 –

相關問題