Creating a game board with Tkinter

浪尽此生 提交于 2021-02-18 22:38:45

问题


I am trying to build a simple game of Connect Four with Python(2.7)

I have created a board, that consists of a simple multidimensional Python list.
My Board list looks like this:

board = [
    [_,_,_,_,_,_,_,_,_,_],
    [_,_,_,_,_,_,_,_,_,_],
    [_,_,_,_,_,_,_,_,_,_],
    [_,_,_,_,_,_,_,_,_,_],
    [_,_,_,_,_,_,_,_,_,_],
    [_,_,_,_,_,_,_,_,_,_],
    [_,_,_,_,O,_,_,_,_,_],
    [_,_,_,_,X,_,_,_,_,_],
    [_,_,_,_,X,O,_,_,_,_],
    [_,_,_,_,X,O,_,_,_,_],
]

Were X is Player1 and O is Player2 (or Computer).

Now, I have created some basic code for the GUI, like this:

# Connect 4 Game
import Tkinter

screen = Tkinter.Tk()
screen.title("My First Game")

#Create a board
board = Tkinter.Canvas(screen,width=500,height=500)
board.pack()

screen.mainloop()

Question: How can i create a visual representation of the board, so that for every list, there is a rectangle? Also, is there a way to detect, when a rectangle is clicked and replace the corresponding list value?


回答1:


I created a board of labels and color them according to which is clicked:

import Tkinter as tk

board = [ [None]*10 for _ in range(10) ]

counter = 0

root = tk.Tk()

def on_click(i,j,event):
    global counter
    color = "red" if counter%2 else "black"
    event.widget.config(bg=color)
    board[i][j] = color
    counter += 1


for i,row in enumerate(board):
    for j,column in enumerate(row):
        L = tk.Label(root,text='    ',bg='grey')
        L.grid(row=i,column=j)
        L.bind('<Button-1>',lambda e,i=i,j=j: on_click(i,j,e))

root.mainloop()

This doesn't do any validation (to make sure that the element clicked is at the bottom for example). It would also be much better with classes instead of global data, but that's an exercise for the interested coder :).




回答2:


You probably want to create a grid of Buttons. You can style them according to the values in board, and assign a callback that updates the board when clicked.



来源:https://stackoverflow.com/questions/14349526/creating-a-game-board-with-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!