user3791849
user3791849

Reputation: 3

Python:How to get correct reference of button in multiple assignment with for loops?

I'm a beginner programmer and I wanted to learn by a game. I'm trying to make a battleship game with the user clicking on buttons(made using Tkinter) to place battle ships around the board. When I click on buttons I get an error saying the below. How to get the right button int the dictionary choises = {}? The error says:

Traceback (most recent call last): File "C:\Python Codes\Battleship.py", line 29, in choice() TypeError: choice() takes exactly 2 arguments (0 given)

Here is the code I used:

from Tkinter import *
import Tkinter as tk
screen = tk.Tk(className = "Battle Ship Game" )
screen.geometry("300x300")
screen["bg"] = "white"

line1= list()

def choice(x,y) :
    global choises
    choises = {}

    choises[x] = y
    print choises

def buildaboard1(screen) :
    x = 20
    for n in range(0,10) :
        y = 20
        for i in range(0,10) :
            line1.append(tk.Button(screen ))
            line1[-1]["command"] = (lambda n : choice (x , y))
            line1[-1].place( x = x , y = y+20 , height = 20 , width = 20 )
            y = y+20
        x = x +20


buildaboard1(screen)
choice()
screen.mainloop()

Upvotes: 0

Views: 146

Answers (1)

furas
furas

Reputation: 142631

This way Tkinter assign values from x and y to a and b at once.
And choice() will can use it when you press button.

line1[-1]["command"] = (lambda a=x, b=y: choice (a , b))

This way Button want to get values from x and y when you click it but then x and y don't exist.

line1[-1]["command"] = (lambda: choice (x , y))

Upvotes: 1

Related Questions