2016-03-01 28 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

欢迎您。虽然我不能答应立即回答。 –

相关问题