2017-01-15 29 views
-1

好的,所以我有这个代码会在tkinter窗口中生成一个按钮的网格,但我没有办法将网格中的按钮分开。说如果我想让网格位置(4,4)的按钮变成蓝色,我该怎么做?我需要使用列表吗?我相信这是一个快速解决方法,在此先感谢。Python,tkinter:如何识别网格中物品的位置?

def game(width,height): 

    for x in range(width): 

     for y in range(height): 

      square = Button(gameWindow) 
      square.grid(column = x, row = (y + 1), sticky = (N+S+E+W)) 

    for x in range(width): 

     Grid.columnconfigure(gameWindow, x, weight = 1) 

    for y in range(height): 

     Grid.rowconfigure(gameWindow, (y + 1), weight = 1) 

    gameWindow.mainloop() 

game(8,8) 

回答

0

square对象列表的列表,那么你可以通过x的索引引用的每个对象和y

from Tkinter import * 

def game(width,height): 
    for x in range(width): 
     # fill a row in the list 
     squares.append([None] * height) 

     for y in range(height): 
      squares[-1][y] = Button(gameWindow) 
      squares[-1][y].grid(column = x, row = (y + 1), sticky = (N+S+E+W)) 

    for x in range(width): 

     Grid.columnconfigure(gameWindow, x, weight = 1) 

    for y in range(height): 

     Grid.rowconfigure(gameWindow, (y + 1), weight = 1) 

squares = [] 
gameWindow = Tk() 

game(8,8) 

# change color of square in x=3, y=4 
squares[3][4].configure(bg='blue') 

gameWindow.mainloop() 
+0

你能给出如何做到这一点的例子吗?我不熟悉名单。谢谢 –

+0

用一个例子编辑 –

+0

它的工作!谢谢你的帮助! –

0

建议: 如果你正在考虑的视觉区分网格,除了mike.k的建议之外,还可以使用Button的背景,activebackground和图像选项。 activebackground选项在鼠标指针所在的位置以及易于实现的地方给出了对比。此外,你可以设计一个聪明的系统来显示与网格系统相关的颜色。

修订你的代码演示实现:

from tkinter import * 

def game(width,height,gameWindow): 

    colors = ['green', 'blue', 'yellow', 'white', 
       'black', 'brown', 'purple', 'cyan'] 

    for x in range(width): 

     for y in range(height): 

      color = colors[y] 
      print('color = {}'.format(color)) 
      square = Button(gameWindow, background=color, 
          activebackground='gold') 
      square.grid(column = x, row = (y + 1), sticky = (N+S+E+W)) 

    for x in range(width): 
     Grid.columnconfigure(gameWindow, x, weight = 1) 

    for y in range(height): 
     Grid.rowconfigure(gameWindow, (y + 1), weight = 1) 

gameWindow = Tk() 
game(8,8, gameWindow) 
gameWindow.mainloop() 

成果从代码enter image description here