1

I wanted to create a game called "battleship". For this, I have to allow the user to place his ships.
I wanted to try this by allowing the user to color a field where the ship has to be placed. My problem is, that I have created 15 x 15 variables in a list by using 2 for loops. Is there actually a command possibility to for example get the row and the column of the grid, because this part, for example, will always give me the last i and the last j I have asked for. Otherwise, I would have to create 225 lines, by mentioning the i and j when using lambda.

self.ship[i][j] = tk.Button(root, text="", padx=30, pady=20, command=lambda:color(i,j))
self.ship[i][j].grid(row=i, column=j)

Lafexlos
  • 7,618
  • 5
  • 38
  • 53
tim123
  • 15
  • 2
  • the full code I cannot post, because it is actually a homework , is it k for posting a part of the code, like the function? – tim123 Jan 29 '20 at 09:00
  • Since this question closed before I had time to answer, please have a look at my solution for your problem: [tkinter creating buttons in for loop passing command arguments](https://stackoverflow.com/a/59964520/2902996) – Joel Jan 29 '20 at 09:58
  • I am very grateful for your post, I also have tried it to use. I will look today evening, what I can use of your code, since you are using something I have not learned yet. – tim123 Jan 29 '20 at 10:03
  • Thank you, don't hesistate to ask me any questions if you need clarification. Essentially, if you do not want the responsive stuff, you can just do `btn["command"] = lambda btn=btn: click(btn)` where `click(btn)` is the function. This will create a binding scope from the button to the function itself. – Joel Jan 29 '20 at 10:07

1 Answers1

0

I hope the following code gives you a good starting point to go ahead with your game.

I have used the same approach of using two for loops to create a 10x10 grid of buttons. Then i have used an click event callback to get the widget that is being clicked upon and then make the selected button blue or perform any operation on that widget.

import tkinter as tk

class Game:

    def __init__(self, master):
        self.master = master
        self.master.resizable(0,0)
        # row index
        for row in range(10):
            # col index
            for col in range(10):
                self.button = tk.Button(master, width=1, height=1)
                self.button.grid(row=row, column=col, padx=8, pady=8, ipadx=10, ipady=4)
                self.button.bind("<Button-1>", self.callback)
        master.mainloop()

    def callback(self, event):
        # get the clicked button
        clicked_btn = event.widget
        btn_at_row_col = clicked_btn.config(bg='blue', state='disabled')

if __name__ == "__main__":
    root = tk.Tk()
    Game(root)  

The output GUI:

This will render a 10x10 grid of buttons.

Then you can click on any button which makes it blue.

Somraj Chowdhury
  • 983
  • 1
  • 6
  • 14